Skip to main content

js_parse/
lib.rs

1//! `quickjs-parse` — ECMAScript 2025 lexer, AST and parser.
2//!
3//! Milestone status: **the lexer is complete (M1a)**; the AST and parser are the
4//! next step and do not exist yet.
5//!
6//! ```no_run
7//! use js_parse::{Lexer, TokenKind};
8//!
9//! let mut lexer = Lexer::new("let answer = 0x2a + 1_000;");
10//! let mut kinds = Vec::new();
11//! loop {
12//!     let token = lexer.next_token().expect("valid source");
13//!     let done = matches!(token.kind, TokenKind::Eof);
14//!     kinds.push(token.kind);
15//!     if done {
16//!         break;
17//!     }
18//! }
19//! assert_eq!(kinds.len(), 8);
20//! ```
21//!
22//! # Known limitation
23//!
24//! String values are Rust `String`s, so a lone surrogate (`"\ud800"`) cannot be
25//! represented yet: it is decoded to U+FFFD. QuickJS keeps UTF-16 code units
26//! and reports `"\ud800".length === 1`, so the string representation must gain
27//! WTF-8 (or UTF-16) support in the `js-value` milestone. This is tracked as a
28//! `TODO(js-value)` and only affects lone surrogates, never well-formed text.
29
30#![deny(unsafe_op_in_unsafe_fn)]
31#![warn(missing_docs)]
32
33pub mod ast;
34
35/// The name `specifier` resolves to when imported from `base`, textually.
36///
37/// This is the reference's `js_default_module_normalize_name`, and it is *textual* on
38/// purpose: `./a.js` imported from `/x/main.js` is `/x/a.js` without anything being
39/// resolved against the filesystem. Two things depend on that rule and must not disagree:
40///
41/// * the loader, which uses the name as the cache key and as what diagnostics print;
42/// * the AOT bundler, which registers precompiled modules *under that name* so the engine
43///   can find them without a loader at all.
44///
45/// A second implementation of this in the bundler would drift from the loader's, and the
46/// symptom would be a product that reports "could not load module filename" for a module
47/// it is carrying.
48///
49/// Only the *leading* `./` and `../` are folded, matching the reference: a specifier that
50/// is not relative (`lodash`, `node:fs`) is returned unchanged, so a bare specifier keeps
51/// failing the way it always did instead of being silently rewritten into a path.
52pub fn normalize_specifier(base: &str, specifier: &str) -> String {
53    if !specifier.starts_with('.') {
54        return specifier.to_string();
55    }
56    // The directory of `base` — everything before its last `/`.
57    let mut filename = match base.rfind('/') {
58        Some(index) => base[..index].to_string(),
59        None => String::new(),
60    };
61    let mut rest = specifier;
62    loop {
63        if let Some(tail) = rest.strip_prefix("./") {
64            rest = tail;
65        } else if let Some(tail) = rest.strip_prefix("../") {
66            if filename.is_empty() {
67                break;
68            }
69            // The last element of the base directory.
70            let last = match filename.rfind('/') {
71                Some(index) => &filename[index + 1..],
72                None => filename.as_str(),
73            };
74            // A base whose last element is `.` or `..` stops the fold: there is nothing
75            // left that the `..` could cancel. The reference breaks here rather than
76            // climbing out, which is what keeps `/../x.js` from becoming `x.js`.
77            if last == "." || last == ".." {
78                break;
79            }
80            match filename.rfind('/') {
81                Some(index) => filename.truncate(index),
82                None => filename.clear(),
83            }
84            rest = tail;
85        } else {
86            break;
87        }
88    }
89    if filename.is_empty() {
90        rest.to_string()
91    } else {
92        format!("{filename}/{rest}")
93    }
94}
95
96/// Whether `source` should be evaluated as a module, decided the way `qjs` decides.
97///
98/// This is a question about source text rather than about the engine — `qjs` asks it to
99/// pick between two eval modes and `qjsc` asks it to pick between two output shapes — so
100/// it lives here, where both can reach it without linking an interpreter.
101///
102/// The rule is deliberately shallow: the **first token** must be `import` or `export`
103/// (an `import` followed by `.` or `(` is `import.meta` or `import()`, both of which are
104/// expressions, so a script may use them). Nothing else makes a file a module.
105///
106/// It has to be this shallow to match the reference, and the difference is observable:
107/// a file that merely *mentions* `import.meta` further down is a script, so it fails with
108/// "import.meta only valid in module code" rather than silently becoming a module.
109pub fn is_module_source(source: &str) -> bool {
110    let bytes = source.as_bytes();
111    let mut index = 0;
112    // A shebang line is not code.
113    if bytes.starts_with(b"#!") {
114        while index < bytes.len() && bytes[index] != b'\n' {
115            index += 1;
116        }
117    }
118    loop {
119        // Whitespace.
120        while index < bytes.len() && bytes[index].is_ascii_whitespace() {
121            index += 1;
122        }
123        if bytes[index..].starts_with(b"//") {
124            while index < bytes.len() && bytes[index] != b'\n' {
125                index += 1;
126            }
127            continue;
128        }
129        if bytes[index..].starts_with(b"/*") {
130            index += 2;
131            while index < bytes.len() && !bytes[index..].starts_with(b"*/") {
132                index += 1;
133            }
134            index = (index + 2).min(bytes.len());
135            continue;
136        }
137        break;
138    }
139    let rest = &source[index.min(source.len())..];
140    let word = |w: &str| -> Option<&str> { rest.strip_prefix(w) };
141    if let Some(tail) = word("export") {
142        // `exportedThing` is an identifier, not the keyword.
143        return !tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$');
144    }
145    if let Some(tail) = word("import") {
146        if tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$') {
147            return false;
148        }
149        let tail = tail.trim_start();
150        // `import.meta` and `import(...)` are expressions.
151        if tail.starts_with('.') || tail.starts_with('(') {
152            return false;
153        }
154        return true;
155    }
156    false
157}
158
159mod error;
160mod lexer;
161pub mod parser;
162mod token;
163mod unicode_id;
164
165pub use error::{LexError, ParseError, Result, SyntaxError};
166pub use lexer::Lexer;
167pub use parser::{
168    EvalContext, Parser, parse_eval_script, parse_eval_script_in, parse_expression, parse_module,
169    parse_script, parse_script_strict, parse_suspensible_global_eval, parse_suspensible_script,
170};
171
172/// Parser configuration constants and helpers.
173pub mod parser_limits {
174    pub use crate::parser::DEFAULT_MAX_DEPTH;
175}
176pub use token::{
177    BigIntLiteral, Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, TemplateToken,
178    Token, TokenKind,
179};