quickjs-parse 0.10.1

ECMAScript 2025 lexer, AST and parser for the pure-Rust QuickJS port
Documentation
//! `quickjs-parse` — ECMAScript 2025 lexer, AST and parser.
//!
//! Milestone status: **the lexer is complete (M1a)**; the AST and parser are the
//! next step and do not exist yet.
//!
//! ```no_run
//! use js_parse::{Lexer, TokenKind};
//!
//! let mut lexer = Lexer::new("let answer = 0x2a + 1_000;");
//! let mut kinds = Vec::new();
//! loop {
//!     let token = lexer.next_token().expect("valid source");
//!     let done = matches!(token.kind, TokenKind::Eof);
//!     kinds.push(token.kind);
//!     if done {
//!         break;
//!     }
//! }
//! assert_eq!(kinds.len(), 8);
//! ```
//!
//! # Known limitation
//!
//! String values are Rust `String`s, so a lone surrogate (`"\ud800"`) cannot be
//! represented yet: it is decoded to U+FFFD. QuickJS keeps UTF-16 code units
//! and reports `"\ud800".length === 1`, so the string representation must gain
//! WTF-8 (or UTF-16) support in the `js-value` milestone. This is tracked as a
//! `TODO(js-value)` and only affects lone surrogates, never well-formed text.

#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]

pub mod ast;

/// The name `specifier` resolves to when imported from `base`, textually.
///
/// This is the reference's `js_default_module_normalize_name`, and it is *textual* on
/// purpose: `./a.js` imported from `/x/main.js` is `/x/a.js` without anything being
/// resolved against the filesystem. Two things depend on that rule and must not disagree:
///
/// * the loader, which uses the name as the cache key and as what diagnostics print;
/// * the AOT bundler, which registers precompiled modules *under that name* so the engine
///   can find them without a loader at all.
///
/// A second implementation of this in the bundler would drift from the loader's, and the
/// symptom would be a product that reports "could not load module filename" for a module
/// it is carrying.
///
/// Only the *leading* `./` and `../` are folded, matching the reference: a specifier that
/// is not relative (`lodash`, `node:fs`) is returned unchanged, so a bare specifier keeps
/// failing the way it always did instead of being silently rewritten into a path.
pub fn normalize_specifier(base: &str, specifier: &str) -> String {
    if !specifier.starts_with('.') {
        return specifier.to_string();
    }
    // The directory of `base` — everything before its last `/`.
    let mut filename = match base.rfind('/') {
        Some(index) => base[..index].to_string(),
        None => String::new(),
    };
    let mut rest = specifier;
    loop {
        if let Some(tail) = rest.strip_prefix("./") {
            rest = tail;
        } else if let Some(tail) = rest.strip_prefix("../") {
            if filename.is_empty() {
                break;
            }
            // The last element of the base directory.
            let last = match filename.rfind('/') {
                Some(index) => &filename[index + 1..],
                None => filename.as_str(),
            };
            // A base whose last element is `.` or `..` stops the fold: there is nothing
            // left that the `..` could cancel. The reference breaks here rather than
            // climbing out, which is what keeps `/../x.js` from becoming `x.js`.
            if last == "." || last == ".." {
                break;
            }
            match filename.rfind('/') {
                Some(index) => filename.truncate(index),
                None => filename.clear(),
            }
            rest = tail;
        } else {
            break;
        }
    }
    if filename.is_empty() {
        rest.to_string()
    } else {
        format!("{filename}/{rest}")
    }
}

/// Whether `source` should be evaluated as a module, decided the way `qjs` decides.
///
/// This is a question about source text rather than about the engine — `qjs` asks it to
/// pick between two eval modes and `qjsc` asks it to pick between two output shapes — so
/// it lives here, where both can reach it without linking an interpreter.
///
/// The rule is deliberately shallow: the **first token** must be `import` or `export`
/// (an `import` followed by `.` or `(` is `import.meta` or `import()`, both of which are
/// expressions, so a script may use them). Nothing else makes a file a module.
///
/// It has to be this shallow to match the reference, and the difference is observable:
/// a file that merely *mentions* `import.meta` further down is a script, so it fails with
/// "import.meta only valid in module code" rather than silently becoming a module.
pub fn is_module_source(source: &str) -> bool {
    let bytes = source.as_bytes();
    let mut index = 0;
    // A shebang line is not code.
    if bytes.starts_with(b"#!") {
        while index < bytes.len() && bytes[index] != b'\n' {
            index += 1;
        }
    }
    loop {
        // Whitespace.
        while index < bytes.len() && bytes[index].is_ascii_whitespace() {
            index += 1;
        }
        if bytes[index..].starts_with(b"//") {
            while index < bytes.len() && bytes[index] != b'\n' {
                index += 1;
            }
            continue;
        }
        if bytes[index..].starts_with(b"/*") {
            index += 2;
            while index < bytes.len() && !bytes[index..].starts_with(b"*/") {
                index += 1;
            }
            index = (index + 2).min(bytes.len());
            continue;
        }
        break;
    }
    let rest = &source[index.min(source.len())..];
    let word = |w: &str| -> Option<&str> { rest.strip_prefix(w) };
    if let Some(tail) = word("export") {
        // `exportedThing` is an identifier, not the keyword.
        return !tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$');
    }
    if let Some(tail) = word("import") {
        if tail.starts_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$') {
            return false;
        }
        let tail = tail.trim_start();
        // `import.meta` and `import(...)` are expressions.
        if tail.starts_with('.') || tail.starts_with('(') {
            return false;
        }
        return true;
    }
    false
}

mod error;
mod lexer;
pub mod parser;
mod token;
mod unicode_id;

pub use error::{LexError, ParseError, Result, SyntaxError};
pub use lexer::Lexer;
pub use parser::{
    EvalContext, Parser, parse_eval_script, parse_eval_script_in, parse_expression, parse_module,
    parse_script, parse_script_strict, parse_suspensible_global_eval, parse_suspensible_script,
};

/// Parser configuration constants and helpers.
pub mod parser_limits {
    pub use crate::parser::DEFAULT_MAX_DEPTH;
}
pub use token::{
    BigIntLiteral, Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, TemplateToken,
    Token, TokenKind,
};