Skip to main content

vvv_core/symbol/
mod.rs

1//! Language-neutral view of declarations.
2//!
3//! A plugin describes its grammar with [`SymbolRule`]s (data); the generic
4//! extractor in `vvv-lang` turns them into [`Symbol`]s. Nothing here knows
5//! tree-sitter.
6
7mod kind;
8
9use serde::{Deserialize, Serialize};
10
11pub use kind::{SymbolKind, UnknownSymbolKind};
12
13use crate::text::Span;
14
15/// A declaration found in one file.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
18pub struct Symbol {
19    pub kind: SymbolKind,
20    pub name: String,
21    /// The identifier token itself: what a rename replaces.
22    pub name_span: Span,
23    /// The declaration node.
24    pub span: Span,
25    /// The declaration with what belongs to it in the text: leading
26    /// attributes and doc comments, an enclosing `export`. What moving the
27    /// declaration cuts; what an outline shows.
28    pub extent: Span,
29    /// The visibility as written (`pub(crate)`, `export`); `None` when the
30    /// declaration has no modifier. What it means is the language's
31    /// [`Semantics`](crate::Semantics).
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub visibility: Option<Modifier>,
34}
35
36impl Symbol {
37    pub fn validate_in(&self, source: &str) -> Result<(), crate::SpanError> {
38        for span in [self.name_span, self.span, self.extent] {
39            span.validate_in(source)?;
40        }
41        if let Some(modifier) = &self.visibility {
42            modifier.span.validate_in(source)?;
43        }
44        Ok(())
45    }
46    /// A symbol whose extent is its node and which has no modifier.
47    pub fn plain(kind: SymbolKind, name: impl Into<String>, name_span: Span, span: Span) -> Self {
48        Self {
49            kind,
50            name: name.into(),
51            name_span,
52            span,
53            extent: span,
54            visibility: None,
55        }
56    }
57
58    pub fn modifier(&self) -> Option<&str> {
59        self.visibility.as_ref().map(|m| m.text.as_str())
60    }
61}
62
63/// A visibility modifier as it appears in the source.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
66pub struct Modifier {
67    pub span: Span,
68    pub text: String,
69}
70
71/// Where a declaration's visibility modifier is found in the tree.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum ModifierAt {
74    /// A direct child of this kind (`visibility_modifier` in Rust).
75    Child(&'static str),
76    /// An enclosing node of this kind whose first token is the modifier
77    /// (`export_statement` in TypeScript). It becomes part of the extent.
78    Parent(&'static str),
79}
80
81/// "Nodes of kind `node` declare a `kind` whose name is the field `name_field`."
82///
83/// Rules are tried in order; the first whose `node`, `under` and `within`
84/// all match wins, so put the more specific rule (a method inside an impl)
85/// before the general one (a function).
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct SymbolRule {
88    pub node: &'static str,
89    /// Field holding the identifier; `None` when the node is its own name
90    /// (a bare enum member, say).
91    pub name_field: Option<&'static str>,
92    pub kind: SymbolKind,
93    /// Only applies when the direct parent has this kind.
94    pub under: Option<&'static str>,
95    /// Only applies when an ancestor of this node kind exists, without a
96    /// nested declaration of the same `node` kind in between.
97    pub within: Option<&'static str>,
98    /// Kinds of preceding siblings that belong to the declaration
99    /// (attributes, doc comments) and extend its extent, as long as no blank
100    /// line separates them from it.
101    pub leading: &'static [&'static str],
102    /// Where the visibility modifier is, if the language has one.
103    pub visibility: Option<ModifierAt>,
104    /// When the name node has a child in this field, the name is that
105    /// child's, repeatedly: `Foo` inside the `generic_type` `Foo<'a>` an
106    /// `impl` is for.
107    pub name_inner: Option<&'static str>,
108    /// Declaration kinds this non-declaration piece can belong to.
109    pub companion_of: &'static [SymbolKind],
110    /// Whether the declaration statement can be moved independently.
111    pub movable: bool,
112    /// Transparent statement wrappers for move scope evidence.
113    pub move_scope_wrappers: &'static [&'static str],
114}
115
116impl SymbolRule {
117    pub const fn new(node: &'static str, name_field: &'static str, kind: SymbolKind) -> Self {
118        Self {
119            node,
120            name_field: Some(name_field),
121            kind,
122            under: None,
123            within: None,
124            leading: &[],
125            visibility: None,
126            name_inner: None,
127            companion_of: &[],
128            move_scope_wrappers: &[],
129            movable: true,
130        }
131    }
132
133    /// The node is the identifier token itself.
134    pub const fn self_named(node: &'static str, kind: SymbolKind) -> Self {
135        Self {
136            node,
137            name_field: None,
138            kind,
139            under: None,
140            within: None,
141            leading: &[],
142            visibility: None,
143            name_inner: None,
144            companion_of: &[],
145            move_scope_wrappers: &[],
146            movable: true,
147        }
148    }
149
150    pub const fn movable(mut self, supported: bool) -> Self {
151        self.movable = supported;
152        self
153    }
154
155    pub const fn move_scope_wrappers(mut self, kinds: &'static [&'static str]) -> Self {
156        self.move_scope_wrappers = kinds;
157        self
158    }
159
160    pub const fn companion_of(mut self, kinds: &'static [SymbolKind]) -> Self {
161        self.companion_of = kinds;
162        self
163    }
164
165    pub const fn name_inner(mut self, field: &'static str) -> Self {
166        self.name_inner = Some(field);
167        self
168    }
169
170    pub const fn leading(mut self, kinds: &'static [&'static str]) -> Self {
171        self.leading = kinds;
172        self
173    }
174
175    pub const fn visibility(mut self, at: ModifierAt) -> Self {
176        self.visibility = Some(at);
177        self
178    }
179
180    /// The direct parent must be this kind.
181    pub const fn under(mut self, parent: &'static str) -> Self {
182        self.under = Some(parent);
183        self
184    }
185
186    pub const fn within(mut self, ancestor: &'static str) -> Self {
187        self.within = Some(ancestor);
188        self
189    }
190}
191
192/// Move evidence for one declaration. Missing evidence means unsupported.
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
194#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
195pub struct DeclarationPieces {
196    pub declaration: Span,
197    /// False for declaration forms without independently owned movable text.
198    pub supported: bool,
199    /// Lexical declaration scope; used to distinguish local same-named bindings.
200    pub scope: Span,
201    pub top_level: bool,
202    pub companions: Vec<CompanionPiece>,
203}
204
205/// A syntax-owned relationship, never inferred by the engine from a name.
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
208pub struct CompanionPiece {
209    pub span: Span,
210    pub ownership: CompanionOwnership,
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
214#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
215#[serde(rename_all = "snake_case")]
216pub enum CompanionOwnership {
217    SameScopeTarget,
218    AmbiguousTarget,
219    UnsupportedTarget,
220}