quickjs-capi 0.13.1

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
//! The atom table: `JSAtom`, the C API's interned property keys.
//!
//! # Why the identifiers are the reference's
//!
//! `JS_ATOM_*` values are part of the ABI. A C module writes `JS_ATOM_length` and we have to
//! read the same number, so the table below is a **transcription** of
//! `oracle/quickjs-master/quickjs-atom.h` in its own order — not a curated subset and not
//! re-sorted. `tests/atoms.rs` re-parses that header and asserts index for index, which is
//! what keeps a transcription from silently drifting.
//!
//! # Why a table and not a hash of the pointer
//!
//! The reference's atoms are refcounted strings with the first few hundred pinned. Here an
//! atom is an index into a per-runtime vector, with the pinned prefix pre-filled: index 0 is
//! `JS_ATOM_NULL`, indices 1..=`JS_ATOM_END - 1` are the constants below, and anything a
//! program interns afterwards is appended. Duplicates hash to the index already there, so
//! `JS_NewAtom(ctx, "length")` twice answers the same atom, which is the only property the
//! C API actually promises.

use std::collections::HashMap;

/// `JSAtom`: a `uint32_t`. `JS_ATOM_NULL` (0) is the null atom.
pub type Atom = u32;

/// `JS_ATOM_NULL`: the atom that addresses no property.
pub const ATOM_NULL: Atom = 0;

/// The pinned atoms, in the reference's order: `JS_ATOM_null` is 1.
///
/// Generated from `quickjs-atom.h` by the `DEF` lines it contains; see the module docs.
pub const PINNED: [&str; 251] = [
    "null",                      // JS_ATOM_null
    "false",                     // JS_ATOM_false
    "true",                      // JS_ATOM_true
    "if",                        // JS_ATOM_if
    "else",                      // JS_ATOM_else
    "return",                    // JS_ATOM_return
    "var",                       // JS_ATOM_var
    "this",                      // JS_ATOM_this
    "delete",                    // JS_ATOM_delete
    "void",                      // JS_ATOM_void
    "typeof",                    // JS_ATOM_typeof
    "new",                       // JS_ATOM_new
    "in",                        // JS_ATOM_in
    "instanceof",                // JS_ATOM_instanceof
    "do",                        // JS_ATOM_do
    "while",                     // JS_ATOM_while
    "for",                       // JS_ATOM_for
    "break",                     // JS_ATOM_break
    "continue",                  // JS_ATOM_continue
    "switch",                    // JS_ATOM_switch
    "case",                      // JS_ATOM_case
    "default",                   // JS_ATOM_default
    "throw",                     // JS_ATOM_throw
    "try",                       // JS_ATOM_try
    "catch",                     // JS_ATOM_catch
    "finally",                   // JS_ATOM_finally
    "function",                  // JS_ATOM_function
    "debugger",                  // JS_ATOM_debugger
    "with",                      // JS_ATOM_with
    "class",                     // JS_ATOM_class
    "const",                     // JS_ATOM_const
    "enum",                      // JS_ATOM_enum
    "export",                    // JS_ATOM_export
    "extends",                   // JS_ATOM_extends
    "import",                    // JS_ATOM_import
    "super",                     // JS_ATOM_super
    "implements",                // JS_ATOM_implements
    "interface",                 // JS_ATOM_interface
    "let",                       // JS_ATOM_let
    "package",                   // JS_ATOM_package
    "private",                   // JS_ATOM_private
    "protected",                 // JS_ATOM_protected
    "public",                    // JS_ATOM_public
    "static",                    // JS_ATOM_static
    "yield",                     // JS_ATOM_yield
    "await",                     // JS_ATOM_await
    "",                          // JS_ATOM_empty_string
    "keys",                      // JS_ATOM_keys
    "size",                      // JS_ATOM_size
    "length",                    // JS_ATOM_length
    "fileName",                  // JS_ATOM_fileName
    "lineNumber",                // JS_ATOM_lineNumber
    "columnNumber",              // JS_ATOM_columnNumber
    "message",                   // JS_ATOM_message
    "cause",                     // JS_ATOM_cause
    "errors",                    // JS_ATOM_errors
    "error",                     // JS_ATOM_error
    "suppressed",                // JS_ATOM_suppressed
    "stack",                     // JS_ATOM_stack
    "name",                      // JS_ATOM_name
    "toString",                  // JS_ATOM_toString
    "toLocaleString",            // JS_ATOM_toLocaleString
    "valueOf",                   // JS_ATOM_valueOf
    "eval",                      // JS_ATOM_eval
    "prototype",                 // JS_ATOM_prototype
    "constructor",               // JS_ATOM_constructor
    "configurable",              // JS_ATOM_configurable
    "writable",                  // JS_ATOM_writable
    "enumerable",                // JS_ATOM_enumerable
    "value",                     // JS_ATOM_value
    "get",                       // JS_ATOM_get
    "set",                       // JS_ATOM_set
    "of",                        // JS_ATOM_of
    "using",                     // JS_ATOM_using
    "__proto__",                 // JS_ATOM___proto__
    "undefined",                 // JS_ATOM_undefined
    "number",                    // JS_ATOM_number
    "boolean",                   // JS_ATOM_boolean
    "string",                    // JS_ATOM_string
    "object",                    // JS_ATOM_object
    "symbol",                    // JS_ATOM_symbol
    "integer",                   // JS_ATOM_integer
    "unknown",                   // JS_ATOM_unknown
    "arguments",                 // JS_ATOM_arguments
    "callee",                    // JS_ATOM_callee
    "caller",                    // JS_ATOM_caller
    "<eval>",                    // JS_ATOM__eval_
    "<ret>",                     // JS_ATOM__ret_
    "<var>",                     // JS_ATOM__var_
    "<arg_var>",                 // JS_ATOM__arg_var_
    "<with>",                    // JS_ATOM__with_
    "lastIndex",                 // JS_ATOM_lastIndex
    "target",                    // JS_ATOM_target
    "index",                     // JS_ATOM_index
    "input",                     // JS_ATOM_input
    "defineProperties",          // JS_ATOM_defineProperties
    "apply",                     // JS_ATOM_apply
    "join",                      // JS_ATOM_join
    "split",                     // JS_ATOM_split
    "construct",                 // JS_ATOM_construct
    "getPrototypeOf",            // JS_ATOM_getPrototypeOf
    "setPrototypeOf",            // JS_ATOM_setPrototypeOf
    "isExtensible",              // JS_ATOM_isExtensible
    "preventExtensions",         // JS_ATOM_preventExtensions
    "has",                       // JS_ATOM_has
    "deleteProperty",            // JS_ATOM_deleteProperty
    "defineProperty",            // JS_ATOM_defineProperty
    "getOwnPropertyDescriptor",  // JS_ATOM_getOwnPropertyDescriptor
    "ownKeys",                   // JS_ATOM_ownKeys
    "add",                       // JS_ATOM_add
    "done",                      // JS_ATOM_done
    "next",                      // JS_ATOM_next
    "values",                    // JS_ATOM_values
    "source",                    // JS_ATOM_source
    "flags",                     // JS_ATOM_flags
    "global",                    // JS_ATOM_global
    "unicode",                   // JS_ATOM_unicode
    "raw",                       // JS_ATOM_raw
    "rawJSON",                   // JS_ATOM_rawJSON
    "new.target",                // JS_ATOM_new_target
    "this.active_func",          // JS_ATOM_this_active_func
    "<home_object>",             // JS_ATOM_home_object
    "<computed_field>",          // JS_ATOM_computed_field
    "<static_computed_field>",   // JS_ATOM_static_computed_field
    "<class_fields_init>",       // JS_ATOM_class_fields_init
    "<brand>",                   // JS_ATOM_brand
    "#constructor",              // JS_ATOM_hash_constructor
    "as",                        // JS_ATOM_as
    "from",                      // JS_ATOM_from
    "meta",                      // JS_ATOM_meta
    "*default*",                 // JS_ATOM__default_
    "*",                         // JS_ATOM__star_
    "Module",                    // JS_ATOM_Module
    "then",                      // JS_ATOM_then
    "resolve",                   // JS_ATOM_resolve
    "reject",                    // JS_ATOM_reject
    "promise",                   // JS_ATOM_promise
    "proxy",                     // JS_ATOM_proxy
    "revoke",                    // JS_ATOM_revoke
    "async",                     // JS_ATOM_async
    "exec",                      // JS_ATOM_exec
    "groups",                    // JS_ATOM_groups
    "indices",                   // JS_ATOM_indices
    "status",                    // JS_ATOM_status
    "reason",                    // JS_ATOM_reason
    "globalThis",                // JS_ATOM_globalThis
    "bigint",                    // JS_ATOM_bigint
    "-0",                        // JS_ATOM_minus_zero
    "Infinity",                  // JS_ATOM_Infinity
    "-Infinity",                 // JS_ATOM_minus_Infinity
    "NaN",                       // JS_ATOM_NaN
    "hasIndices",                // JS_ATOM_hasIndices
    "ignoreCase",                // JS_ATOM_ignoreCase
    "multiline",                 // JS_ATOM_multiline
    "dotAll",                    // JS_ATOM_dotAll
    "sticky",                    // JS_ATOM_sticky
    "unicodeSets",               // JS_ATOM_unicodeSets
    "not-equal",                 // JS_ATOM_not_equal
    "timed-out",                 // JS_ATOM_timed_out
    "ok",                        // JS_ATOM_ok
    "toISOString",               // JS_ATOM_toISOString
    "alphabet",                  // JS_ATOM_alphabet
    "lastChunkHandling",         // JS_ATOM_lastChunkHandling
    "omitPadding",               // JS_ATOM_omitPadding
    "toJSON",                    // JS_ATOM_toJSON
    "maxByteLength",             // JS_ATOM_maxByteLength
    "Object",                    // JS_ATOM_Object
    "Array",                     // JS_ATOM_Array
    "Error",                     // JS_ATOM_Error
    "Number",                    // JS_ATOM_Number
    "String",                    // JS_ATOM_String
    "Boolean",                   // JS_ATOM_Boolean
    "Symbol",                    // JS_ATOM_Symbol
    "Arguments",                 // JS_ATOM_Arguments
    "Math",                      // JS_ATOM_Math
    "JSON",                      // JS_ATOM_JSON
    "Date",                      // JS_ATOM_Date
    "Function",                  // JS_ATOM_Function
    "GeneratorFunction",         // JS_ATOM_GeneratorFunction
    "ForInIterator",             // JS_ATOM_ForInIterator
    "RegExp",                    // JS_ATOM_RegExp
    "ArrayBuffer",               // JS_ATOM_ArrayBuffer
    "SharedArrayBuffer",         // JS_ATOM_SharedArrayBuffer
    "Uint8ClampedArray",         // JS_ATOM_Uint8ClampedArray
    "Int8Array",                 // JS_ATOM_Int8Array
    "Uint8Array",                // JS_ATOM_Uint8Array
    "Int16Array",                // JS_ATOM_Int16Array
    "Uint16Array",               // JS_ATOM_Uint16Array
    "Int32Array",                // JS_ATOM_Int32Array
    "Uint32Array",               // JS_ATOM_Uint32Array
    "BigInt64Array",             // JS_ATOM_BigInt64Array
    "BigUint64Array",            // JS_ATOM_BigUint64Array
    "Float16Array",              // JS_ATOM_Float16Array
    "Float32Array",              // JS_ATOM_Float32Array
    "Float64Array",              // JS_ATOM_Float64Array
    "DataView",                  // JS_ATOM_DataView
    "BigInt",                    // JS_ATOM_BigInt
    "WeakRef",                   // JS_ATOM_WeakRef
    "FinalizationRegistry",      // JS_ATOM_FinalizationRegistry
    "Map",                       // JS_ATOM_Map
    "Set",                       // JS_ATOM_Set
    "WeakMap",                   // JS_ATOM_WeakMap
    "WeakSet",                   // JS_ATOM_WeakSet
    "Iterator",                  // JS_ATOM_Iterator
    "Iterator Helper",           // JS_ATOM_IteratorHelper
    "Iterator Concat",           // JS_ATOM_IteratorConcat
    "Iterator Wrap",             // JS_ATOM_IteratorWrap
    "Iterator Zip",              // JS_ATOM_IteratorZip
    "Array From Async",          // JS_ATOM_ArrayFromAsync
    "Map Iterator",              // JS_ATOM_Map_Iterator
    "Set Iterator",              // JS_ATOM_Set_Iterator
    "Array Iterator",            // JS_ATOM_Array_Iterator
    "String Iterator",           // JS_ATOM_String_Iterator
    "RegExp String Iterator",    // JS_ATOM_RegExp_String_Iterator
    "Generator",                 // JS_ATOM_Generator
    "Proxy",                     // JS_ATOM_Proxy
    "Promise",                   // JS_ATOM_Promise
    "PromiseResolveFunction",    // JS_ATOM_PromiseResolveFunction
    "PromiseRejectFunction",     // JS_ATOM_PromiseRejectFunction
    "AsyncFunction",             // JS_ATOM_AsyncFunction
    "AsyncFunctionResolve",      // JS_ATOM_AsyncFunctionResolve
    "AsyncFunctionReject",       // JS_ATOM_AsyncFunctionReject
    "AsyncGeneratorFunction",    // JS_ATOM_AsyncGeneratorFunction
    "AsyncGenerator",            // JS_ATOM_AsyncGenerator
    "DisposableStack",           // JS_ATOM_DisposableStack
    "AsyncDisposableStack",      // JS_ATOM_AsyncDisposableStack
    "EvalError",                 // JS_ATOM_EvalError
    "RangeError",                // JS_ATOM_RangeError
    "ReferenceError",            // JS_ATOM_ReferenceError
    "SyntaxError",               // JS_ATOM_SyntaxError
    "TypeError",                 // JS_ATOM_TypeError
    "URIError",                  // JS_ATOM_URIError
    "InternalError",             // JS_ATOM_InternalError
    "AggregateError",            // JS_ATOM_AggregateError
    "SuppressedError",           // JS_ATOM_SuppressedError
    "<brand>",                   // JS_ATOM_Private_brand
    "Symbol.toPrimitive",        // JS_ATOM_Symbol_toPrimitive
    "Symbol.iterator",           // JS_ATOM_Symbol_iterator
    "Symbol.match",              // JS_ATOM_Symbol_match
    "Symbol.matchAll",           // JS_ATOM_Symbol_matchAll
    "Symbol.replace",            // JS_ATOM_Symbol_replace
    "Symbol.search",             // JS_ATOM_Symbol_search
    "Symbol.split",              // JS_ATOM_Symbol_split
    "Symbol.toStringTag",        // JS_ATOM_Symbol_toStringTag
    "Symbol.isConcatSpreadable", // JS_ATOM_Symbol_isConcatSpreadable
    "Symbol.hasInstance",        // JS_ATOM_Symbol_hasInstance
    "Symbol.species",            // JS_ATOM_Symbol_species
    "Symbol.unscopables",        // JS_ATOM_Symbol_unscopables
    "Symbol.asyncIterator",      // JS_ATOM_Symbol_asyncIterator
    "Symbol.dispose",            // JS_ATOM_Symbol_dispose
    "Symbol.asyncDispose",       // JS_ATOM_Symbol_asyncDispose
];

/// `JS_ATOM_END`: one past the last pinned atom, which is also the first free index.
pub const ATOM_END: Atom = PINNED.len() as Atom + 1;

/// The atoms one runtime has interned.
///
/// Per runtime rather than per process because the reference's are too: a `JSAtom` is only
/// meaningful to the runtime that made it, which is why every accessor takes a `JSContext *`
/// or a `JSRuntime *` and why mixing two runtimes' atoms is undefined by construction.
pub struct AtomTable {
    /// `index -> text`, with the pinned prefix already filled in.
    texts: Vec<String>,
    /// `text -> index`, so interning is a lookup after the first time.
    indices: HashMap<String, Atom>,
}

impl AtomTable {
    /// A table holding only the pinned atoms.
    pub fn new() -> AtomTable {
        let texts: Vec<String> = PINNED.iter().map(|text| (*text).to_string()).collect();
        // Index 0 is `ATOM_NULL`, which addresses nothing and therefore has no text; the
        // vector stays one behind the atom number for ever, and `text()` accounts for it.
        let indices = texts
            .iter()
            .enumerate()
            .map(|(index, text)| (text.clone(), index as Atom + 1))
            .collect();
        AtomTable { texts, indices }
    }

    /// The text `atom` addresses, or `None` for `JS_ATOM_NULL` and out-of-range atoms.
    pub fn text(&self, atom: Atom) -> Option<&str> {
        if atom == ATOM_NULL {
            return None;
        }
        self.texts.get(atom as usize - 1).map(String::as_str)
    }

    /// Intern `text`, answering the atom that addresses it.
    ///
    /// Never answers `ATOM_NULL`: this engine has no "out of memory" atom, and a caller that
    /// compares against `JS_ATOM_NULL` to detect failure would otherwise see a spurious one.
    pub fn intern(&mut self, text: &str) -> Atom {
        if let Some(&atom) = self.indices.get(text) {
            return atom;
        }
        self.texts.push(text.to_string());
        let atom = self.texts.len() as Atom;
        self.indices.insert(text.to_string(), atom);
        atom
    }

    /// How many atoms are interned, for the memory-usage report.
    pub fn len(&self) -> usize {
        self.texts.len()
    }

    /// Whether nothing but the pinned atoms is interned.
    ///
    /// Never true — the constructor fills the pinned prefix — but a `len` without it trips
    /// `clippy::len_without_is_empty`, and the answer is honest about what it counts.
    pub fn is_empty(&self) -> bool {
        self.texts.is_empty()
    }
}

impl Default for AtomTable {
    fn default() -> Self {
        AtomTable::new()
    }
}