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::layout::Position;
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    /// The response to an export request.
144    #[derive(Debug, Clone, Serialize, Deserialize)]
145    #[serde(untagged, rename_all = "camelCase")]
146    pub enum OnExportResponse {
147        /// Non-page or a single page exported.
148        Single {
149            /// The path of the exported file. None if not written to file.
150            path: Option<PathBuf>,
151            /// The data of the exported file. None if written to file.
152            data: Option<String>,
153        },
154        /// Multiple pages exported.
155        Paged {
156            /// The total number of pages of the document.
157            total_pages: usize,
158            /// The exported pages.
159            items: Vec<PagedExportResponse>,
160        },
161    }
162
163    /// The response to a single page export.
164    #[derive(Debug, Clone, Serialize, Deserialize)]
165    #[serde(rename_all = "camelCase")]
166    pub struct PagedExportResponse {
167        /// The page number of the exported page (0-based).
168        pub page: usize,
169        /// The path of the exported file. None if not written to file.
170        pub path: Option<PathBuf>,
171        /// The data of the exported file. None if written to file.
172        pub data: Option<String>,
173    }
174
175    /// A request to format the document.
176    #[derive(Debug, Clone)]
177    pub struct FormattingRequest {
178        /// The path of the document to get semantic tokens for.
179        pub path: PathBuf,
180    }
181
182    /// A request to get the server info.
183    #[derive(Debug, Clone)]
184    pub struct ServerInfoRequest {}
185
186    /// The response to the server info request.
187    #[derive(Debug, Clone, Serialize, Deserialize)]
188    #[serde(rename_all = "camelCase")]
189    pub struct ServerInfoResponse {
190        /// The root path of the server.
191        pub root: Option<PathBuf>,
192        /// The font paths of the server.
193        pub font_paths: Vec<PathBuf>,
194        /// The inputs of the server.
195        pub inputs: Dict,
196        /// The statistics of the server.
197        pub stats: HashMap<String, String>,
198    }
199
200    /// The feature of the fold request.
201    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
202    pub enum FoldRequestFeature {
203        /// Serves the request with the first pinned entry.
204        PinnedFirst,
205        /// Makes the items unique.
206        Unique,
207        /// Merges the items.
208        Mergeable,
209        /// Makes the items unique without context.
210        ContextFreeUnique,
211    }
212
213    /// The analysis request.
214    #[derive(Debug, Clone, strum::IntoStaticStr)]
215    pub enum CompilerQueryRequest {
216        /// A request to run an export task.
217        OnExport(OnExportRequest),
218        /// A request to get the hover information.
219        Hover(HoverRequest),
220        /// A request to go to the definition.
221        GotoDefinition(GotoDefinitionRequest),
222        /// A request to go to the declaration.
223        GotoDeclaration(GotoDeclarationRequest),
224        /// A request to get the references.
225        References(ReferencesRequest),
226        /// A request to get the inlay hints.
227        InlayHint(InlayHintRequest),
228        /// A request to get the document colors.
229        DocumentColor(DocumentColorRequest),
230        /// A request to get the document links.
231        DocumentLink(DocumentLinkRequest),
232        /// A request to get the document highlights.
233        DocumentHighlight(DocumentHighlightRequest),
234        /// A request to get the color presentations.
235        ColorPresentation(ColorPresentationRequest),
236        /// A request to get the code actions.
237        CodeAction(CodeActionRequest),
238        /// A request to get the code lenses.
239        CodeLens(CodeLensRequest),
240        /// A request to get the completions.
241        Completion(CompletionRequest),
242        /// A request to get the signature helps.
243        SignatureHelp(SignatureHelpRequest),
244        /// A request to rename.
245        Rename(RenameRequest),
246        /// A request to determine the files to be renamed.
247        WillRenameFiles(WillRenameFilesRequest),
248        /// A request to prepare the rename.
249        PrepareRename(PrepareRenameRequest),
250        /// A request to get the document symbols.
251        DocumentSymbol(DocumentSymbolRequest),
252        /// A request to get the symbols.
253        Symbol(SymbolRequest),
254        /// A request to get the semantic tokens full.
255        SemanticTokensFull(SemanticTokensFullRequest),
256        /// A request to get the semantic tokens delta.
257        SemanticTokensDelta(SemanticTokensDeltaRequest),
258        /// A request to format the document.
259        Formatting(FormattingRequest),
260        /// A request to get the folding ranges.
261        FoldingRange(FoldingRangeRequest),
262        /// A request to get the selection ranges.
263        SelectionRange(SelectionRangeRequest),
264        /// A request to interact with the code context.
265        InteractCodeContext(InteractCodeContextRequest),
266
267        /// A request to get extra text edits on enter.
268        OnEnter(OnEnterRequest),
269
270        /// A request to get the document metrics.
271        DocumentMetrics(DocumentMetricsRequest),
272        /// A request to get the workspace labels.
273        WorkspaceLabel(WorkspaceLabelRequest),
274        /// A request to get the server info.
275        ServerInfo(ServerInfoRequest),
276    }
277
278    impl CompilerQueryRequest {
279        /// Gets the feature of the fold request.
280        pub fn fold_feature(&self) -> FoldRequestFeature {
281            use FoldRequestFeature::*;
282            match self {
283                Self::OnExport(..) => Mergeable,
284                Self::Hover(..) => PinnedFirst,
285                Self::GotoDefinition(..) => PinnedFirst,
286                Self::GotoDeclaration(..) => PinnedFirst,
287                Self::References(..) => PinnedFirst,
288                Self::InlayHint(..) => Unique,
289                Self::DocumentColor(..) => PinnedFirst,
290                Self::DocumentLink(..) => PinnedFirst,
291                Self::DocumentHighlight(..) => PinnedFirst,
292                Self::ColorPresentation(..) => ContextFreeUnique,
293                Self::CodeAction(..) => Unique,
294                Self::CodeLens(..) => Unique,
295                Self::Completion(..) => Mergeable,
296                Self::SignatureHelp(..) => PinnedFirst,
297                Self::Rename(..) => Mergeable,
298                Self::WillRenameFiles(..) => Mergeable,
299                Self::PrepareRename(..) => Mergeable,
300                Self::DocumentSymbol(..) => ContextFreeUnique,
301                Self::WorkspaceLabel(..) => Mergeable,
302                Self::Symbol(..) => Mergeable,
303                Self::SemanticTokensFull(..) => PinnedFirst,
304                Self::SemanticTokensDelta(..) => PinnedFirst,
305                Self::Formatting(..) => ContextFreeUnique,
306                Self::FoldingRange(..) => ContextFreeUnique,
307                Self::SelectionRange(..) => ContextFreeUnique,
308                Self::InteractCodeContext(..) => PinnedFirst,
309
310                Self::OnEnter(..) => ContextFreeUnique,
311
312                Self::DocumentMetrics(..) => PinnedFirst,
313                Self::ServerInfo(..) => Mergeable,
314            }
315        }
316
317        /// Gets the associated path of the request.
318        pub fn associated_path(&self) -> Option<&Path> {
319            Some(match self {
320                Self::OnExport(..) => return None,
321                Self::Hover(req) => &req.path,
322                Self::GotoDefinition(req) => &req.path,
323                Self::GotoDeclaration(req) => &req.path,
324                Self::References(req) => &req.path,
325                Self::InlayHint(req) => &req.path,
326                Self::DocumentColor(req) => &req.path,
327                Self::DocumentLink(req) => &req.path,
328                Self::DocumentHighlight(req) => &req.path,
329                Self::ColorPresentation(req) => &req.path,
330                Self::CodeAction(req) => &req.path,
331                Self::CodeLens(req) => &req.path,
332                Self::Completion(req) => &req.path,
333                Self::SignatureHelp(req) => &req.path,
334                Self::Rename(req) => &req.path,
335                Self::WillRenameFiles(..) => return None,
336                Self::PrepareRename(req) => &req.path,
337                Self::DocumentSymbol(req) => &req.path,
338                Self::Symbol(..) => return None,
339                Self::WorkspaceLabel(..) => return None,
340                Self::SemanticTokensFull(req) => &req.path,
341                Self::SemanticTokensDelta(req) => &req.path,
342                Self::Formatting(req) => &req.path,
343                Self::FoldingRange(req) => &req.path,
344                Self::SelectionRange(req) => &req.path,
345                Self::InteractCodeContext(req) => &req.path,
346
347                Self::OnEnter(req) => &req.path,
348
349                Self::DocumentMetrics(req) => &req.path,
350                Self::ServerInfo(..) => return None,
351            })
352        }
353    }
354
355    /// The response to the compiler query request.
356    #[derive(Debug, Clone, Serialize, Deserialize)]
357    #[serde(untagged)]
358    pub enum CompilerQueryResponse {
359        /// The response to the on export request.
360        OnExport(Option<OnExportResponse>),
361        /// The response to the hover request.
362        Hover(Option<Hover>),
363        /// The response to the goto definition request.
364        GotoDefinition(Option<GotoDefinitionResponse>),
365        /// The response to the goto declaration request.
366        GotoDeclaration(Option<GotoDeclarationResponse>),
367        /// The response to the references request.
368        References(Option<Vec<LspLocation>>),
369        /// The response to the inlay hint request.
370        InlayHint(Option<Vec<InlayHint>>),
371        /// The response to the document color request.
372        DocumentColor(Option<Vec<ColorInformation>>),
373        /// The response to the document link request.
374        DocumentLink(Option<Vec<DocumentLink>>),
375        /// The response to the document highlight request.
376        DocumentHighlight(Option<Vec<DocumentHighlight>>),
377        /// The response to the color presentation request.
378        ColorPresentation(Option<Vec<ColorPresentation>>),
379        /// The response to the code action request.
380        CodeAction(Option<Vec<CodeAction>>),
381        /// The response to the code lens request.
382        CodeLens(Option<Vec<CodeLens>>),
383        /// The response to the completion request.
384        Completion(Option<CompletionList>),
385        /// The response to the signature help request.
386        SignatureHelp(Option<SignatureHelp>),
387        /// The response to the prepare rename request.
388        PrepareRename(Option<PrepareRenameResponse>),
389        /// The response to the rename request.
390        Rename(Option<WorkspaceEdit>),
391        /// The response to the will rename files request.
392        WillRenameFiles(Option<WorkspaceEdit>),
393        /// The response to the document symbol request.
394        DocumentSymbol(Option<DocumentSymbolResponse>),
395        /// The response to the symbol request.
396        Symbol(Option<Vec<SymbolInformation>>),
397        /// The response to the workspace label request.
398        WorkspaceLabel(Option<Vec<SymbolInformation>>),
399        /// The response to the semantic tokens full request.
400        SemanticTokensFull(Option<SemanticTokensResult>),
401        /// The response to the semantic tokens delta request.
402        SemanticTokensDelta(Option<SemanticTokensFullDeltaResult>),
403        /// The response to the formatting request.
404        Formatting(Option<Vec<TextEdit>>),
405        /// The response to the folding range request.
406        FoldingRange(Option<Vec<FoldingRange>>),
407        /// The response to the selection range request.
408        SelectionRange(Option<Vec<SelectionRange>>),
409        /// The response to the interact code context request.
410        InteractCodeContext(Option<Vec<Option<InteractCodeContextResponse>>>),
411
412        /// The response to the on enter request.
413        OnEnter(Option<Vec<TextEdit>>),
414
415        /// The response to the document metrics request.
416        DocumentMetrics(Option<DocumentMetricsResponse>),
417        /// The response to the server info request.
418        ServerInfo(Option<HashMap<String, ServerInfoResponse>>),
419    }
420}
421
422pub use polymorphic::*;
423
424#[cfg(test)]
425mod tests;