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