Skip to main content

vvv_core/
navigation.rs

1//! Lexical and imported bindings used by navigation, independent of mutation scope.
2
3use crate::{ImportBinding, ModulePath, Name, Span, Symbol, SymbolKind};
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
7#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
8#[serde(rename_all = "snake_case")]
9pub enum BindingNamespace {
10    Type,
11    Value,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
16pub struct LexicalBinding {
17    pub symbol: Symbol,
18    /// Lexical owner, including synthetic successful-condition scopes.
19    pub scope: Span,
20    pub excluded: Vec<Span>,
21    /// Regions where the binding owns its name but is not yet initialized.
22    /// They prevent falling through to an outer binding in a temporal dead zone.
23    #[serde(default, skip_serializing_if = "Vec::is_empty")]
24    pub uninitialized: Vec<Span>,
25    /// Start of lexical ownership: delayed for sequential bindings, or the scope
26    /// start for parameters, generics and block-owned lexical declarations.
27    pub visible_from: usize,
28    pub namespace: BindingNamespace,
29    /// Syntax forces a binding rather than a possible constant pattern.
30    /// Older plugin facts remain conservative around unknown expansions.
31    #[serde(default)]
32    pub explicit: bool,
33}
34
35impl LexicalBinding {
36    pub fn initialized(&self, span: Span) -> bool {
37        !self
38            .uninitialized
39            .iter()
40            .any(|region| region.contains(&span))
41    }
42
43    pub fn visible(&self, name: &str, span: Span, namespace: BindingNamespace) -> bool {
44        self.symbol.name == name
45            && self.namespace == namespace
46            && self.scope.contains(&span)
47            && self.visible_from <= span.start
48            && !self.excluded.iter().any(|s| s.contains(&span))
49    }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
54pub struct NamedImport {
55    pub local: String,
56    pub imported: String,
57    pub module: Option<ModulePath>,
58    pub name_span: Span,
59    pub alias_span: Span,
60    pub reexport: bool,
61    pub type_only: bool,
62}
63
64/// A simple binding. Complex patterns remain unsupported rather than guessed.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct BindingRule {
67    pub node: &'static str,
68    /// `None` marks a binding form whose enclosing scope cannot be confirmed.
69    pub name: Option<&'static str>,
70    pub scopes: &'static [&'static str],
71    pub kind: SymbolKind,
72    pub namespace: BindingNamespace,
73    pub after: bool,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct NamedImportRule {
78    /// Field holding the imported name, or the first direct identifier child.
79    pub name: Option<&'static str>,
80    /// A fixed export name for default or namespace imports.
81    pub imported: Option<&'static str>,
82    pub node: &'static str,
83    pub statement: &'static str,
84    pub reexport: bool,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
89pub struct QualifiedImport {
90    pub span: Span,
91    pub binding: String,
92    pub member: String,
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub struct QualifiedImportRule {
97    pub node: &'static str,
98    pub object: &'static str,
99    pub member: &'static str,
100}
101
102/// A declaration directly owned by a navigation module, with visibility evidence.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
105pub struct ModuleDeclaration {
106    pub name_span: Span,
107    pub restriction: Option<ModulePath>,
108}
109
110/// File-relative module ownership used only by navigation.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
113pub struct ModuleScope {
114    pub path: Vec<Name>,
115    pub span: Span,
116    /// The inline module's name; absent for the file root.
117    pub declaration: Option<Span>,
118    pub declarations: Vec<ModuleDeclaration>,
119    pub imports: Vec<ImportBinding>,
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct ModuleScopeRule {
124    pub node: &'static str,
125    pub name: &'static str,
126    pub body: &'static str,
127}
128
129/// Block-wide named imports for navigation, independent of mutation bindings.
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
132pub struct ImportScope {
133    pub span: Span,
134    pub imports: Vec<ImportBinding>,
135    #[serde(default)]
136    pub aliases: Vec<Span>,
137}
138
139/// A macro whose expansion may introduce items throughout a block and locals
140/// after the invocation. This is navigation evidence, never mutation scope.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
143pub struct ScopeUncertainty {
144    pub scope: Span,
145    pub invocation: Span,
146}
147
148/// Macro positions whose expansion is required to be an expression.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub struct MacroScopeRule {
151    pub node: &'static str,
152    pub scopes: &'static [&'static str],
153    pub expression_containers: &'static [&'static str],
154    pub expression_fields: &'static [(&'static str, &'static str)],
155}
156
157/// How a pattern occurrence can use a name, independent of any parser.
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
159#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
160#[serde(rename_all = "snake_case")]
161pub enum PatternRole {
162    Identifier,
163    Constant,
164    Constructor,
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
169#[serde(rename_all = "snake_case")]
170pub enum ConstructorShape {
171    Unit,
172    Tuple,
173    Record,
174}
175
176/// Constructor syntax on a declaration; an enum variant names its owning enum.
177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
178#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
179pub struct PatternConstructor {
180    pub name_span: Span,
181    pub owner: Option<Span>,
182    pub shape: ConstructorShape,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
187pub struct PatternReference {
188    pub span: Span,
189    pub path: ModulePath,
190    pub role: PatternRole,
191    pub shape: Option<ConstructorShape>,
192}
193
194/// One possible binding site and its explicit syntactic mode.
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
197pub struct PatternBinding {
198    pub name: String,
199    pub span: Span,
200    pub by_ref: bool,
201    pub mutable: bool,
202}
203
204/// Direct alternatives; nested alternatives have their own constraint.
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
206#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
207pub struct PatternAlternatives {
208    pub branches: Vec<Vec<PatternBinding>>,
209}
210
211/// A supported pattern and the region reached by its possible bindings.
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
214pub struct PatternScope {
215    pub span: Span,
216    pub scope: Span,
217    pub excluded: Vec<Span>,
218    pub visible_from: usize,
219    pub references: Vec<PatternReference>,
220    pub alternatives: Vec<PatternAlternatives>,
221}
222
223impl PatternScope {
224    pub fn contains(&self, span: Span) -> bool {
225        self.span.contains(&span)
226            || (self.scope.contains(&span)
227                && self.visible_from <= span.start
228                && !self
229                    .excluded
230                    .iter()
231                    .any(|excluded| excluded.contains(&span)))
232    }
233}
234
235#[cfg(test)]
236mod initialization_tests {
237    use super::*;
238
239    #[test]
240    fn initialization_regions_preserve_binding_ownership() {
241        let mut binding = LexicalBinding {
242            symbol: Symbol::plain(SymbolKind::Variable, "x", Span::new(5, 6), Span::new(5, 9)),
243            scope: Span::new(0, 20),
244            excluded: vec![],
245            uninitialized: vec![],
246            visible_from: 0,
247            namespace: BindingNamespace::Value,
248            explicit: true,
249        };
250        assert!(binding.initialized(Span::new(2, 3)));
251        binding.uninitialized.push(Span::new(0, 5));
252        assert!(binding.visible("x", Span::new(2, 3), BindingNamespace::Value));
253        assert!(!binding.initialized(Span::new(2, 3)));
254        assert!(binding.initialized(Span::new(10, 11)));
255        assert_eq!(
256            serde_json::from_value::<LexicalBinding>(serde_json::to_value(&binding).unwrap())
257                .unwrap(),
258            binding
259        );
260    }
261}