Skip to main content

fallow_engine/
export_declarations.rs

1//! The exported variable declarations whose `export` keyword exports more
2//! than one name.
3//!
4//! One `export` keyword exports every name of `export const { a, b } = x;`,
5//! `export const [a, b] = x;` and `export const a = 1, b = 2;`. `fallow fix`
6//! can remove that keyword only when every one of these names is unused, so
7//! it must know all the names, also of a nested pattern, a default value or a
8//! rest element.
9
10use std::path::Path;
11
12use oxc_ast::ast::{Declaration, Program, Statement};
13use oxc_span::{GetSpan, SourceType};
14
15/// One top-level exported variable declaration that binds more than one
16/// name or binds its names through a destructuring pattern.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct SharedExportDeclaration {
19    /// The byte offset of the `export` keyword.
20    pub start: u32,
21    /// The byte offset after the end of the declaration.
22    pub end: u32,
23    /// Every name that the declaration binds, in source order.
24    pub names: Vec<String>,
25}
26
27/// The shared export declarations of the file at `path`.
28///
29/// A JavaScript or TypeScript file is parsed as a whole. A Vue or Svelte
30/// file is parsed per inline `<script>` block and an Astro file per
31/// frontmatter block. Each offset is an offset into `source`.
32///
33/// Returns `None` for another file type, or when a block does not parse
34/// cleanly. The caller then does not know the names that a declaration
35/// binds.
36#[must_use]
37pub fn shared_export_declarations(
38    path: &Path,
39    source: &str,
40) -> Option<Vec<SharedExportDeclaration>> {
41    if fallow_extract::is_sfc_file(path) {
42        let scripts = fallow_extract::extract_sfc_scripts(source);
43        return parse_blocks(scripts.iter().filter(|script| script.src.is_none()));
44    }
45    if path
46        .extension()
47        .is_some_and(|extension| extension == "astro")
48    {
49        let frontmatter = fallow_extract::astro::extract_astro_frontmatter(source);
50        return parse_blocks(frontmatter.iter());
51    }
52    let source_type = SourceType::from_path(path).ok()?;
53    parse_block(source, source_type, 0)
54}
55
56fn parse_blocks<'a>(
57    scripts: impl Iterator<Item = &'a fallow_extract::sfc::SfcScript>,
58) -> Option<Vec<SharedExportDeclaration>> {
59    let mut declarations = Vec::new();
60    for script in scripts {
61        let source_type = match (script.is_typescript, script.is_jsx) {
62            (true, true) => SourceType::tsx(),
63            (true, false) => SourceType::ts(),
64            (false, true) => SourceType::jsx(),
65            (false, false) => SourceType::mjs(),
66        };
67        let offset = u32::try_from(script.byte_offset).ok()?;
68        declarations.extend(parse_block(&script.body, source_type, offset)?);
69    }
70    Some(declarations)
71}
72
73/// Parse one block of script text that starts at byte `offset` of the file.
74fn parse_block(
75    source: &str,
76    source_type: SourceType,
77    offset: u32,
78) -> Option<Vec<SharedExportDeclaration>> {
79    fallow_extract::parse_bounded(source, || {
80        let allocator = oxc_allocator::Allocator::default();
81        let parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
82        if parsed.fatal_error || parsed.diagnostics.has_errors() {
83            return None;
84        }
85        Some(collect(&parsed.program, offset))
86    })
87    .flatten()
88}
89
90fn collect(program: &Program<'_>, offset: u32) -> Vec<SharedExportDeclaration> {
91    program
92        .body
93        .iter()
94        .filter_map(|statement| {
95            let Statement::ExportDeclaration(export) = statement else {
96                return None;
97            };
98            let Declaration::VariableDeclaration(variables) = &export.declaration else {
99                return None;
100            };
101            let is_pattern = variables
102                .declarations
103                .iter()
104                .any(|declarator| declarator.id.get_binding_identifier().is_none());
105            if variables.declarations.len() < 2 && !is_pattern {
106                return None;
107            }
108            let names = variables
109                .declarations
110                .iter()
111                .flat_map(|declarator| declarator.id.get_binding_identifiers())
112                .map(|identifier| identifier.name.to_string())
113                .collect();
114            let span = export.span();
115            Some(SharedExportDeclaration {
116                start: span.start + offset,
117                end: span.end + offset,
118                names,
119            })
120        })
121        .collect()
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    fn names(path: &str, source: &str) -> Option<Vec<Vec<String>>> {
129        shared_export_declarations(Path::new(path), source).map(|declarations| {
130            declarations
131                .into_iter()
132                .map(|declaration| declaration.names)
133                .collect()
134        })
135    }
136
137    #[test]
138    fn finds_every_name_of_each_pattern_form() {
139        let source = "export const { a = 1, b: { c }, ...rest } = x;\nexport let [d, , [e], ...f] = y;\nexport var g = 1, h = 2;\nexport const single = 1;\nexport function fn() {}\n";
140        assert_eq!(
141            names("store.ts", source),
142            Some(vec![
143                vec!["a".to_owned(), "c".to_owned(), "rest".to_owned()],
144                vec!["d".to_owned(), "e".to_owned(), "f".to_owned()],
145                vec!["g".to_owned(), "h".to_owned()],
146            ])
147        );
148    }
149
150    #[test]
151    fn spans_the_full_declaration() {
152        let source = "const x = {};\nexport const {\n  a,\n} = x;\n";
153        let declarations = shared_export_declarations(Path::new("store.ts"), source).unwrap();
154        let declaration = &declarations[0];
155        assert_eq!(
156            &source[declaration.start as usize..declaration.end as usize],
157            "export const {\n  a,\n} = x;"
158        );
159    }
160
161    /// The text of each declaration that `source` holds.
162    fn texts(path: &str, source: &str) -> Vec<String> {
163        shared_export_declarations(Path::new(path), source)
164            .unwrap()
165            .into_iter()
166            .map(|declaration| {
167                source[declaration.start as usize..declaration.end as usize].to_owned()
168            })
169            .collect()
170    }
171
172    #[test]
173    fn reads_each_script_block_of_a_vue_file() {
174        let source = "<template><div /></template>\n<script lang=\"ts\">\nexport const c = 1, d = 2;\n</script>\n<script setup lang=\"ts\">\nconst e = 1;\n</script>\n";
175        assert_eq!(
176            texts("store.vue", source),
177            vec!["export const c = 1, d = 2;"]
178        );
179        assert_eq!(
180            names("store.vue", source),
181            Some(vec![vec!["c".to_owned(), "d".to_owned()]])
182        );
183    }
184
185    #[test]
186    fn reads_the_module_script_of_a_svelte_file() {
187        let source =
188            "<script context=\"module\">\n  export const { a, b } = x;\n</script>\n<p>hi</p>\n";
189        assert_eq!(
190            texts("store.svelte", source),
191            vec!["export const { a, b } = x;"]
192        );
193    }
194
195    #[test]
196    fn reads_the_frontmatter_of_an_astro_file() {
197        let source = "---\nexport const [a, b] = [1, 2];\n---\n<p>{a}</p>\n";
198        assert_eq!(
199            texts("page.astro", source),
200            vec!["export const [a, b] = [1, 2];"]
201        );
202    }
203
204    #[test]
205    fn gives_none_for_another_file_type() {
206        assert_eq!(names("notes.md", "export const { a, b } = x;\n"), None);
207    }
208
209    #[test]
210    fn gives_none_for_a_file_that_does_not_parse() {
211        assert_eq!(
212            names("store.ts", "export const [a, b] = x;\nexport const = ;\n"),
213            None
214        );
215    }
216}