Skip to main content

quickjs/
atoms.rs

1//! The atom table: `JSAtom`, the C API's interned property keys.
2//!
3//! # Why the identifiers are the reference's
4//!
5//! `JS_ATOM_*` values are part of the ABI. A C module writes `JS_ATOM_length` and we have to
6//! read the same number, so the table below is a **transcription** of
7//! `oracle/quickjs-master/quickjs-atom.h` in its own order — not a curated subset and not
8//! re-sorted. `tests/atoms.rs` re-parses that header and asserts index for index, which is
9//! what keeps a transcription from silently drifting.
10//!
11//! # Why a table and not a hash of the pointer
12//!
13//! The reference's atoms are refcounted strings with the first few hundred pinned. Here an
14//! atom is an index into a per-runtime vector, with the pinned prefix pre-filled: index 0 is
15//! `JS_ATOM_NULL`, indices 1..=`JS_ATOM_END - 1` are the constants below, and anything a
16//! program interns afterwards is appended. Duplicates hash to the index already there, so
17//! `JS_NewAtom(ctx, "length")` twice answers the same atom, which is the only property the
18//! C API actually promises.
19
20use std::collections::HashMap;
21
22/// `JSAtom`: a `uint32_t`. `JS_ATOM_NULL` (0) is the null atom.
23pub type Atom = u32;
24
25/// `JS_ATOM_NULL`: the atom that addresses no property.
26pub const ATOM_NULL: Atom = 0;
27
28/// The pinned atoms, in the reference's order: `JS_ATOM_null` is 1.
29///
30/// Generated from `quickjs-atom.h` by the `DEF` lines it contains; see the module docs.
31pub const PINNED: [&str; 251] = [
32    "null",                      // JS_ATOM_null
33    "false",                     // JS_ATOM_false
34    "true",                      // JS_ATOM_true
35    "if",                        // JS_ATOM_if
36    "else",                      // JS_ATOM_else
37    "return",                    // JS_ATOM_return
38    "var",                       // JS_ATOM_var
39    "this",                      // JS_ATOM_this
40    "delete",                    // JS_ATOM_delete
41    "void",                      // JS_ATOM_void
42    "typeof",                    // JS_ATOM_typeof
43    "new",                       // JS_ATOM_new
44    "in",                        // JS_ATOM_in
45    "instanceof",                // JS_ATOM_instanceof
46    "do",                        // JS_ATOM_do
47    "while",                     // JS_ATOM_while
48    "for",                       // JS_ATOM_for
49    "break",                     // JS_ATOM_break
50    "continue",                  // JS_ATOM_continue
51    "switch",                    // JS_ATOM_switch
52    "case",                      // JS_ATOM_case
53    "default",                   // JS_ATOM_default
54    "throw",                     // JS_ATOM_throw
55    "try",                       // JS_ATOM_try
56    "catch",                     // JS_ATOM_catch
57    "finally",                   // JS_ATOM_finally
58    "function",                  // JS_ATOM_function
59    "debugger",                  // JS_ATOM_debugger
60    "with",                      // JS_ATOM_with
61    "class",                     // JS_ATOM_class
62    "const",                     // JS_ATOM_const
63    "enum",                      // JS_ATOM_enum
64    "export",                    // JS_ATOM_export
65    "extends",                   // JS_ATOM_extends
66    "import",                    // JS_ATOM_import
67    "super",                     // JS_ATOM_super
68    "implements",                // JS_ATOM_implements
69    "interface",                 // JS_ATOM_interface
70    "let",                       // JS_ATOM_let
71    "package",                   // JS_ATOM_package
72    "private",                   // JS_ATOM_private
73    "protected",                 // JS_ATOM_protected
74    "public",                    // JS_ATOM_public
75    "static",                    // JS_ATOM_static
76    "yield",                     // JS_ATOM_yield
77    "await",                     // JS_ATOM_await
78    "",                          // JS_ATOM_empty_string
79    "keys",                      // JS_ATOM_keys
80    "size",                      // JS_ATOM_size
81    "length",                    // JS_ATOM_length
82    "fileName",                  // JS_ATOM_fileName
83    "lineNumber",                // JS_ATOM_lineNumber
84    "columnNumber",              // JS_ATOM_columnNumber
85    "message",                   // JS_ATOM_message
86    "cause",                     // JS_ATOM_cause
87    "errors",                    // JS_ATOM_errors
88    "error",                     // JS_ATOM_error
89    "suppressed",                // JS_ATOM_suppressed
90    "stack",                     // JS_ATOM_stack
91    "name",                      // JS_ATOM_name
92    "toString",                  // JS_ATOM_toString
93    "toLocaleString",            // JS_ATOM_toLocaleString
94    "valueOf",                   // JS_ATOM_valueOf
95    "eval",                      // JS_ATOM_eval
96    "prototype",                 // JS_ATOM_prototype
97    "constructor",               // JS_ATOM_constructor
98    "configurable",              // JS_ATOM_configurable
99    "writable",                  // JS_ATOM_writable
100    "enumerable",                // JS_ATOM_enumerable
101    "value",                     // JS_ATOM_value
102    "get",                       // JS_ATOM_get
103    "set",                       // JS_ATOM_set
104    "of",                        // JS_ATOM_of
105    "using",                     // JS_ATOM_using
106    "__proto__",                 // JS_ATOM___proto__
107    "undefined",                 // JS_ATOM_undefined
108    "number",                    // JS_ATOM_number
109    "boolean",                   // JS_ATOM_boolean
110    "string",                    // JS_ATOM_string
111    "object",                    // JS_ATOM_object
112    "symbol",                    // JS_ATOM_symbol
113    "integer",                   // JS_ATOM_integer
114    "unknown",                   // JS_ATOM_unknown
115    "arguments",                 // JS_ATOM_arguments
116    "callee",                    // JS_ATOM_callee
117    "caller",                    // JS_ATOM_caller
118    "<eval>",                    // JS_ATOM__eval_
119    "<ret>",                     // JS_ATOM__ret_
120    "<var>",                     // JS_ATOM__var_
121    "<arg_var>",                 // JS_ATOM__arg_var_
122    "<with>",                    // JS_ATOM__with_
123    "lastIndex",                 // JS_ATOM_lastIndex
124    "target",                    // JS_ATOM_target
125    "index",                     // JS_ATOM_index
126    "input",                     // JS_ATOM_input
127    "defineProperties",          // JS_ATOM_defineProperties
128    "apply",                     // JS_ATOM_apply
129    "join",                      // JS_ATOM_join
130    "split",                     // JS_ATOM_split
131    "construct",                 // JS_ATOM_construct
132    "getPrototypeOf",            // JS_ATOM_getPrototypeOf
133    "setPrototypeOf",            // JS_ATOM_setPrototypeOf
134    "isExtensible",              // JS_ATOM_isExtensible
135    "preventExtensions",         // JS_ATOM_preventExtensions
136    "has",                       // JS_ATOM_has
137    "deleteProperty",            // JS_ATOM_deleteProperty
138    "defineProperty",            // JS_ATOM_defineProperty
139    "getOwnPropertyDescriptor",  // JS_ATOM_getOwnPropertyDescriptor
140    "ownKeys",                   // JS_ATOM_ownKeys
141    "add",                       // JS_ATOM_add
142    "done",                      // JS_ATOM_done
143    "next",                      // JS_ATOM_next
144    "values",                    // JS_ATOM_values
145    "source",                    // JS_ATOM_source
146    "flags",                     // JS_ATOM_flags
147    "global",                    // JS_ATOM_global
148    "unicode",                   // JS_ATOM_unicode
149    "raw",                       // JS_ATOM_raw
150    "rawJSON",                   // JS_ATOM_rawJSON
151    "new.target",                // JS_ATOM_new_target
152    "this.active_func",          // JS_ATOM_this_active_func
153    "<home_object>",             // JS_ATOM_home_object
154    "<computed_field>",          // JS_ATOM_computed_field
155    "<static_computed_field>",   // JS_ATOM_static_computed_field
156    "<class_fields_init>",       // JS_ATOM_class_fields_init
157    "<brand>",                   // JS_ATOM_brand
158    "#constructor",              // JS_ATOM_hash_constructor
159    "as",                        // JS_ATOM_as
160    "from",                      // JS_ATOM_from
161    "meta",                      // JS_ATOM_meta
162    "*default*",                 // JS_ATOM__default_
163    "*",                         // JS_ATOM__star_
164    "Module",                    // JS_ATOM_Module
165    "then",                      // JS_ATOM_then
166    "resolve",                   // JS_ATOM_resolve
167    "reject",                    // JS_ATOM_reject
168    "promise",                   // JS_ATOM_promise
169    "proxy",                     // JS_ATOM_proxy
170    "revoke",                    // JS_ATOM_revoke
171    "async",                     // JS_ATOM_async
172    "exec",                      // JS_ATOM_exec
173    "groups",                    // JS_ATOM_groups
174    "indices",                   // JS_ATOM_indices
175    "status",                    // JS_ATOM_status
176    "reason",                    // JS_ATOM_reason
177    "globalThis",                // JS_ATOM_globalThis
178    "bigint",                    // JS_ATOM_bigint
179    "-0",                        // JS_ATOM_minus_zero
180    "Infinity",                  // JS_ATOM_Infinity
181    "-Infinity",                 // JS_ATOM_minus_Infinity
182    "NaN",                       // JS_ATOM_NaN
183    "hasIndices",                // JS_ATOM_hasIndices
184    "ignoreCase",                // JS_ATOM_ignoreCase
185    "multiline",                 // JS_ATOM_multiline
186    "dotAll",                    // JS_ATOM_dotAll
187    "sticky",                    // JS_ATOM_sticky
188    "unicodeSets",               // JS_ATOM_unicodeSets
189    "not-equal",                 // JS_ATOM_not_equal
190    "timed-out",                 // JS_ATOM_timed_out
191    "ok",                        // JS_ATOM_ok
192    "toISOString",               // JS_ATOM_toISOString
193    "alphabet",                  // JS_ATOM_alphabet
194    "lastChunkHandling",         // JS_ATOM_lastChunkHandling
195    "omitPadding",               // JS_ATOM_omitPadding
196    "toJSON",                    // JS_ATOM_toJSON
197    "maxByteLength",             // JS_ATOM_maxByteLength
198    "Object",                    // JS_ATOM_Object
199    "Array",                     // JS_ATOM_Array
200    "Error",                     // JS_ATOM_Error
201    "Number",                    // JS_ATOM_Number
202    "String",                    // JS_ATOM_String
203    "Boolean",                   // JS_ATOM_Boolean
204    "Symbol",                    // JS_ATOM_Symbol
205    "Arguments",                 // JS_ATOM_Arguments
206    "Math",                      // JS_ATOM_Math
207    "JSON",                      // JS_ATOM_JSON
208    "Date",                      // JS_ATOM_Date
209    "Function",                  // JS_ATOM_Function
210    "GeneratorFunction",         // JS_ATOM_GeneratorFunction
211    "ForInIterator",             // JS_ATOM_ForInIterator
212    "RegExp",                    // JS_ATOM_RegExp
213    "ArrayBuffer",               // JS_ATOM_ArrayBuffer
214    "SharedArrayBuffer",         // JS_ATOM_SharedArrayBuffer
215    "Uint8ClampedArray",         // JS_ATOM_Uint8ClampedArray
216    "Int8Array",                 // JS_ATOM_Int8Array
217    "Uint8Array",                // JS_ATOM_Uint8Array
218    "Int16Array",                // JS_ATOM_Int16Array
219    "Uint16Array",               // JS_ATOM_Uint16Array
220    "Int32Array",                // JS_ATOM_Int32Array
221    "Uint32Array",               // JS_ATOM_Uint32Array
222    "BigInt64Array",             // JS_ATOM_BigInt64Array
223    "BigUint64Array",            // JS_ATOM_BigUint64Array
224    "Float16Array",              // JS_ATOM_Float16Array
225    "Float32Array",              // JS_ATOM_Float32Array
226    "Float64Array",              // JS_ATOM_Float64Array
227    "DataView",                  // JS_ATOM_DataView
228    "BigInt",                    // JS_ATOM_BigInt
229    "WeakRef",                   // JS_ATOM_WeakRef
230    "FinalizationRegistry",      // JS_ATOM_FinalizationRegistry
231    "Map",                       // JS_ATOM_Map
232    "Set",                       // JS_ATOM_Set
233    "WeakMap",                   // JS_ATOM_WeakMap
234    "WeakSet",                   // JS_ATOM_WeakSet
235    "Iterator",                  // JS_ATOM_Iterator
236    "Iterator Helper",           // JS_ATOM_IteratorHelper
237    "Iterator Concat",           // JS_ATOM_IteratorConcat
238    "Iterator Wrap",             // JS_ATOM_IteratorWrap
239    "Iterator Zip",              // JS_ATOM_IteratorZip
240    "Array From Async",          // JS_ATOM_ArrayFromAsync
241    "Map Iterator",              // JS_ATOM_Map_Iterator
242    "Set Iterator",              // JS_ATOM_Set_Iterator
243    "Array Iterator",            // JS_ATOM_Array_Iterator
244    "String Iterator",           // JS_ATOM_String_Iterator
245    "RegExp String Iterator",    // JS_ATOM_RegExp_String_Iterator
246    "Generator",                 // JS_ATOM_Generator
247    "Proxy",                     // JS_ATOM_Proxy
248    "Promise",                   // JS_ATOM_Promise
249    "PromiseResolveFunction",    // JS_ATOM_PromiseResolveFunction
250    "PromiseRejectFunction",     // JS_ATOM_PromiseRejectFunction
251    "AsyncFunction",             // JS_ATOM_AsyncFunction
252    "AsyncFunctionResolve",      // JS_ATOM_AsyncFunctionResolve
253    "AsyncFunctionReject",       // JS_ATOM_AsyncFunctionReject
254    "AsyncGeneratorFunction",    // JS_ATOM_AsyncGeneratorFunction
255    "AsyncGenerator",            // JS_ATOM_AsyncGenerator
256    "DisposableStack",           // JS_ATOM_DisposableStack
257    "AsyncDisposableStack",      // JS_ATOM_AsyncDisposableStack
258    "EvalError",                 // JS_ATOM_EvalError
259    "RangeError",                // JS_ATOM_RangeError
260    "ReferenceError",            // JS_ATOM_ReferenceError
261    "SyntaxError",               // JS_ATOM_SyntaxError
262    "TypeError",                 // JS_ATOM_TypeError
263    "URIError",                  // JS_ATOM_URIError
264    "InternalError",             // JS_ATOM_InternalError
265    "AggregateError",            // JS_ATOM_AggregateError
266    "SuppressedError",           // JS_ATOM_SuppressedError
267    "<brand>",                   // JS_ATOM_Private_brand
268    "Symbol.toPrimitive",        // JS_ATOM_Symbol_toPrimitive
269    "Symbol.iterator",           // JS_ATOM_Symbol_iterator
270    "Symbol.match",              // JS_ATOM_Symbol_match
271    "Symbol.matchAll",           // JS_ATOM_Symbol_matchAll
272    "Symbol.replace",            // JS_ATOM_Symbol_replace
273    "Symbol.search",             // JS_ATOM_Symbol_search
274    "Symbol.split",              // JS_ATOM_Symbol_split
275    "Symbol.toStringTag",        // JS_ATOM_Symbol_toStringTag
276    "Symbol.isConcatSpreadable", // JS_ATOM_Symbol_isConcatSpreadable
277    "Symbol.hasInstance",        // JS_ATOM_Symbol_hasInstance
278    "Symbol.species",            // JS_ATOM_Symbol_species
279    "Symbol.unscopables",        // JS_ATOM_Symbol_unscopables
280    "Symbol.asyncIterator",      // JS_ATOM_Symbol_asyncIterator
281    "Symbol.dispose",            // JS_ATOM_Symbol_dispose
282    "Symbol.asyncDispose",       // JS_ATOM_Symbol_asyncDispose
283];
284
285/// `JS_ATOM_END`: one past the last pinned atom, which is also the first free index.
286pub const ATOM_END: Atom = PINNED.len() as Atom + 1;
287
288/// The atoms one runtime has interned.
289///
290/// Per runtime rather than per process because the reference's are too: a `JSAtom` is only
291/// meaningful to the runtime that made it, which is why every accessor takes a `JSContext *`
292/// or a `JSRuntime *` and why mixing two runtimes' atoms is undefined by construction.
293pub struct AtomTable {
294    /// `index -> text`, with the pinned prefix already filled in.
295    texts: Vec<String>,
296    /// `text -> index`, so interning is a lookup after the first time.
297    indices: HashMap<String, Atom>,
298}
299
300impl AtomTable {
301    /// A table holding only the pinned atoms.
302    pub fn new() -> AtomTable {
303        let texts: Vec<String> = PINNED.iter().map(|text| (*text).to_string()).collect();
304        // Index 0 is `ATOM_NULL`, which addresses nothing and therefore has no text; the
305        // vector stays one behind the atom number for ever, and `text()` accounts for it.
306        let indices = texts
307            .iter()
308            .enumerate()
309            .map(|(index, text)| (text.clone(), index as Atom + 1))
310            .collect();
311        AtomTable { texts, indices }
312    }
313
314    /// The text `atom` addresses, or `None` for `JS_ATOM_NULL` and out-of-range atoms.
315    pub fn text(&self, atom: Atom) -> Option<&str> {
316        if atom == ATOM_NULL {
317            return None;
318        }
319        self.texts.get(atom as usize - 1).map(String::as_str)
320    }
321
322    /// Intern `text`, answering the atom that addresses it.
323    ///
324    /// Never answers `ATOM_NULL`: this engine has no "out of memory" atom, and a caller that
325    /// compares against `JS_ATOM_NULL` to detect failure would otherwise see a spurious one.
326    pub fn intern(&mut self, text: &str) -> Atom {
327        if let Some(&atom) = self.indices.get(text) {
328            return atom;
329        }
330        self.texts.push(text.to_string());
331        let atom = self.texts.len() as Atom;
332        self.indices.insert(text.to_string(), atom);
333        atom
334    }
335
336    /// How many atoms are interned, for the memory-usage report.
337    pub fn len(&self) -> usize {
338        self.texts.len()
339    }
340
341    /// Whether nothing but the pinned atoms is interned.
342    ///
343    /// Never true — the constructor fills the pinned prefix — but a `len` without it trips
344    /// `clippy::len_without_is_empty`, and the answer is honest about what it counts.
345    pub fn is_empty(&self) -> bool {
346        self.texts.is_empty()
347    }
348}
349
350impl Default for AtomTable {
351    fn default() -> Self {
352        AtomTable::new()
353    }
354}