bun_js_parser 0.1.1

A Rust-native programmable browser runtime built on Servo and SpiderMonkey
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use crate::lexer::{self as js_lexer, T};
use crate::p::P;
use crate::parser::{ExportClauseResult, ImportClause, is_eval_or_arguments};
use bun_alloc::ArenaVecExt as _;
use bun_ast::LexerLog as _;
use bun_ast::expr::Data as ExprData;
use bun_ast::op::Level;
use bun_ast::{ClauseItem, E, Expr, LocRef};
use bun_core::Error;

// Zig: `fn ParseImportExport(comptime ts, comptime jsx, comptime scan_only) type { return struct { ... } }`
// — file-split mixin pattern. Round-C lowered `const JSX: JSXTransformType` → `J: JsxT`, so this is
// a direct `impl P` block.

impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_ONLY> {
    /// Note: The caller has already parsed the "import" keyword
    pub fn parse_import_expr(&mut self, loc: bun_ast::Loc, level: Level) -> Result<Expr, Error> {
        let p = self;
        // Parse an "import.meta" expression
        if p.lexer.token == T::TDot {
            p.esm_import_keyword = js_lexer::range_of_identifier(p.source, loc);
            p.lexer.next()?;
            if p.lexer.is_contextual_keyword(b"meta") {
                p.lexer.next()?;
                p.has_import_meta = true;
                return Ok(p.new_expr(E::ImportMeta {}, loc));
            } else {
                p.lexer.expected_string(b"\"meta\"")?;
            }
        }

        if level.gt(Level::Call) {
            let r = js_lexer::range_of_identifier(p.source, loc);
            p.log().add_range_error(
                Some(p.source),
                r,
                b"Cannot use an \"import\" expression here without parentheses",
            );
        }

        // allow "in" inside call arguments;
        let old_allow_in = p.allow_in;
        p.allow_in = true;

        p.lexer.preserve_all_comments_before = true;
        p.lexer.expect(T::TOpenParen)?;

        // const comments = try p.lexer.comments_to_preserve_before.toOwnedSlice();
        p.lexer.comments_to_preserve_before.clear();

        p.lexer.preserve_all_comments_before = false;

        let mut value = p.parse_expr(Level::Comma)?;

        let mut import_options = Expr::EMPTY;
        if p.lexer.token == T::TComma {
            // "import('./foo.json', )"
            p.lexer.next()?;

            if p.lexer.token != T::TCloseParen {
                // "import('./foo.json', { assert: { type: 'json' } })"
                import_options = p.parse_expr(Level::Comma)?;

                if p.lexer.token == T::TComma {
                    // "import('./foo.json', { assert: { type: 'json' } }, )"
                    p.lexer.next()?;
                }
            }
        }

        p.lexer.expect(T::TCloseParen)?;

        p.allow_in = old_allow_in;

        if SCAN_ONLY {
            // PORT NOTE: reshaped for borrowck — EString::slice takes &mut self (rope flatten),
            // so capture the slice (arena-lifetime) before re-using `value` by-value below.
            let slice_opt: Option<&'a [u8]> = if let ExprData::EString(e_string) = &mut value.data {
                if e_string.is_utf8() && e_string.is_present() {
                    Some(e_string.slice(p.arena))
                } else {
                    None
                }
            } else {
                None
            };
            if let Some(slice) = slice_opt {
                let import_record_index =
                    p.add_import_record(bun_ast::ImportKind::Dynamic, value.loc, slice);
                return Ok(p.new_expr(
                    E::Import {
                        expr: value,
                        import_record_index,
                        options: import_options,
                    },
                    loc,
                ));
            }
        }

        // _ = comments; // TODO: leading_interior comments

        Ok(p.new_expr(
            E::Import {
                expr: value,
                // .leading_interior_comments = comments,
                import_record_index: u32::MAX,
                options: import_options,
            },
            loc,
        ))
    }

    pub fn parse_import_clause(&mut self) -> Result<ImportClause<'a>, Error> {
        let p = self;
        // TODO(port): narrow error set
        let mut items = bun_alloc::ArenaVec::<ClauseItem>::new_in(p.arena);
        p.lexer.expect(T::TOpenBrace)?;
        let mut is_single_line = !p.lexer.has_newline_before;
        // this variable should not exist if we're not in a typescript file
        // PORT NOTE: in Zig this var was comptime-gated to only exist when TS is enabled;
        // in Rust we declare it unconditionally — dead-store elim removes it when !TS.
        let mut had_type_only_imports = false;

        while p.lexer.token != T::TCloseBrace {
            // The alias may be a keyword;
            let is_identifier = p.lexer.token == T::TIdentifier;
            let alias_loc = p.lexer.loc();
            let alias = p.parse_clause_alias(b"import")?;
            let mut name = LocRef {
                loc: alias_loc,
                ref_: Some(p.store_name_in_ref(alias)?),
            };
            let mut original_name = alias;
            p.lexer.next()?;

            let probably_type_only_import = if TYPESCRIPT {
                alias == b"type" && p.lexer.token != T::TComma && p.lexer.token != T::TCloseBrace
            } else {
                false
            };

            // "import { type xx } from 'mod'"
            // "import { type xx as yy } from 'mod'"
            // "import { type 'xx' as yy } from 'mod'"
            // "import { type as } from 'mod'"
            // "import { type as as } from 'mod'"
            // "import { type as as as } from 'mod'"
            if probably_type_only_import {
                if p.lexer.is_contextual_keyword(b"as") {
                    p.lexer.next()?;
                    if p.lexer.is_contextual_keyword(b"as") {
                        original_name = p.lexer.identifier;
                        name = LocRef {
                            loc: p.lexer.loc(),
                            ref_: Some(p.store_name_in_ref(original_name)?),
                        };
                        p.lexer.next()?;

                        if p.lexer.token == T::TIdentifier {
                            // "import { type as as as } from 'mod'"
                            // "import { type as as foo } from 'mod'"
                            had_type_only_imports = true;
                            p.lexer.next()?;
                        } else {
                            // "import { type as as } from 'mod'"

                            items.push(ClauseItem {
                                alias: alias.into(),
                                alias_loc,
                                name,
                                original_name: original_name.into(),
                            });
                        }
                    } else if p.lexer.token == T::TIdentifier {
                        had_type_only_imports = true;

                        // "import { type as xxx } from 'mod'"
                        original_name = p.lexer.identifier;
                        name = LocRef {
                            loc: p.lexer.loc(),
                            ref_: Some(p.store_name_in_ref(original_name)?),
                        };
                        p.lexer.expect(T::TIdentifier)?;

                        if is_eval_or_arguments(original_name) {
                            let r = p.source.range_of_string(name.loc);
                            p.log().add_range_error_fmt(
                                Some(p.source),
                                r,
                                format_args!(
                                    "Cannot use {} as an identifier here",
                                    bstr::BStr::new(original_name)
                                ),
                            );
                        }

                        items.push(ClauseItem {
                            alias: alias.into(),
                            alias_loc,
                            name,
                            original_name: original_name.into(),
                        });
                    }
                } else {
                    let is_identifier_inner = p.lexer.token == T::TIdentifier;

                    // "import { type xx } from 'mod'"
                    // "import { type xx as yy } from 'mod'"
                    // "import { type if as yy } from 'mod'"
                    // "import { type 'xx' as yy } from 'mod'"
                    let _ = p.parse_clause_alias(b"import")?;
                    p.lexer.next()?;

                    if p.lexer.is_contextual_keyword(b"as") {
                        p.lexer.next()?;

                        p.lexer.expect(T::TIdentifier)?;
                    } else if !is_identifier_inner {
                        // An import where the name is a keyword must have an alias
                        p.lexer.expected_string(b"\"as\"")?;
                    }
                    had_type_only_imports = true;
                }
            } else {
                if p.lexer.is_contextual_keyword(b"as") {
                    p.lexer.next()?;
                    original_name = p.lexer.identifier;
                    name = LocRef {
                        loc: alias_loc,
                        ref_: Some(p.store_name_in_ref(original_name)?),
                    };
                    p.lexer.expect(T::TIdentifier)?;
                } else if !is_identifier {
                    // An import where the name is a keyword must have an alias
                    p.lexer.expected_string(b"\"as\"")?;
                }

                // Reject forbidden names
                if is_eval_or_arguments(original_name) {
                    let r = js_lexer::range_of_identifier(p.source, name.loc);
                    p.log().add_range_error_fmt(
                        Some(p.source),
                        r,
                        format_args!(
                            "Cannot use \"{}\" as an identifier here",
                            bstr::BStr::new(original_name)
                        ),
                    );
                }

                items.push(ClauseItem {
                    alias: alias.into(),
                    alias_loc,
                    name,
                    original_name: original_name.into(),
                });
            }

            if p.lexer.token != T::TComma {
                break;
            }

            if p.lexer.has_newline_before {
                is_single_line = false;
            }

            p.lexer.next()?;

            if p.lexer.has_newline_before {
                is_single_line = false;
            }
        }

        if p.lexer.has_newline_before {
            is_single_line = false;
        }

        p.lexer.expect(T::TCloseBrace)?;
        Ok(ImportClause {
            items: items.into_bump_slice_mut(),
            is_single_line,
            had_type_only_imports: if TYPESCRIPT {
                had_type_only_imports
            } else {
                false
            },
        })
    }

    pub fn parse_export_clause(&mut self) -> Result<ExportClauseResult<'a>, Error> {
        let p = self;
        // TODO(port): narrow error set
        let mut items = bun_alloc::ArenaVec::<ClauseItem>::with_capacity_in(1, p.arena);
        p.lexer.expect(T::TOpenBrace)?;
        let mut is_single_line = !p.lexer.has_newline_before;
        let mut first_non_identifier_loc = bun_ast::Loc { start: 0 };
        let mut had_type_only_exports = false;

        while p.lexer.token != T::TCloseBrace {
            let mut alias = p.parse_clause_alias(b"export")?;
            let mut alias_loc = p.lexer.loc();

            let name = LocRef {
                loc: alias_loc,
                ref_: Some(p.store_name_in_ref(alias).expect("unreachable")),
            };
            let original_name = alias;

            // The name can actually be a keyword if we're really an "export from"
            // statement. However, we won't know until later. Allow keywords as
            // identifiers for now and throw an error later if there's no "from".
            //
            //   // This is fine
            //   export { default } from 'path'
            //
            //   // This is a syntax error
            //   export { default }
            //
            if p.lexer.token != T::TIdentifier && first_non_identifier_loc.start == 0 {
                first_non_identifier_loc = p.lexer.loc();
            }
            p.lexer.next()?;

            if TYPESCRIPT {
                if alias == b"type" && p.lexer.token != T::TComma && p.lexer.token != T::TCloseBrace
                {
                    if p.lexer.is_contextual_keyword(b"as") {
                        p.lexer.next()?;

                        if p.lexer.is_contextual_keyword(b"as") {
                            alias = p.parse_clause_alias(b"export")?;
                            alias_loc = p.lexer.loc();
                            p.lexer.next()?;

                            if p.lexer.token != T::TComma && p.lexer.token != T::TCloseBrace {
                                // "export { type as as as }"
                                // "export { type as as foo }"
                                // "export { type as as 'foo' }"
                                let _ = p.parse_clause_alias(b"export").unwrap_or(b"");
                                had_type_only_exports = true;
                                p.lexer.next()?;
                            } else {
                                // "export { type as as }"
                                items.push(ClauseItem {
                                    alias: alias.into(),
                                    alias_loc,
                                    name,
                                    original_name: original_name.into(),
                                });
                                // PERF(port): was assume_capacity (catch unreachable on append)
                            }
                        } else if p.lexer.token != T::TComma && p.lexer.token != T::TCloseBrace {
                            // "export { type as xxx }"
                            // "export { type as 'xxx' }"
                            alias = p.parse_clause_alias(b"export")?;
                            alias_loc = p.lexer.loc();
                            p.lexer.next()?;

                            items.push(ClauseItem {
                                alias: alias.into(),
                                alias_loc,
                                name,
                                original_name: original_name.into(),
                            });
                        } else {
                            had_type_only_exports = true;
                        }
                    } else {
                        // The name can actually be a keyword if we're really an "export from"
                        // statement. However, we won't know until later. Allow keywords as
                        // identifiers for now and throw an error later if there's no "from".
                        //
                        //   // This is fine
                        //   export { default } from 'path'
                        //
                        //   // This is a syntax error
                        //   export { default }
                        //
                        if p.lexer.token != T::TIdentifier && first_non_identifier_loc.start == 0 {
                            first_non_identifier_loc = p.lexer.loc();
                        }

                        // "export { type xx }"
                        // "export { type xx as yy }"
                        // "export { type xx as if }"
                        // "export { type default } from 'path'"
                        // "export { type default as if } from 'path'"
                        // "export { type xx as 'yy' }"
                        // "export { type 'xx' } from 'mod'"
                        let _ = p.parse_clause_alias(b"export").unwrap_or(b"");
                        p.lexer.next()?;

                        if p.lexer.is_contextual_keyword(b"as") {
                            p.lexer.next()?;
                            let _ = p.parse_clause_alias(b"export").unwrap_or(b"");
                            p.lexer.next()?;
                        }

                        had_type_only_exports = true;
                    }
                } else {
                    if p.lexer.is_contextual_keyword(b"as") {
                        p.lexer.next()?;
                        alias = p.parse_clause_alias(b"export")?;
                        alias_loc = p.lexer.loc();

                        p.lexer.next()?;
                    }

                    items.push(ClauseItem {
                        alias: alias.into(),
                        alias_loc,
                        name,
                        original_name: original_name.into(),
                    });
                }
            } else {
                if p.lexer.is_contextual_keyword(b"as") {
                    p.lexer.next()?;
                    alias = p.parse_clause_alias(b"export")?;
                    alias_loc = p.lexer.loc();

                    p.lexer.next()?;
                }

                items.push(ClauseItem {
                    alias: alias.into(),
                    alias_loc,
                    name,
                    original_name: original_name.into(),
                });
            }

            // we're done if there's no comma
            if p.lexer.token != T::TComma {
                break;
            }

            if p.lexer.has_newline_before {
                is_single_line = false;
            }
            p.lexer.next()?;
            if p.lexer.has_newline_before {
                is_single_line = false;
            }
        }

        if p.lexer.has_newline_before {
            is_single_line = false;
        }
        p.lexer.expect(T::TCloseBrace)?;

        // Throw an error here if we found a keyword earlier and this isn't an
        // "export from" statement after all
        if first_non_identifier_loc.start != 0 && !p.lexer.is_contextual_keyword(b"from") {
            let r = js_lexer::range_of_identifier(p.source, first_non_identifier_loc);
            p.lexer.add_range_error(
                r,
                format_args!(
                    "Expected identifier but found \"{}\"",
                    bstr::BStr::new(p.source.text_for_range(r))
                ),
            )?;
            return Err(bun_core::err!("SyntaxError"));
        }

        Ok(ExportClauseResult {
            clauses: items.into_bump_slice_mut(),
            is_single_line,
            had_type_only_exports,
        })
    }
}

// ported from: src/js_parser/ast/parseImportExport.zig