Skip to main content

vvv_core/lang/
mod.rs

1//! The language plugin boundary.
2//!
3//! A [`Language`] knows how to look inside one kind of source file. It never
4//! hands out parser nodes: everything it returns is plain data ([`RawMatch`],
5//! [`Symbol`], [`ImportRef`], [`Facts`]), which is what lets the core and the
6//! planners be tested with a fake language and lets a real language move out
7//! of process.
8
9mod registry;
10
11use std::borrow::Cow;
12use std::fmt;
13
14use serde::{Deserialize, Serialize};
15
16pub use registry::LanguageRegistry;
17
18use crate::facts::Facts;
19use crate::highlight::{Highlight, HighlightRule};
20use crate::import::{ImportGrammar, ImportRef};
21use crate::paths::PathSyntax;
22use crate::query::Query;
23use crate::resolve::{Layout, Surgery};
24use crate::search::{RawMatch, SearchError};
25use crate::semantics::Semantics;
26use crate::symbol::{Symbol, SymbolRule};
27
28/// Stable identifier of a language (`rust`, `typescript`, ...).
29#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
30#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
31#[serde(transparent)]
32pub struct LanguageId(Cow<'static, str>);
33
34impl LanguageId {
35    pub const fn new(id: &'static str) -> Self {
36        Self(Cow::Borrowed(id))
37    }
38
39    pub fn as_str(&self) -> &str {
40        &self.0
41    }
42}
43
44impl From<String> for LanguageId {
45    fn from(id: String) -> Self {
46        Self(Cow::Owned(id))
47    }
48}
49
50impl From<&str> for LanguageId {
51    fn from(id: &str) -> Self {
52        Self(Cow::Owned(id.to_owned()))
53    }
54}
55
56impl fmt::Display for LanguageId {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.write_str(&self.0)
59    }
60}
61
62impl fmt::Debug for LanguageId {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(f, "LanguageId({})", self.0)
65    }
66}
67
68/// Everything a grammar-backed language declares about itself, as data:
69/// what a declaration is, what an identifier token is, where import paths
70/// live. A language module contributes one of these beside its semantics.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct Grammar {
73    pub import_scopes: &'static [&'static str],
74    pub module_scopes: Option<crate::ModuleScopeRule>,
75    pub macro_scopes: Option<crate::MacroScopeRule>,
76    pub binding_markers: &'static [&'static str],
77    pub navigation_values: &'static [&'static str],
78    pub calls: &'static [crate::CallRule],
79    pub callees: &'static [crate::CalleeRule],
80    pub anonymous_callables: &'static [&'static str],
81    /// Constructor fields excluded from lexical binding extraction.
82    pub pattern_constructors: &'static [(&'static str, &'static str)],
83    pub pattern_containers: &'static [&'static str],
84    pub qualified_imports: &'static [crate::QualifiedImportRule],
85    pub bindings: &'static [crate::BindingRule],
86    pub lexical_qualified: &'static [&'static str],
87    pub lexical_boundaries: &'static [&'static str],
88    pub lexical_containers: &'static [&'static str],
89    pub lexical_barriers: &'static [&'static str],
90    pub named_imports: &'static [crate::NamedImportRule],
91    pub named_modules: bool,
92    /// Modifiers that export a declaration under a name other than its own.
93    pub non_named_exports: &'static [&'static str],
94    pub symbols: &'static [SymbolRule],
95    pub signatures: &'static [crate::SignatureRule],
96    pub identifiers: &'static [&'static str],
97    pub imports: ImportGrammar,
98    pub highlights: &'static [HighlightRule],
99    /// Identifier kinds that can be followed through module/type bindings.
100    pub navigation_types: &'static [&'static str],
101    /// Ancestors requiring lexical or receiver information not supplied yet.
102    pub navigation_barriers: &'static [&'static str],
103    /// Child fields on an ancestor that introduce unsupported generic bindings.
104    pub navigation_bindings: &'static [&'static str],
105}
106
107impl Grammar {
108    pub const EMPTY: Self = Self {
109        import_scopes: &[],
110        module_scopes: None,
111        macro_scopes: None,
112        binding_markers: &[],
113        navigation_values: &[],
114        calls: &[],
115        callees: &[],
116        anonymous_callables: &[],
117        pattern_constructors: &[],
118        pattern_containers: &[],
119        qualified_imports: &[],
120        bindings: &[],
121        lexical_qualified: &[],
122        lexical_boundaries: &[],
123        lexical_containers: &[],
124        lexical_barriers: &[],
125        named_imports: &[],
126        named_modules: false,
127        non_named_exports: &[],
128        symbols: &[],
129        signatures: &[],
130        identifiers: &[],
131        imports: ImportGrammar::EMPTY,
132        highlights: &[],
133        navigation_types: &[],
134        navigation_barriers: &[],
135        navigation_bindings: &[],
136    };
137}
138
139pub trait Language: Send + Sync {
140    fn id(&self) -> LanguageId;
141    /// Plugins in the same group can resolve references to each other's source files.
142    /// Incoming discovery scans this group; it still confirms every target by navigation.
143    fn reference_group(&self) -> LanguageId {
144        self.id()
145    }
146
147    /// File extensions (without the dot) this language claims.
148    fn extensions(&self) -> &'static [&'static str];
149
150    /// What the language's syntax means.
151    fn semantics(&self) -> &'static Semantics;
152
153    /// How the language spells paths: what its import text is parsed with
154    /// and what a rendered path is spelled back with.
155    fn paths(&self) -> PathSyntax;
156
157    /// Text every glob import contains (`::*` in Rust), so a file that does
158    /// not spell it need not be parsed when only globs are looked for;
159    /// `None` when the language has no glob imports.
160    fn glob_marker(&self) -> Option<&'static str> {
161        None
162    }
163
164    /// Everything about one file from one parse.
165    fn facts(&self, source: &str) -> Result<Facts, SearchError>;
166
167    /// Whether this language can run `query` at all: its grammar compiles
168    /// the pattern and knows the node kind. Asked once per language before
169    /// any file is read; a language that declines is skipped, not fatal.
170    fn accepts(&self, query: &Query) -> Result<(), SearchError> {
171        let _ = query;
172        Ok(())
173    }
174
175    /// Search over one file's text, honouring every part of the query.
176    fn find(&self, source: &str, query: &Query) -> Result<Vec<RawMatch>, SearchError>;
177
178    /// Declarations in one file, in source order.
179    fn symbols(&self, source: &str) -> Result<Vec<Symbol>, SearchError> {
180        let _ = source;
181        Ok(Vec::new())
182    }
183
184    /// Every identifier token spelling `name`, declarations included.
185    fn references(&self, source: &str, name: &str) -> Result<Vec<RawMatch>, SearchError> {
186        let _ = (source, name);
187        Ok(Vec::new())
188    }
189
190    /// Import paths in one file, in source order.
191    fn imports(&self, source: &str) -> Result<Vec<ImportRef>, SearchError> {
192        let _ = source;
193        Ok(Vec::new())
194    }
195
196    /// Syntax colouring for one file, as non-overlapping spans in order.
197    fn highlights(&self, source: &str) -> Result<Vec<Highlight>, SearchError> {
198        let _ = source;
199        Ok(Vec::new())
200    }
201
202    /// How the language's projects are arranged, when vvv can follow them.
203    fn layout(&self) -> Option<&dyn Layout> {
204        None
205    }
206
207    /// How to spell edits in the language, when files can be moved.
208    fn surgery(&self) -> Option<&dyn Surgery> {
209        None
210    }
211}