Skip to main content

vvv_core/import/
mod.rs

1//! Import references as data, and the declarative rules that find them.
2//!
3//! A language names other files or modules with paths: `crate::foo::bar` in
4//! Rust, `'./foo/bar'` in TypeScript. [`ImportRef`] is one such path in one
5//! file; [`ImportRule`]s tell the generic extractor in `vvv-lang` where the
6//! grammar puts them. Resolving what a path *means* is the job of a
7//! [`Layout`](crate::resolve::Layout).
8
9use serde::{Deserialize, Serialize};
10
11use crate::paths::{ModulePath, Name, PathSyntax};
12use crate::text::Span;
13
14/// One path in one file. `span` covers exactly the text a rewrite replaces.
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
17pub struct ImportRef {
18    pub span: Span,
19    /// The full path as written (`crate::a::b`, `../x/y`), parsed by the
20    /// grammar's [`PathSyntax`]. For a grouped entry this includes the
21    /// group's prefix.
22    pub path: ModulePath,
23    /// Present when the path is an entry of a grouped import such as
24    /// `use a::{b, c::d}`; replacing `span` alone can then only express
25    /// paths that stay under the group's prefix.
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub group: Option<ImportGroup>,
28    /// `use a::b::*`: every name under the path is brought into scope.
29    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
30    pub glob: bool,
31    /// Part of an import statement (`use`, `import`), so it brings its last
32    /// segment into the file's scope. A qualified path in an expression
33    /// (`fff::GrepMatch` in a type position) is a reference to rewrite on a
34    /// move, but declares nothing.
35    #[serde(default = "yes", skip_serializing_if = "std::ops::Not::not")]
36    pub declares: bool,
37    /// A `pub use`, an `export … from`: the name it brings in is offered on
38    /// again under this file's address, so a path to it here reaches the
39    /// original declaration.
40    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
41    pub reexport: bool,
42    /// The name the statement binds instead of the path's last segment:
43    /// `Cfg` in `use a::Config as Cfg`.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub alias: Option<Name>,
46}
47
48fn yes() -> bool {
49    true
50}
51
52impl ImportRef {
53    pub fn new(span: Span, path: ModulePath) -> Self {
54        Self {
55            span,
56            path,
57            group: None,
58            glob: false,
59            declares: true,
60            reexport: false,
61            alias: None,
62        }
63    }
64
65    pub fn glob(mut self) -> Self {
66        self.glob = true;
67        self
68    }
69
70    pub fn reexporting(mut self) -> Self {
71        self.reexport = true;
72        self
73    }
74
75    pub fn aliased(mut self, alias: impl Into<Name>) -> Self {
76        self.alias = Some(alias.into());
77        self
78    }
79
80    /// The name the import brings into scope: its alias, else the path's
81    /// last segment; a glob binds nothing nameable.
82    pub fn binding(&self) -> Option<&Name> {
83        if self.glob {
84            return None;
85        }
86        self.alias.as_ref().or_else(|| self.path.last())
87    }
88
89    /// True when replacing `span` with any path is a complete rewrite.
90    pub fn is_standalone(&self) -> bool {
91        self.group.is_none()
92    }
93}
94
95/// Evidence that an import statement binds a name in the file's module.
96/// Missing evidence does not authorize cross-file binding lookup.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
99pub struct ImportBinding {
100    pub span: Span,
101    pub visibility: Option<crate::Modifier>,
102    pub restriction: Option<ModulePath>,
103}
104
105/// Where a grouped entry sits, so a surgery can rewrite it in place or move
106/// it out of the group.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
109pub struct ImportGroup {
110    /// Combined prefix of the enclosing groups (`crate::util`).
111    pub prefix: ModulePath,
112    /// The whole entry, alias or nested list included (`parse::Config as Cfg`).
113    pub item: Span,
114    /// The innermost list the entry belongs to, braces included.
115    pub list: Span,
116    /// How many entries that list has.
117    pub items: usize,
118    /// The enclosing statement (`pub use crate::util::{…};`).
119    pub statement: Span,
120    /// Whether `list` is the statement's own list rather than a nested one.
121    pub top_level: bool,
122}
123
124/// Where a grammar keeps import paths.
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum ImportRule {
127    /// Nodes of this kind carry a path: in `field` when given, else the node
128    /// itself. Only the outermost such node counts, so `crate::a::b` is one
129    /// reference even though its parser tree nests three `scoped_identifier`s.
130    Node {
131        kind: &'static str,
132        field: Option<&'static str>,
133        /// Only when the direct parent has this kind.
134        under: Option<&'static str>,
135    },
136    /// An ast-grep pattern whose `capture` holds the path.
137    Pattern {
138        pattern: &'static str,
139        capture: &'static str,
140    },
141}
142
143impl ImportRule {
144    pub const fn node(kind: &'static str) -> Self {
145        Self::Node {
146            kind,
147            field: None,
148            under: None,
149        }
150    }
151
152    pub const fn field(kind: &'static str, field: &'static str) -> Self {
153        Self::Node {
154            kind,
155            field: Some(field),
156            under: None,
157        }
158    }
159
160    pub const fn under(self, parent: &'static str) -> Self {
161        match self {
162            Self::Node { kind, field, .. } => Self::Node {
163                kind,
164                field,
165                under: Some(parent),
166            },
167            other => other,
168        }
169    }
170
171    pub const fn pattern(pattern: &'static str, capture: &'static str) -> Self {
172        Self::Pattern { pattern, capture }
173    }
174}
175
176/// How paths nest inside grouped imports such as Rust's `use a::{b, c::d}`.
177///
178/// An entry found under a `list` node gets the enclosing `scope` nodes'
179/// `prefix_field` texts prepended (outermost first, joined by the grammar's
180/// [`PathSyntax`]) and carries an [`ImportGroup`] describing its place in
181/// the `statement`.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub struct ImportNesting {
184    pub list: &'static str,
185    pub scope: &'static str,
186    pub prefix_field: &'static str,
187    pub statement: &'static str,
188}
189
190/// Where an import's alias is written: the path sits under a node of this
191/// kind, which holds the alias in `field` (Rust's `use_as_clause`, field
192/// `alias`).
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub struct AliasRule {
195    pub under: &'static str,
196    pub field: &'static str,
197}
198
199/// What makes an import statement a re-export.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
201pub enum ReExportRule {
202    /// The language has none vvv follows.
203    #[default]
204    Never,
205    /// The statement carries a child of this kind (Rust's
206    /// `visibility_modifier` on a `use_declaration`).
207    Modifier(&'static str),
208    /// The statement kind itself re-exports (TypeScript's `export_statement`
209    /// with a source).
210    Statement(&'static str),
211}
212
213/// A language's complete description of where its import paths live.
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub struct ImportGrammar {
216    /// How the language spells a path: what the rules' text is parsed with.
217    pub syntax: PathSyntax,
218    /// Root node whose direct import statements bind module-visible names.
219    pub module_root: Option<&'static str>,
220    pub rules: &'static [ImportRule],
221    /// Which statements re-export what they import.
222    pub reexports: ReExportRule,
223    pub nesting: Option<ImportNesting>,
224    /// Node kind whose path child is a glob import (`use_wildcard` in Rust).
225    pub glob_under: Option<&'static str>,
226    /// Text every glob import contains (`::*` in Rust): what a file must
227    /// spell to be worth parsing when only globs are looked for.
228    pub glob_marker: Option<&'static str>,
229    /// Where an `as` alias is found, in languages that spell one on a path.
230    pub alias: Option<AliasRule>,
231    /// Node kinds of import statements. A path found under one declares its
232    /// name; a path found elsewhere is a reference. Empty means every path
233    /// the rules find is a statement.
234    pub statements: &'static [&'static str],
235}
236
237impl ImportGrammar {
238    pub const EMPTY: Self = Self {
239        syntax: PathSyntax::Scoped,
240        module_root: None,
241        rules: &[],
242        reexports: ReExportRule::Never,
243        nesting: None,
244        glob_under: None,
245        glob_marker: None,
246        alias: None,
247        statements: &[],
248    };
249
250    pub const fn new(syntax: PathSyntax, rules: &'static [ImportRule]) -> Self {
251        Self {
252            syntax,
253            module_root: None,
254            rules,
255            reexports: ReExportRule::Never,
256            nesting: None,
257            glob_under: None,
258            glob_marker: None,
259            alias: None,
260            statements: &[],
261        }
262    }
263
264    pub const fn module_bindings(mut self, root: &'static str) -> Self {
265        self.module_root = Some(root);
266        self
267    }
268
269    pub const fn aliased_by(mut self, parent: &'static str, field: &'static str) -> Self {
270        self.alias = Some(AliasRule {
271            under: parent,
272            field,
273        });
274        self
275    }
276
277    pub const fn statements(mut self, kinds: &'static [&'static str]) -> Self {
278        self.statements = kinds;
279        self
280    }
281
282    pub const fn nested(mut self, nesting: ImportNesting) -> Self {
283        self.nesting = Some(nesting);
284        self
285    }
286
287    pub const fn reexports(mut self, rule: ReExportRule) -> Self {
288        self.reexports = rule;
289        self
290    }
291
292    /// Globs are the paths under `parent`, and every one spells `marker`.
293    pub const fn globs_under(mut self, parent: &'static str, marker: &'static str) -> Self {
294        self.glob_under = Some(parent);
295        self.glob_marker = Some(marker);
296        self
297    }
298}