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