Skip to main content

vvv_core/search/
mod.rs

1//! Search results as plain data.
2//!
3//! A [`Language`](crate::lang::Language) produces [`RawMatch`]es, which know
4//! nothing about files; the engine ties them to a path, a position and a
5//! stable id. Only what a language produces lives here.
6
7use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10
11use crate::symbol::Symbol;
12use crate::text::Span;
13
14#[derive(Debug, Clone, thiserror::Error)]
15pub enum SearchError {
16    #[error("invalid pattern: {0}")]
17    Pattern(String),
18    #[error("invalid node kind: {0}")]
19    Kind(String),
20    #[error("{0}")]
21    Other(String),
22}
23
24/// What position a match occupies in its file: the declaration itself, a
25/// token inside an import statement, or any other use. Views lead with
26/// declarations and dim imports; the engine orders results by it.
27#[derive(
28    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
29)]
30#[serde(rename_all = "lowercase")]
31pub enum Role {
32    Declaration,
33    Import,
34    #[default]
35    Use,
36}
37
38/// One meta-variable binding.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Capture {
41    pub span: Span,
42    pub text: String,
43}
44
45/// `$A` binds one node; `$$$A` binds a sequence.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(untagged)]
48pub enum CaptureValue {
49    Single(Capture),
50    Multiple(Vec<Capture>),
51}
52
53/// A match within a single text, before it is tied to a file.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct RawMatch {
56    pub span: Span,
57    /// Tree-sitter node kind of the matched node.
58    pub kind: String,
59    pub text: String,
60    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
61    pub captures: BTreeMap<String, CaptureValue>,
62    /// Set when the matched node is a declaration.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub symbol: Option<Symbol>,
65    #[serde(default)]
66    pub role: Role,
67}
68
69impl RawMatch {
70    /// A match with no captures and no symbol, from a span and its text.
71    pub fn plain(span: Span, kind: impl Into<String>, text: impl Into<String>) -> Self {
72        Self {
73            span,
74            kind: kind.into(),
75            text: text.into(),
76            captures: BTreeMap::new(),
77            symbol: None,
78            role: Role::Use,
79        }
80    }
81}