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 index;
48pub mod package;
49pub mod syntax;
50pub mod testing;
51pub use tinymist_analysis::{stats::GLOBAL_STATS, ty, upstream};
52
53/// The physical position in a document.
54pub type FramePosition = typst::introspection::PagedPosition;
55
56mod adt;
57mod lsp_typst_boundary;
58mod prelude;
59
60mod bib;
61mod check;
62mod code_action;
63mod code_context;
64mod code_lens;
65mod color_presentation;
66mod completion;
67mod diagnostics;
68mod document_color;
69mod document_highlight;
70mod document_link;
71mod document_metrics;
72mod document_symbol;
73mod folding_range;
74mod goto_declaration;
75mod goto_definition;
76mod hover;
77mod inlay_hint;
78mod jump;
79mod on_enter;
80mod prepare_rename;
81mod references;
82mod rename;
83mod selection_range;
84mod semantic_tokens_delta;
85mod semantic_tokens_full;
86mod signature_help;
87mod symbol;
88mod will_rename_files;
89mod workspace_label;
90
91use typst::syntax::Source;
92
93use tinymist_analysis::{adt::interner::Interned, log_debug_ct};
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
120mod polymorphic {
121    use completion::CompletionList;
122    use lsp_types::TextEdit;
123    use serde::{Deserialize, Serialize};
124    use tinymist_project::ProjectTask;
125    use typst::foundations::Dict;
126
127    use super::prelude::*;
128    use super::*;
129
130    /// A request to run an export task.
131    #[derive(Debug, Clone)]
132    pub struct OnExportRequest {
133        /// The path of the document to export.
134        pub path: PathBuf,
135        /// The export task to run.
136        pub task: ProjectTask,
137        /// Whether to write to file.
138        pub write: bool,
139        /// Whether to open the exported file(s) after the export is done.
140        pub open: bool,
141    }
142
143    /// A request to run an export markdown task.
144    #[derive(Debug, Clone)]
145    pub struct OnExportMdRequest {
146        /// The path of the document to export.
147        pub path: PathBuf,
148        /// The processor package to use for the export.
149        pub processor: Option<String>,
150        /// The export task to run.
151        pub task: ProjectTask,
152        /// Whether to write to file.
153        pub write: bool,
154        /// Whether to open the exported file(s) after the export is done.
155        pub open: bool,
156    }
157
158    /// The response to an export request.
159    #[derive(Debug, Clone, Serialize, Deserialize)]
160    #[serde(untagged, rename_all = "camelCase")]
161    pub enum OnExportResponse {
162        /// Non-page or a single page exported.
163        Single {
164            /// The path of the exported file. None if not written to file.
165            path: Option<PathBuf>,
166            /// The data of the exported file. None if written to file.
167            data: Option<String>,
168        },
169        /// Multiple pages exported.
170        Paged {
171            /// The total number of pages of the document.
172            total_pages: usize,
173            /// The exported pages.
174            items: Vec<PagedExportResponse>,
175        },
176    }
177
178    /// The response to a single page export.
179    #[derive(Debug, Clone, Serialize, Deserialize)]
180    #[serde(rename_all = "camelCase")]
181    pub struct PagedExportResponse {
182        /// The page number of the exported page (0-based).
183        pub page: usize,
184        /// The path of the exported file. None if not written to file.
185        pub path: Option<PathBuf>,
186        /// The data of the exported file. None if written to file.
187        pub data: Option<String>,
188    }
189
190    /// A request to format the document.
191    #[derive(Debug, Clone)]
192    pub struct FormattingRequest {
193        /// The path of the document to get semantic tokens for.
194        pub path: PathBuf,
195    }
196
197    /// A request to get the server info.
198    #[derive(Debug, Clone)]
199    pub struct ServerInfoRequest {}
200
201    /// The response to the server info request.
202    #[derive(Debug, Clone, Serialize, Deserialize)]
203    #[serde(rename_all = "camelCase")]
204    pub struct ServerInfoResponse {
205        /// The root path of the server.
206        pub root: Option<PathBuf>,
207        /// The font paths of the server.
208        pub font_paths: Vec<PathBuf>,
209        /// The inputs of the server.
210        pub inputs: Dict,
211        /// The statistics of the server.
212        pub stats: HashMap<String, String>,
213    }
214
215    /// The feature of the fold request.
216    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
217    pub enum FoldRequestFeature {
218        /// Serves the request with the first pinned entry.
219        PinnedFirst,
220        /// Makes the items unique.
221        Unique,
222        /// Merges the items.
223        Mergeable,
224        /// Makes the items unique without context.
225        ContextFreeUnique,
226    }
227
228    /// The analysis request.
229    #[derive(Debug, Clone, strum::IntoStaticStr)]
230    pub enum CompilerQueryRequest {
231        /// A request to run an export task.
232        OnExport(OnExportRequest),
233        /// A request to run an export markdown task.
234        OnExportMd(OnExportMdRequest),
235        /// A request to get the hover information.
236        Hover(HoverRequest),
237        /// A request to get the hover information for a symbol.
238        HoverSymbol(String),
239        /// A request to go to the definition.
240        GotoDefinition(GotoDefinitionRequest),
241        /// A request to go to the definition of a symbol.
242        GotoDefinitionSymbol(String),
243        /// A request to go to the declaration.
244        GotoDeclaration(GotoDeclarationRequest),
245        /// A request to get the references.
246        References(ReferencesRequest),
247        /// A request to get the inlay hints.
248        InlayHint(InlayHintRequest),
249        /// A request to get the document colors.
250        DocumentColor(DocumentColorRequest),
251        /// A request to get the document links.
252        DocumentLink(DocumentLinkRequest),
253        /// A request to get the document highlights.
254        DocumentHighlight(DocumentHighlightRequest),
255        /// A request to get the color presentations.
256        ColorPresentation(ColorPresentationRequest),
257        /// A request to get the code actions.
258        CodeAction(CodeActionRequest),
259        /// A request to get the code lenses.
260        CodeLens(CodeLensRequest),
261        /// A request to get the completions.
262        Completion(CompletionRequest),
263        /// A request to get the signature helps.
264        SignatureHelp(SignatureHelpRequest),
265        /// A request to rename.
266        Rename(RenameRequest),
267        /// A request to determine the files to be renamed.
268        WillRenameFiles(WillRenameFilesRequest),
269        /// A request to prepare the rename.
270        PrepareRename(PrepareRenameRequest),
271        /// A request to get the document symbols.
272        DocumentSymbol(DocumentSymbolRequest),
273        /// A request to get the symbols.
274        Symbol(SymbolRequest),
275        /// A request to get the semantic tokens full.
276        SemanticTokensFull(SemanticTokensFullRequest),
277        /// A request to get the semantic tokens delta.
278        SemanticTokensDelta(SemanticTokensDeltaRequest),
279        /// A request to format the document.
280        Formatting(FormattingRequest),
281        /// A request to get the folding ranges.
282        FoldingRange(FoldingRangeRequest),
283        /// A request to get the selection ranges.
284        SelectionRange(SelectionRangeRequest),
285        /// A request to interact with the code context.
286        InteractCodeContext(InteractCodeContextRequest),
287
288        /// A request to get extra text edits on enter.
289        OnEnter(OnEnterRequest),
290
291        /// A request to get the document metrics.
292        DocumentMetrics(DocumentMetricsRequest),
293        /// A request to get the workspace labels.
294        WorkspaceLabel(WorkspaceLabelRequest),
295        /// A request to get the server info.
296        ServerInfo(ServerInfoRequest),
297    }
298
299    impl CompilerQueryRequest {
300        /// Gets the feature of the fold request.
301        pub fn fold_feature(&self) -> FoldRequestFeature {
302            use FoldRequestFeature::*;
303            match self {
304                Self::OnExport(..) => Mergeable,
305                Self::OnExportMd(..) => Mergeable,
306                Self::Hover(..) => PinnedFirst,
307                Self::HoverSymbol(..) => PinnedFirst,
308                Self::GotoDefinition(..) => PinnedFirst,
309                Self::GotoDefinitionSymbol(..) => PinnedFirst,
310                Self::GotoDeclaration(..) => PinnedFirst,
311                Self::References(..) => PinnedFirst,
312                Self::InlayHint(..) => Unique,
313                Self::DocumentColor(..) => PinnedFirst,
314                Self::DocumentLink(..) => PinnedFirst,
315                Self::DocumentHighlight(..) => PinnedFirst,
316                Self::ColorPresentation(..) => ContextFreeUnique,
317                Self::CodeAction(..) => Unique,
318                Self::CodeLens(..) => Unique,
319                Self::Completion(..) => Mergeable,
320                Self::SignatureHelp(..) => PinnedFirst,
321                Self::Rename(..) => Mergeable,
322                Self::WillRenameFiles(..) => Mergeable,
323                Self::PrepareRename(..) => Mergeable,
324                Self::DocumentSymbol(..) => ContextFreeUnique,
325                Self::WorkspaceLabel(..) => Mergeable,
326                Self::Symbol(..) => Mergeable,
327                Self::SemanticTokensFull(..) => PinnedFirst,
328                Self::SemanticTokensDelta(..) => PinnedFirst,
329                Self::Formatting(..) => ContextFreeUnique,
330                Self::FoldingRange(..) => ContextFreeUnique,
331                Self::SelectionRange(..) => ContextFreeUnique,
332                Self::InteractCodeContext(..) => PinnedFirst,
333
334                Self::OnEnter(..) => ContextFreeUnique,
335
336                Self::DocumentMetrics(..) => PinnedFirst,
337                Self::ServerInfo(..) => Mergeable,
338            }
339        }
340
341        /// Gets the associated path of the request.
342        pub fn associated_path(&self) -> Option<&Path> {
343            Some(match self {
344                Self::OnExport(..) => return None,
345                Self::OnExportMd(..) => return None,
346                Self::Hover(req) => &req.path,
347                Self::HoverSymbol(..) => return None,
348                Self::GotoDefinition(req) => &req.path,
349                Self::GotoDefinitionSymbol(..) => return None,
350                Self::GotoDeclaration(req) => &req.path,
351                Self::References(req) => &req.path,
352                Self::InlayHint(req) => &req.path,
353                Self::DocumentColor(req) => &req.path,
354                Self::DocumentLink(req) => &req.path,
355                Self::DocumentHighlight(req) => &req.path,
356                Self::ColorPresentation(req) => &req.path,
357                Self::CodeAction(req) => &req.path,
358                Self::CodeLens(req) => &req.path,
359                Self::Completion(req) => &req.path,
360                Self::SignatureHelp(req) => &req.path,
361                Self::Rename(req) => &req.path,
362                Self::WillRenameFiles(..) => return None,
363                Self::PrepareRename(req) => &req.path,
364                Self::DocumentSymbol(req) => &req.path,
365                Self::Symbol(..) => return None,
366                Self::WorkspaceLabel(..) => return None,
367                Self::SemanticTokensFull(req) => &req.path,
368                Self::SemanticTokensDelta(req) => &req.path,
369                Self::Formatting(req) => &req.path,
370                Self::FoldingRange(req) => &req.path,
371                Self::SelectionRange(req) => &req.path,
372                Self::InteractCodeContext(req) => &req.path,
373
374                Self::OnEnter(req) => &req.path,
375
376                Self::DocumentMetrics(req) => &req.path,
377                Self::ServerInfo(..) => return None,
378            })
379        }
380    }
381
382    /// The response to the compiler query request.
383    #[derive(Debug, Clone, Serialize, Deserialize)]
384    #[serde(untagged)]
385    pub enum CompilerQueryResponse {
386        /// The response to the on export request.
387        OnExport(Option<OnExportResponse>),
388        /// The response to the hover request.
389        Hover(Option<Hover>),
390        /// The response to the goto definition request.
391        GotoDefinition(Option<GotoDefinitionResponse>),
392        /// The response to the goto declaration request.
393        GotoDeclaration(Option<GotoDeclarationResponse>),
394        /// The response to the references request.
395        References(Option<Vec<LspLocation>>),
396        /// The response to the inlay hint request.
397        InlayHint(Option<Vec<InlayHint>>),
398        /// The response to the document color request.
399        DocumentColor(Option<Vec<ColorInformation>>),
400        /// The response to the document link request.
401        DocumentLink(Option<Vec<DocumentLink>>),
402        /// The response to the document highlight request.
403        DocumentHighlight(Option<Vec<DocumentHighlight>>),
404        /// The response to the color presentation request.
405        ColorPresentation(Option<Vec<ColorPresentation>>),
406        /// The response to the code action request.
407        CodeAction(Option<Vec<CodeAction>>),
408        /// The response to the code lens request.
409        CodeLens(Option<Vec<CodeLens>>),
410        /// The response to the completion request.
411        Completion(Option<CompletionList>),
412        /// The response to the signature help request.
413        SignatureHelp(Option<SignatureHelp>),
414        /// The response to the prepare rename request.
415        PrepareRename(Option<PrepareRenameResponse>),
416        /// The response to the rename request.
417        Rename(Option<WorkspaceEdit>),
418        /// The response to the will rename files request.
419        WillRenameFiles(Option<WorkspaceEdit>),
420        /// The response to the document symbol request.
421        DocumentSymbol(Option<DocumentSymbolResponse>),
422        /// The response to the symbol request.
423        Symbol(Option<Vec<SymbolInformation>>),
424        /// The response to the workspace label request.
425        WorkspaceLabel(Option<Vec<SymbolInformation>>),
426        /// The response to the semantic tokens full request.
427        SemanticTokensFull(Option<SemanticTokensResult>),
428        /// The response to the semantic tokens delta request.
429        SemanticTokensDelta(Option<SemanticTokensFullDeltaResult>),
430        /// The response to the formatting request.
431        Formatting(Option<Vec<TextEdit>>),
432        /// The response to the folding range request.
433        FoldingRange(Option<Vec<FoldingRange>>),
434        /// The response to the selection range request.
435        SelectionRange(Option<Vec<SelectionRange>>),
436        /// The response to the interact code context request.
437        InteractCodeContext(Option<Vec<Option<InteractCodeContextResponse>>>),
438
439        /// The response to the on enter request.
440        OnEnter(Option<Vec<TextEdit>>),
441
442        /// The response to the document metrics request.
443        DocumentMetrics(Option<DocumentMetricsResponse>),
444        /// The response to the server info request.
445        ServerInfo(Option<HashMap<String, ServerInfoResponse>>),
446    }
447}
448
449pub use polymorphic::*;
450
451#[cfg(test)]
452mod tests;