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