parsec_js/module.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! What a module imports and exports: the spec's ImportEntry and
5//! ExportEntry records (ECMA-262 16.2.1.6), read from the tree.
6//!
7//! A bundler, a linter or a code-search tool can build a module graph
8//! from these without resolving a file: [`ModuleRecord::requested_modules`]
9//! are the edges, and the entries say which names cross each one. The
10//! entries are sorted as ParseModule sorts them: exports of local names,
11//! re-exports of one name (`export { a } from "m"`, and an imported name
12//! exported again), and `export * from "m"`.
13//!
14//! ```
15//! use parsec_js::module::{ImportName, ModuleRecord};
16//! use parsec_js::{Options, SourceType, parse};
17//!
18//! let src = r#"import { readFile as read } from "node:fs";
19//! import config from "./config.json" with { type: "json" };
20//! export { read };
21//! export default function main() {}"#;
22//! let options = Options { source_type: SourceType::Module, ..Options::default() };
23//! let ast = parse(src, &options).unwrap();
24//! let record = ModuleRecord::new(&ast, src);
25//!
26//! let specifiers: Vec<_> = record.requested_modules.iter().map(|m| m.specifier.as_str()).collect();
27//! assert_eq!(specifiers, ["node:fs", "./config.json"]);
28//! assert_eq!(record.requested_modules[1].attributes, [("type".to_string(), "json".to_string())]);
29//! assert_eq!(record.import_entries[0].import_name, ImportName::Name("readFile".into()));
30//! assert_eq!(record.import_entries[0].local_name, "read");
31//! // `read` is imported, so exporting it is a re-export of node:fs's
32//! // readFile.
33//! assert_eq!(record.indirect_export_entries[0].export_name.as_deref(), Some("read"));
34//! assert_eq!(record.local_export_entries[0].local_name.as_deref(), Some("main"));
35//! ```
36//!
37//! Strings are Rust strings: a specifier with a lone surrogate in it,
38//! `"\uD800"`, has U+FFFD in its place. Export and import names can't
39//! have one; the parser rejects them.
40
41use std::collections::HashMap;
42
43use parsec_base::Span;
44
45use crate::ast::{Ast, Node, NodeId};
46use crate::text;
47
48/// A module a module asks for: its specifier and import attributes.
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct ModuleRequest {
51 /// The string after `from`, or after `import`, decoded.
52 pub specifier: String,
53 /// The `with { key: "value" }` attributes, sorted by key as the spec
54 /// sorts them (by UTF-16 code units).
55 pub attributes: Vec<(String, String)>,
56 /// Where the specifier's string literal first appears.
57 pub span: Span,
58}
59
60/// What an ImportEntry imports.
61#[derive(Clone, Debug, PartialEq, Eq)]
62pub enum ImportName {
63 /// An export by name; `default` for a default import.
64 Name(String),
65 /// The whole namespace, `import * as ns`.
66 NamespaceObject,
67}
68
69/// One name a module imports.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct ImportEntry {
72 /// Its index in [`ModuleRecord::requested_modules`].
73 pub module_request: usize,
74 pub import_name: ImportName,
75 /// The name it's bound to here.
76 pub local_name: String,
77 /// The import specifier it comes from.
78 pub span: Span,
79}
80
81/// What an ExportEntry re-exports from another module.
82#[derive(Clone, Debug, PartialEq, Eq)]
83pub enum ExportImportName {
84 /// One export by name.
85 Name(String),
86 /// `export * as ns from "m"`: the whole namespace.
87 All,
88 /// `export * from "m"`: every export but `default`.
89 AllButDefault,
90}
91
92/// One name a module exports.
93#[derive(Clone, Debug, PartialEq, Eq)]
94pub struct ExportEntry {
95 /// The name it's exported as; `None` for `export * from "m"`.
96 pub export_name: Option<String>,
97 /// For a re-export, its index in [`ModuleRecord::requested_modules`].
98 pub module_request: Option<usize>,
99 pub import_name: Option<ExportImportName>,
100 /// The local binding it exports; `*default*` for `export default`
101 /// with an expression or an anonymous declaration.
102 pub local_name: Option<String>,
103 /// The node it comes from: a specifier, a declared name, an `export
104 /// default` or an `export *`.
105 pub span: Span,
106}
107
108/// A module's imports and exports, as ParseModule records them.
109#[derive(Clone, Debug, Default, PartialEq, Eq)]
110pub struct ModuleRecord {
111 /// Each module requested, once, in the order first requested; two
112 /// requests are one when their specifiers and attributes are the
113 /// same.
114 pub requested_modules: Vec<ModuleRequest>,
115 pub import_entries: Vec<ImportEntry>,
116 /// Exports of the module's own bindings, and of an imported
117 /// namespace exported again.
118 pub local_export_entries: Vec<ExportEntry>,
119 /// Re-exports of one name from another module.
120 pub indirect_export_entries: Vec<ExportEntry>,
121 /// `export * from "m"`.
122 pub star_export_entries: Vec<ExportEntry>,
123}
124
125impl ModuleRecord {
126 /// The records for `ast`, parsed from `src`. A script's are empty.
127 pub fn new(ast: &Ast, src: &str) -> ModuleRecord {
128 let mut record = ModuleRecord::default();
129 let mut requests = Requests::new();
130 let Node::Program { body, .. } = *ast.node(ast.root()) else {
131 unreachable!("the root is a program")
132 };
133 let mut exports = Vec::new();
134 for &item in ast.get(body) {
135 match *ast.node(item) {
136 Node::ImportDeclaration {
137 specifiers,
138 source,
139 attributes,
140 } => {
141 let request = record.request(&mut requests, ast, src, source, attributes);
142 for &spec in ast.get(specifiers) {
143 let (import_name, local) = match *ast.node(spec) {
144 Node::ImportSpecifier { imported, local } => {
145 (ImportName::Name(export_name(ast, src, imported)), local)
146 }
147 Node::ImportDefaultSpecifier { local } => {
148 (ImportName::Name("default".into()), local)
149 }
150 Node::ImportNamespaceSpecifier { local } => {
151 (ImportName::NamespaceObject, local)
152 }
153 _ => continue,
154 };
155 record.import_entries.push(ImportEntry {
156 module_request: request,
157 import_name,
158 local_name: name(ast, src, local),
159 span: ast.span(spec),
160 });
161 }
162 }
163 Node::ExportNamed {
164 declaration: Some(declaration),
165 ..
166 } => {
167 for id in declared(ast, declaration) {
168 let n = name(ast, src, id);
169 exports.push(local_export(Some(n.clone()), n, ast.span(id)));
170 }
171 }
172 Node::ExportNamed {
173 declaration: None,
174 specifiers,
175 source,
176 attributes,
177 } => {
178 let request =
179 source.map(|s| record.request(&mut requests, ast, src, s, attributes));
180 for &spec in ast.get(specifiers) {
181 let Node::ExportSpecifier { local, exported } = *ast.node(spec) else {
182 continue;
183 };
184 let local_name = export_name(ast, src, local);
185 let exported = Some(export_name(ast, src, exported));
186 let span = ast.span(spec);
187 exports.push(match request {
188 None => local_export(exported, local_name, span),
189 Some(r) => ExportEntry {
190 export_name: exported,
191 module_request: Some(r),
192 import_name: Some(ExportImportName::Name(local_name)),
193 local_name: None,
194 span,
195 },
196 });
197 }
198 }
199 Node::ExportDefault { declaration } => {
200 let own = match *ast.node(declaration) {
201 Node::Function(f) if f.kind == crate::ast::FunctionKind::Declaration => {
202 f.id
203 }
204 Node::Class(c) if c.declaration => c.id,
205 _ => None,
206 };
207 let local =
208 own.map_or_else(|| "*default*".to_string(), |id| name(ast, src, id));
209 exports.push(local_export(Some("default".into()), local, ast.span(item)));
210 }
211 Node::ExportAll {
212 exported,
213 source,
214 attributes,
215 } => {
216 let request = record.request(&mut requests, ast, src, source, attributes);
217 let export_name = exported.map(|e| export_name(ast, src, e));
218 let import_name = if export_name.is_some() {
219 ExportImportName::All
220 } else {
221 ExportImportName::AllButDefault
222 };
223 exports.push(ExportEntry {
224 export_name,
225 module_request: Some(request),
226 import_name: Some(import_name),
227 local_name: None,
228 span: ast.span(item),
229 });
230 }
231 _ => {}
232 }
233 }
234 // Early errors allow each local name to be imported once, so the
235 // first entry is the only one.
236 let mut by_local: HashMap<&str, usize> = HashMap::new();
237 for (i, ie) in record.import_entries.iter().enumerate() {
238 by_local.entry(ie.local_name.as_str()).or_insert(i);
239 }
240 for ee in exports {
241 match (&ee.module_request, &ee.import_name) {
242 (None, _) => {
243 let imported = ee
244 .local_name
245 .as_deref()
246 .and_then(|l| by_local.get(l))
247 .map(|&i| &record.import_entries[i]);
248 match imported {
249 None
250 | Some(ImportEntry {
251 import_name: ImportName::NamespaceObject,
252 ..
253 }) => record.local_export_entries.push(ee),
254 Some(ie) => {
255 let ImportName::Name(n) = &ie.import_name else {
256 unreachable!("matched above")
257 };
258 let entry = ExportEntry {
259 export_name: ee.export_name,
260 module_request: Some(ie.module_request),
261 import_name: Some(ExportImportName::Name(n.clone())),
262 local_name: None,
263 span: ee.span,
264 };
265 record.indirect_export_entries.push(entry);
266 }
267 }
268 }
269 (Some(_), Some(ExportImportName::AllButDefault)) => {
270 record.star_export_entries.push(ee)
271 }
272 (Some(_), _) => record.indirect_export_entries.push(ee),
273 }
274 }
275 record
276 }
277
278 /// The index of the request for `source` with `attributes`, added if
279 /// it's new.
280 fn request(
281 &mut self,
282 requests: &mut Requests,
283 ast: &Ast,
284 src: &str,
285 source: NodeId,
286 attributes: crate::ast::List,
287 ) -> usize {
288 let mut attrs: Vec<(Vec<u16>, Vec<u16>)> = ast
289 .get(attributes)
290 .iter()
291 .filter_map(|&a| match *ast.node(a) {
292 Node::ImportAttribute { key, value } => {
293 let key = match ast.node(key) {
294 Node::Literal(_) => string_units(ast, src, key),
295 _ => name(ast, src, key).encode_utf16().collect(),
296 };
297 Some((key, string_units(ast, src, value)))
298 }
299 _ => None,
300 })
301 .collect();
302 attrs.sort();
303 // Compared as UTF-16, so two lone surrogates that both read as
304 // U+FFFD stay two requests.
305 let key = (string_units(ast, src, source), attrs);
306 if let Some(&i) = requests.get(&key) {
307 return i;
308 }
309 let (specifier, attrs) = &key;
310 self.requested_modules.push(ModuleRequest {
311 specifier: String::from_utf16_lossy(specifier),
312 attributes: attrs
313 .iter()
314 .map(|(k, v)| (String::from_utf16_lossy(k), String::from_utf16_lossy(v)))
315 .collect(),
316 span: ast.span(source),
317 });
318 let i = self.requested_modules.len() - 1;
319 requests.insert(key, i);
320 i
321 }
322}
323
324fn local_export(export_name: Option<String>, local_name: String, span: Span) -> ExportEntry {
325 ExportEntry {
326 export_name,
327 module_request: None,
328 import_name: None,
329 local_name: Some(local_name),
330 span,
331 }
332}
333
334/// An identifier's name, escapes decoded.
335fn name(ast: &Ast, src: &str, id: NodeId) -> String {
336 text::ident_name(ast.span(id).text(src)).into_owned()
337}
338
339/// A string literal's value.
340/// A request's specifier and sorted attributes, as UTF-16, to its index.
341type Requests = HashMap<(Vec<u16>, Vec<(Vec<u16>, Vec<u16>)>), usize>;
342
343fn string(ast: &Ast, src: &str, id: NodeId) -> String {
344 String::from_utf16_lossy(&string_units(ast, src, id))
345}
346
347/// A string literal's value, as the UTF-16 code units the spec compares.
348fn string_units(ast: &Ast, src: &str, id: NodeId) -> Vec<u16> {
349 let span = ast.span(id);
350 let body = Span::new(span.start + 1, span.end - 1).text(src);
351 text::string_value(body)
352}
353
354/// A ModuleExportName: an identifier name or a string.
355fn export_name(ast: &Ast, src: &str, id: NodeId) -> String {
356 match ast.node(id) {
357 Node::Literal(_) => string(ast, src, id),
358 _ => name(ast, src, id),
359 }
360}
361
362/// The identifiers a declaration after `export` declares, in order.
363fn declared(ast: &Ast, declaration: NodeId) -> Vec<NodeId> {
364 let mut out = Vec::new();
365 match *ast.node(declaration) {
366 Node::VariableDeclaration { declarations, .. } => {
367 let mut stack: Vec<NodeId> = ast
368 .get(declarations)
369 .iter()
370 .rev()
371 .filter_map(|&d| match *ast.node(d) {
372 Node::VariableDeclarator { id, .. } => Some(id),
373 _ => None,
374 })
375 .collect();
376 while let Some(id) = stack.pop() {
377 let before = stack.len();
378 match *ast.node(id) {
379 Node::Identifier => out.push(id),
380 Node::ObjectPattern { properties } => {
381 for &p in ast.get(properties) {
382 match *ast.node(p) {
383 Node::Property { value, .. } => stack.push(value),
384 Node::Rest { argument } => stack.push(argument),
385 _ => {}
386 }
387 }
388 }
389 Node::ArrayPattern { elements } => {
390 stack.extend(
391 ast.get(elements)
392 .iter()
393 .filter(|&&e| !matches!(ast.node(e), Node::Elision)),
394 );
395 }
396 Node::Rest { argument } => stack.push(argument),
397 Node::AssignmentPattern { left, .. } => stack.push(left),
398 _ => {}
399 }
400 // In source order: the children just pushed, first on top.
401 stack[before..].reverse();
402 }
403 }
404 Node::Function(f) => out.extend(f.id),
405 Node::Class(c) => out.extend(c.id),
406 _ => {}
407 }
408 out
409}