Value System
For contributors working on the runtime — type coercion, property access, or adding new value types.
Executive Summary
TGocciaValuehierarchy — All runtime values inherit fromTGocciaValue; primitives, objects, arrays, functions, classes, iterators, and typed arrays each have dedicated subclasses- Virtual property access —
GetProperty/SetPropertyare virtual methods on the base class, eliminating type checks at call sites - GC integration — Every value auto-registers via
AfterConstruction; subclasses overrideTraceReferencesto mark owned references - Shared prototype singletons — String, Number, Array, Set, Map, WeakSet, WeakMap, WeakRef, FinalizationRegistry, Symbol, Function, and TypedArray types share a single prototype instance per engine; the prototype lives in a realm slot and is unpinned when the engine is freed
The value system is the foundation of GocciaScript's runtime. Every piece of data — numbers, strings, objects, functions — is represented as a TGocciaValue or one of its subclasses.
Type Hierarchy
classDiagramTGocciaValue <|-- TGocciaNullLiteralValueTGocciaValue <|-- TGocciaUndefinedLiteralValueTGocciaValue <|-- TGocciaBooleanLiteralValueTGocciaValue <|-- TGocciaNumberLiteralValueTGocciaValue <|-- TGocciaStringLiteralValueTGocciaValue <|-- TGocciaSymbolValueTGocciaValue <|-- TGocciaObjectValueTGocciaObjectValue <|-- TGocciaClassValueTGocciaObjectValue <|-- TGocciaFunctionBaseTGocciaFunctionBase <|-- TGocciaBytecodeFunctionValueTGocciaFunctionBase <|-- TGocciaNativeFunctionValueTGocciaFunctionBase <|-- TGocciaBoundFunctionValueTGocciaInstanceValue <|-- TGocciaArrayValueTGocciaInstanceValue <|-- TGocciaSetValueTGocciaInstanceValue <|-- TGocciaMapValueTGocciaObjectValue <|-- TGocciaPromiseValueTGocciaObjectValue <|-- TGocciaInstanceValueTGocciaInstanceValue <|-- TGocciaWeakSetValueTGocciaInstanceValue <|-- TGocciaWeakMapValueTGocciaInstanceValue <|-- TGocciaWeakRefValueTGocciaInstanceValue <|-- TGocciaFinalizationRegistryValueTGocciaObjectValue <|-- TGocciaEnumValueTGocciaObjectValue <|-- TGocciaIteratorValueTGocciaIteratorValue <|-- TGocciaArrayIteratorValueTGocciaIteratorValue <|-- TGocciaStringIteratorValueTGocciaIteratorValue <|-- TGocciaMapIteratorValueTGocciaIteratorValue <|-- TGocciaSetIteratorValueTGocciaIteratorValue <|-- TGocciaGenericIteratorValueTGocciaIteratorValue <|-- TGocciaIteratorHelperValueTGocciaIteratorHelperValue <|-- TGocciaLazyMapIteratorValueTGocciaIteratorHelperValue <|-- TGocciaLazyFilterIteratorValueTGocciaIteratorHelperValue <|-- TGocciaLazyTakeIteratorValueTGocciaIteratorHelperValue <|-- TGocciaLazyDropIteratorValueTGocciaIteratorHelperValue <|-- TGocciaLazyFlatMapIteratorValueTGocciaIteratorHelperValue <|-- TGocciaConcatIteratorValueTGocciaIteratorHelperValue <|-- TGocciaZipIteratorValueTGocciaIteratorHelperValue <|-- TGocciaZipKeyedIteratorValueTGocciaInstanceValue <|-- TGocciaArrayBufferValueTGocciaInstanceValue <|-- TGocciaSharedArrayBufferValueTGocciaInstanceValue <|-- TGocciaDataViewValueTGocciaInstanceValue <|-- TGocciaTypedArrayValueTGocciaInstanceValue <|-- TGocciaNumberObjectValueTGocciaInstanceValue <|-- TGocciaStringObjectValueTGocciaInstanceValue <|-- TGocciaBooleanObjectValueTGocciaObjectValue <|-- TGocciaSymbolObjectValueclass TGocciaValue {<<abstract>>}class TGocciaNullLiteralValue {null}class TGocciaUndefinedLiteralValue {undefined}class TGocciaBooleanLiteralValue {true / false}class TGocciaNumberLiteralValue {42, 3.14, NaN, Infinity}class TGocciaStringLiteralValue {"hello"}class TGocciaObjectValue {key: value}class TGocciaArrayValue {[1, 2, 3]}class TGocciaPromiseValue {Promise (pending/fulfilled/rejected)}class TGocciaBytecodeFunctionValue {(x) => x + 1, methods, generators}class TGocciaClassValue {class Foo { }}class TGocciaInstanceValue {new Foo()}class TGocciaNativeFunctionValue {Built-in Pascal functions}class TGocciaArrayBufferValue {Fixed-length or resizable binary data buffer}class TGocciaSharedArrayBufferValue {Shared-memory binary data buffer}class TGocciaDataViewValue {Endian-aware view over binary data}class TGocciaTypedArrayValue {Typed view over ArrayBuffer}
GC Integration
Every TGocciaValue participates in the unified mark-and-sweep garbage collector. Values auto-register via AfterConstruction; subclasses override TraceReferences to mark owned references. See Garbage Collector for the full GC architecture, contributor rules, and design rationale.
Type Discrimination via Virtual Dispatch
The base TGocciaValue class provides two virtual methods for runtime type discrimination, replacing multi-is type check chains with single VMT calls:
TGocciaValue = class(TGCManagedObject)function IsPrimitive: Boolean; virtual; // Returns False by defaultfunction IsCallable: Boolean; virtual; // Returns False by defaultfunction IsConstructable: Boolean; virtual; // Returns False by defaultend;
IsPrimitive
Returns True for primitive value types. Overridden by:
| Type | Returns |
|---|---|
TGocciaNullLiteralValue | True |
TGocciaUndefinedLiteralValue | True |
TGocciaBooleanLiteralValue | True |
TGocciaNumberLiteralValue | True |
TGocciaStringLiteralValue | True |
TGocciaSymbolValue | True |
TGocciaBigIntValue | True |
| All others (objects, arrays, functions, classes) | False (inherited default) |
Used by ToPrimitive (Goccia.Values.ToPrimitive.pas) to skip conversion for values that are already primitive.
IsCallable
Returns True for values that can be invoked as functions. Overridden by:
| Type | Returns |
|---|---|
TGocciaFunctionBase (and all subclasses: TGocciaBytecodeFunctionValue, TGocciaBoundFunctionValue, TGocciaNativeFunctionValue) | True |
TGocciaClassValue | True (callable via new) |
TGocciaProxyValue | Delegates to the proxy target |
| All others | False (inherited default) |
Used by:
ToPrimitive— to check whethervalueOf()andtoString()results are callable before invoking them.Function.prototype.call/apply/bind— to validate that the receiver is callable.- Array method callbacks (
map,filter,reduce,sort, etc.) — to validate user-provided callbacks. Set.prototype.forEachandMap.prototype.forEach— to validate the callback argument.IsDeepEqual— to reject callable objects from deep structural comparison when TypeNames differ.
Important: When code needs to cast to TGocciaFunctionBase after the check (e.g., accessor property invocation via .Call()), use is TGocciaFunctionBase instead of IsCallable. This is because TGocciaClassValue inherits from TGocciaObjectValue (not TGocciaFunctionBase) but returns True for IsCallable. The RTTI check ensures the cast is safe.
IsConstructable
Returns True for values that can be used as constructors. This is intentionally narrower than IsCallable, because callable values such as arrow functions, generator functions, and explicitly non-constructable native functions must be rejected by new, extends, and super() construction paths.
Overridden by:
| Type | Returns |
|---|---|
TGocciaFunctionBase | True when the function owns a prototype property, or for bound functions when the target is constructable |
TGocciaNativeFunctionValue | True unless marked NotConstructable; native functions created without a prototype are non-constructable by default |
TGocciaClassValue | True |
TGocciaProxyValue | Delegates to the proxy target |
| Generator functions and non-constructor bytecode functions | False |
| All others | False (inherited default) |
Use IsConstructable instead of IsCallable when validating class heritage or constructor dispatch. Continue to use the concrete value type when the next step requires a specific construct API.
Virtual Property Access
Property access is unified through virtual methods on the TGocciaValue base class:
TGocciaValue = class(TGCManagedObject)function GetProperty(const AName: string): TGocciaValue; virtual;procedure SetProperty(const AName: string; const AValue: TGocciaValue); virtual;end;
The base TGocciaValue provides default implementations: GetProperty returns nil and SetProperty is a no-op. Subclasses override these to implement property semantics:
| Value Type | GetProperty | SetProperty |
|---|---|---|
TGocciaObjectValue | Looks up own properties, walks prototype chain | Creates/updates property descriptor |
TGocciaArrayValue | Handles length and numeric indices, delegates to object | Handles numeric index and length, delegates to object |
TGocciaClassValue | Checks static properties | Sets static properties |
TGocciaInstanceValue | Checks instance, then prototype (invokes getters) | Checks for setters, then sets directly |
Primitives (including TGocciaStringLiteralValue) | Returns nil — property access on a primitive boxes it to its wrapper object first | No-op |
The VM and the built-ins access properties uniformly via Value.GetProperty(Name) and Value.SetProperty(Name, NewValue) — no type checking or interface querying needed at the call site.
Primitives
Null and Undefined
Both are singletons — only one instance exists in the runtime:
class function TGocciaNullLiteralValue.NullValue: TGocciaNullLiteralValue;class function TGocciaUndefinedLiteralValue.UndefinedValue: TGocciaUndefinedLiteralValue;
This enables fast identity checks: if Value = TGocciaUndefinedLiteralValue.UndefinedValue then ...
Booleans
true and false are cached singletons via TrueValue and FalseValue. Boolean creation goes through a factory:
class function TGocciaBooleanLiteralValue.FromBoolean(const AValue: Boolean): TGocciaBooleanLiteralValue;// Returns TrueValue or FalseValue
ToNumberLiteral returns OneValue or ZeroValue singletons rather than allocating a new TGocciaNumberLiteralValue, avoiding an allocation on every boolean-to-number coercion.
Numbers
Simple wrapper around a Double:
TGocciaNumberLiteralValue = class(TGocciaValue)FValue: Double;end;
Special number singletons (class functions on TGocciaNumberLiteralValue): NaNValue, InfinityValue, NegativeInfinityValue, NegativeZeroValue, plus ZeroValue and OneValue.
Checking for special values: Use the property accessors (IsNaN, IsInfinity / IsNegativeInfinity / IsInfinite, IsNegativeZero). IsNaN and the infinity checks delegate to Math.IsNaN and Math.IsInfinite; IsNegativeZero calls NumberBits.IsNegativeZero, which compares the double's 64-bit pattern with the sign bit alone.
Number Prototype (TGocciaNumberObjectValue)
When methods are called on number primitives (e.g., (42).toFixed(2)), the number is auto-boxed into a TGocciaNumberObjectValue. All number object instances within an engine share a single per-engine prototype singleton, stored in a realm slot and following the same pattern as strings, arrays, sets, and maps.
| Method | Description |
|---|---|
toFixed(digits?) | Format with fixed-point notation. Returns "NaN", "Infinity", "-Infinity" for special values. |
toString(radix?) | String representation in radix 2–36 (default 10); other radixes throw RangeError. Special values return their default string. |
valueOf() | Return the primitive number value. |
toPrecision(precision?) | Format to specified precision. Special values return their default string. |
toExponential(digits?) | Format in exponential notation. |
toLocaleString(locales?, options?) | Locale-aware formatting through Intl.NumberFormat; installed by the numberArrayToLocaleString shim (Goccia.Shims.pas). |
Strings
Simple wrapper around a Pascal string:
TGocciaStringLiteralValue = class(TGocciaValue)FValue: string;end;
String primitives get .length, .charAt(), .includes() and the other methods from the realm's single String.prototype, as a TGocciaStringObjectValue boxed from them would (the class new String() also produces). A named read does not create that box: TryGetStringPrimitiveProperty answers from the string's own characters and length, then from String.prototype with the primitive as the receiver. Computed reads still box. Every built-in prototype is per engine and lives in a realm slot, but the wiring varies by type:
- Owned slot with
TGocciaSharedPrototype—Set,Map,Promise,ArrayBuffer,SharedArrayBuffer,DataView,TypedArrayand the weak collections. The helper creates the prototype and pins it and its method host in its constructor; the realm frees the helper on tear-down, which unpins both. - Raw slots —
Array,Number,SymbolandIteratorkeep the prototype in one slot and the method host in another (GArrayMethodHostSlot,GNumberMethodHostSlot,GSymbolMethodHostSlot, …); forArrayandNumberboth slots hold the same instance.String.prototype(GStringPrototypeSlot) andFunction.prototype(GFunctionPrototypeSlot, aTGocciaFunctionSharedPrototype) are their own method hosts in a single slot.SetSlotpins; realm tear-down unpins.
In all cases mutations on one engine's String.prototype do not leak into the next engine on the same worker thread.
Symbols
Unique, immutable primitive values used as property keys (Goccia.Values.SymbolValue.pas):
TGocciaSymbolValue = class(TGocciaValue)FDescription: string;FId: Integer; // Auto-incrementing unique IDend;
Each symbol has a globally unique Id assigned at creation. Type coercion follows ECMAScript strict mode semantics:
| Conversion | Result |
|---|---|
ToBoolean | true |
ToNumber | Throws TypeError ("Cannot convert a Symbol value to a number") |
ToString | "Symbol(description)" (used by String(symbol) and internal display) |
Implicit coercion restrictions: Symbols cannot be implicitly converted to strings or numbers. Any operation that triggers implicit coercion throws a TypeError:
- String coercion — Template literals (
`${symbol}`), string concatenation ("" + symbol),String.prototype.concat - Number coercion — Arithmetic operators (
+,-,*,/,%,**), bitwise operators (|,&,^,~,<<,>>,>>>), relational comparisons (<,>,<=,>=)
Explicit conversions that work:
String(symbol)— Returns the descriptive string (e.g.,"Symbol(foo)"). UsesToStringLiteralinternally.symbol.toString()— Same result asString(symbol).Boolean(symbol)— Returnstrue.typeof symbol— Returns"symbol".
Explicit conversions that throw:
Number(symbol)— ThrowsTypeError. Internally,ToNumberLiteralraises the error.- Unary
+symbol/-symbol— ThrowsTypeError(these triggerToNumberLiteral).
The implicit coercion checks for symbols are implemented at the operator level (primarily in Goccia.Arithmetic.pas, with string built-in behavior in Goccia.Values.StringObjectValue.pas) so that operators reach Symbol-rejection cleanly without first invoking ToStringLiteral on a non-symbol path.
Symbol wrapper objects: Object(symbol) boxes a symbol primitive into a TGocciaSymbolObjectValue, a plain TGocciaObjectValue subclass whose prototype is Symbol.prototype and whose SymbolData property holds the underlying TGocciaSymbolValue. Symbol.prototype methods use thisSymbolValue to accept either the primitive or the wrapper. ToObject (via Box) also produces the wrapper when other spec operations need an object from a symbol.
Shared prototype singleton: Like strings and numbers, symbols use a per-engine shared prototype object stored in a realm slot. It is initialized via InitializePrototype; the realm pins it on SetSlot and releases it on Destroy. The description getter and toString() method are registered on this shared prototype, and TGocciaSymbolValue.GetProperty delegates to the prototype via GetPropertyWithContext so that accessor getters receive the correct symbol instance as this. Symbol.prototype is exposed on the Symbol constructor function, matching ECMAScript semantics. Symbol is an always-registered standard built-in; special-purpose surfaces like test assertions, benchmarking, and FFI are installed through runtime extension classes. Symbol type checks at the operator level use standard RTTI (is TGocciaSymbolValue) rather than VMT methods purely for implementation simplicity.
Weak eligibility: TGocciaSymbolValue.Registered distinguishes symbols returned by Symbol.for() from local/well-known symbols. Non-registered symbols can be held weakly by WeakMap/WeakSet; registered symbols are pinned by the global symbol registry and rejected by CanBeHeldWeakly.
Objects store symbol-keyed properties separately from string-keyed properties via TGocciaObjectValue.FSymbolDescriptors. The in operator handles symbol keys directly via HasSymbolPropertyInChain, without converting them to strings (see TGocciaVM.HasPropertyValue in Goccia.VM.pas).
Type Conversion
ToPrimitive (Goccia.Values.ToPrimitive.pas)
The ECMAScript abstract operation ToPrimitive converts any value to a primitive. For primitives, it's a no-op. For objects, it first probes the @@toPrimitive well-known symbol via GetMethod (ES2026 §7.1.1 step 2.a + §7.3.10): if present and callable, it is invoked with the hint as a string argument ("string", "number", or "default"), and the result must be a primitive or a TypeError is thrown; if present but not callable, a TypeError is thrown immediately. If @@toPrimitive is absent (undefined or null), OrdinaryToPrimitive runs: with tphString it tries toString() first, then valueOf(); with tphDefault or tphNumber it tries valueOf() first, then toString(). Returns the first result that is a primitive, or throws TypeError if neither method returns one. Used by +, comparison operators, and the spec coercion methods.
ToPropertyKey helper
Goccia.Values.ToPrimitive also exposes ToPropertyKey (ES2026 §7.1.19) — coerces a value to a property key. Symbols pass through unchanged so the caller can dispatch to symbol-keyed property storage; non-symbols are coerced via ToPrimitive(string) and then ToStringLiteral. Property-access call sites check the returned type and route to either the string or symbol property table.
Coercion Methods
Every value implements three conversion methods, following JavaScript coercion rules:
| Method | Returns | Example (undefined) |
|---|---|---|
ToBooleanLiteral | TGocciaBooleanLiteralValue | false |
ToNumberLiteral | TGocciaNumberLiteralValue | NaN |
ToStringLiteral | TGocciaStringLiteralValue | "undefined" |
For objects and class instances, ToStringLiteral and ToNumberLiteral go through ToPrimitive — they may invoke user-defined toString() / valueOf() and can therefore throw or trigger arbitrary side effects. Callers in error-boundary contexts (the bytecode throw constructor, the top-level throw formatter) avoid invoking them on objects entirely — they read primitive name/message properties or render a static [object <Tag>] placeholder instead, since post-VM-unwind re-entry is unsafe.
Do not override ToNumberLiteral in TGocciaObjectValue subclasses. The base-class implementation delegates to ToPrimitive(number), which looks up valueOf() / toString() on the object at runtime. Subclasses that hardcode conversion results bypass ToPrimitive and silently ignore user-overridden methods. If a subclass needs custom numeric coercion, register the appropriate valueOf prototype method instead — ToPrimitive will find and invoke it. ToStringLiteral may be overridden when a subclass (a) directly implements the same join()-style logic that ToPrimitive would reach through the prototype, and (b) must work on internally-created instances that may lack a full prototype chain (e.g. arrays during early bootstrap).
Conversion follows ECMAScript specification semantics:
| Value | ToBoolean | ToNumber | ToString |
|---|---|---|---|
undefined | false | NaN | "undefined" |
null | false | 0 | "null" |
true | true | 1 | "true" |
false | false | 0 | "false" |
0, -0, NaN | false | — | "0", "0", "NaN" |
"" (empty) | false | 0 | — |
| Objects | true | ToPrimitive(number) | ToPrimitive(string) |
Objects
Property Descriptors
Objects use ECMAScript-compliant property descriptors:
Data descriptors:
TGocciaPropertyDescriptorData = classValue: TGocciaValue;Writable: Boolean; // Can the value be changed?Enumerable: Boolean; // Visible in for...in / Object.keys()?Configurable: Boolean; // Can the descriptor be modified/deleted?end;
Accessor descriptors:
TGocciaPropertyDescriptorAccessor = classGetter: TGocciaValue; // Get functionSetter: TGocciaValue; // Set functionEnumerable: Boolean;Configurable: Boolean;end;
Who frees a descriptor. GetOwnPropertyDescriptor, GetOwnSymbolPropertyDescriptor and OwnPropertyDescriptorForKey ([[GetOwnProperty]]) return either the descriptor the object stores, which the object owns, or one built for a property the object does not store: an array element or length, a function's length and name, a class's prototype, a String object's index, a typed-array element, a module namespace export, a Proxy trap's result. A built descriptor is CallerOwned. The caller releases whatever it got with ReleaseDescriptor, which frees only a caller-owned one, and reads what it needs before it defines or deletes on the same object or runs guest code (a getter, a setter, a proxy trap), since any of those may free a stored descriptor. A caller that keeps a descriptor clones it or calls TakeOwnership. HasOwnPropertyDescriptor and OwnPropertyIsEnumerable answer the common questions without handing a descriptor out (ADR 0143).
A definition takes its descriptor. DefineProperty, DefineSymbolProperty and their Try forms ([[DefineOwnProperty]]) store or free the descriptor they are given on every exit: when they succeed, when they refuse, and when anything inside them raises, a TypeError, guest code in a Proxy trap or a valueOf, the memory limit, a deadline, an instruction budget or a host's abort at any value allocation. A caller never frees a descriptor it passed, so Obj.DefineProperty(Name, TGocciaPropertyDescriptorData.Create(...)) cannot leak. An override frees the descriptor itself before anything it does ahead of the inherited call raises; a refused growth of the property map frees what the Add was storing in the map's growth gate. An EOutOfMemory from FPC's own allocator is outside the contract (ADR 0184).
Property Deletion
DeleteProperty returns True for configurable or non-existent properties, False for non-configurable properties. Delete call sites convert False to TypeError by default, matching ECMAScript strict mode semantics. With script source --compat-non-strict-mode, expression-level delete keeps the False result instead, and identifier delete can remove configurable global object properties through the global scope's DeleteBinding path.
ToPropertyDescriptor
The ToPropertyDescriptor helper (Goccia.Values.ObjectPropertyDescriptor.pas) implements ES2026 §6.2.5.5. It is the single entry point for parsing a JavaScript descriptor object into a TGocciaPropertyDescriptorData or TGocciaPropertyDescriptorAccessor. Both Object.defineProperty and Reflect.defineProperty delegate to this helper, ensuring identical semantics:
- Inherits unspecified attributes from an existing descriptor (if any)
- Validates that
get/setvalues are callable orundefined(throwsTypeError) - Rejects mixed data+accessor descriptors — a descriptor with both (
valueorwritable) and (getorset) throwsTypeError - Constructs the appropriate descriptor type based on which fields are present
FromPropertyDescriptor
The reverse direction, FromPropertyDescriptor in the same unit, implements ES2026 §6.2.6.4: it turns a descriptor into the JavaScript object that Object.getOwnPropertyDescriptor, Object.getOwnPropertyDescriptors and Reflect.getOwnPropertyDescriptor return and that a Proxy defineProperty trap receives (undefined for no descriptor). Each field is made with CreateDataPropertyOrThrow, so it is an own data property and a setter inherited from Object.prototype never runs. No guest code runs while it reads the descriptor, so a caller may pass a descriptor still stored on the object it describes.
Property Definition Merging
When Object.defineProperty is called on an existing property, unspecified descriptor attributes are inherited from the existing descriptor rather than defaulting to false. For example, calling Object.defineProperty(obj, "x", { enumerable: false }) on a property that is configurable: true, writable: true preserves those attributes. New properties use false as the default for all unspecified attributes, matching ECMAScript specification behavior.
Property Order
String-keyed properties live in FProperties, a TGocciaPropertyMap (TOrderedStringMap<TGocciaPropertyDescriptor>) that keeps creation order; symbol-keyed properties use FSymbolDescriptors plus FSymbolInsertionOrder. GetOwnPropertyKeys returns array-index keys in ascending numeric order first, then other strings in creation order, so Object.keys({ b: 1, 2: 1, a: 1, 1: 1 }) is ["1", "2", "b", "a"] as in JavaScript.
Prototype Chain
Objects can have a prototype via FPrototype: TGocciaObjectValue. Property lookup walks the chain:
- Check own property descriptors (invoking getters if present).
- If not found, check
FPrototype. - Repeat until
nilprototype.
ES2026 §10.1.8.1 OrdinaryGet, §10.1.7.1 OrdinaryHasProperty and §10.1.9.2 OrdinarySetWithOwnDescriptor continue at the parent by calling the parent's own internal method. While the parent's class keeps TGocciaObjectValue's GetPropertyWithContext, HasProperty or AssignPropertyWithReceiver, that call is the same procedure, so the walk steps to the parent in a loop and a chain of any length takes no native stack. A parent whose class overrides the lookup, such as a Proxy, is asked through its own method instead. The walk recognizes such a class by the method it resolves to, so a new override needs no registration. Calls into a Proxy are counted against MAX_PROPERTY_DELEGATION_DEPTH, calls into other such objects against MAX_OBJECT_DELEGATION_DEPTH; see Call Stack Depth Limit.
GetProperty(Name) delegates to GetPropertyWithContext(Name, Self). The WithContext variant carries a this reference through the prototype chain so that inherited getter functions execute with the correct receiver (the original object, not the prototype where the getter was found).
Object Freezing
Object.freeze() calls TGocciaObjectValue.Freeze:
- Freeze — Makes the object non-extensible, then redefines every own property as non-configurable (data properties also non-writable), and sets the
FFrozenandFSealedmarkers. - Writes — Rejected by the property descriptors and the extensibility check, not by the marker; a failed write throws
TypeErrorby default (see Property Descriptor System). Object.isFrozen(obj)— RunsTestIntegrityFrozen(TestIntegrityLevel(O, frozen), ES2026 §7.3.16): the object must be non-extensible and every own property non-configurable, with data properties non-writable. So an object made non-extensible with only non-writable, non-configurable properties reportstruewithout ever callingfreeze. Non-objects returntrue.
Error Helpers (Goccia.Values.ErrorHelper.pas)
A utility unit that centralizes JavaScript error object construction. Instead of manually building error objects at every throw site, code uses:
ThrowTypeError('Cannot set property on non-object');ThrowRangeError('Invalid range in Math.clamp');ThrowReferenceError('x is not defined');ThrowError('Something went wrong');
Each helper creates a TGocciaObjectValue with name and message properties and raises it as a TGocciaThrowValue. The CreateErrorObject(Name, Message) function is also available for cases where the error should be returned rather than thrown (e.g., error constructors).
Arrays
TGocciaArrayValue extends TGocciaInstanceValue.
- Sparse arrays — Holes are the
TGocciaHoleValue.HoleValuesentinel in the internalFElementslist, nevernil. - Numeric property access —
arr["0"]andarr[0]both resolve to the first element. - Shared prototype singleton — All array instances within an engine share a single per-engine prototype, stored in a realm slot. Methods are registered once on this shared prototype during
InitializePrototype(guarded by checking the realm slot) and pinned automatically byTGocciaRealm.SetSlot. The constructor assignsFPrototypefrom the realm slot instead of creating a per-instance prototype. - Prototype methods —
map,filter,reduce,forEach,some,every,flat,flatMap,find,findIndex,indexOf,lastIndexOf,join,includes,concat,push,pop,shift,unshift,sort,splice,reverse,fill,at,slice,toReversed,toSorted,toSpliced— all operate throughThisValue(notSelf) to access instance data, since the method pointers are bound to a single method host instance. - String conversion — An array has no
ToStringLiteralof its own: a template literal,String()or+reachesArray.prototype.toStringthroughToPrimitive, and sojoin.joinconverts each element once, in order. Up to 16 elements it appends, which for so few costs least; above that it hands the strings toTStringJoinBuffer(StringJoin.pas), which keeps a reference to each non-empty one and writes the result once at its exact size, so the work is O(n) where repeated appending took O(n^2). Separators and empty elements take no memory before the result. Its reference table, and converted strings that nothing else holds, are reserved against the memory budget while it holds them; a result past the budget is refused with a catchableRangeErrorbefore it is allocated, and the final copy polls the deadline and a host's abort. The typed-arrayjoinandtoLocaleStringwork the same way.Array.prototype.toLocaleStringis a JavaScript shim that still joins by appending, in O(n^2).
Sets
TGocciaSetValue extends TGocciaInstanceValue (Goccia.Values.SetValue.pas). A collection of unique values with insertion-order iteration.
- Uniqueness — Uses
IsSameValueZero(same as===exceptNaN === NaNis true) to test for duplicates. - Shared prototype singleton — All set instances within an engine share a single per-engine prototype, held by a
TGocciaSharedPrototypein a realm-owned slot (Owned-slot pattern). Methods are registered once duringInitializePrototype. Each method operates throughThisValueto access instance data. - Methods —
add,has,delete,clear,forEach,values,keys,entries,union,intersection,difference,symmetricDifference,isSubsetOf,isSupersetOf,isDisjointFrom— all registered on the shared prototype. - Set-like operations — Set operation methods accept either a
Setor an object withsize,has(value), andkeys()properties. Runtime validation follows the Set Record shape used by the ECMAScript algorithms. - Internal storage —
FStore: TGocciaOrderedValueMap, an insertion-ordered map keyed by SameValueZero (members map to themselves). size— Aget sizeaccessor on the prototype.- Spreadable —
ToArrayconverts to aTGocciaArrayValuefor spread syntax support.
Maps
TGocciaMapValue extends TGocciaInstanceValue (Goccia.Values.MapValue.pas). A collection of key-value pairs with insertion-order iteration where any value can be a key.
- Key equality — Uses
IsSameValueZerofor key lookup. - Internal storage —
FStore: TGocciaOrderedValueMap, the same SameValueZero-keyed, insertion-ordered map that backsSet. - Maps follow the same implementation pattern as Sets (see Sets above): prototype-registered methods, a
get sizeprototype accessor, andToArrayspreadability. - Methods —
get,set,has,delete,clear,forEach,keys,values,entries— all registered on the shared prototype.
Weak Collections
TGocciaWeakMapValue, TGocciaWeakSetValue, TGocciaWeakRefValue, and TGocciaFinalizationRegistryValue extend TGocciaInstanceValue (Goccia.Values.WeakMapValue.pas, Goccia.Values.WeakSetValue.pas, Goccia.Values.WeakRefValue.pas, Goccia.Values.FinalizationRegistryValue.pas). They are class-backed native instances so subclassing and constructor semantics match other built-in native classes.
- Weak eligibility —
Goccia.Values.WeakReferenceSupport.CanBeHeldWeaklyaccepts objects and non-registered symbols. Primitives andSymbol.for()registry symbols are rejected by mutators and constructors. - Internal storage — WeakMap stores entries in
THashMap<TGocciaValue,TGocciaValue>; WeakSet stores membership inTHashMap<TGocciaValue,Boolean>. Allowed keys are object/symbol identity values, so pointer identity matches the requiredSameValuebehavior for this domain. - No enumeration surface — WeakMap/WeakSet intentionally do not expose
size,clear,forEach, iterators,keys,values, orentries. - Shared prototype singleton — Each weak collection has a per-engine shared prototype stored in a realm-owned slot. Prototype methods operate through
ThisValue, matching the built-in method-host pattern. - WeakRef kept objects — WeakRef construction and
deref()add the target to the GC kept-objects set. The set is cleared at host job checkpoints so repeatedderef()calls in the same job are stable without making the target strongly reachable forever. - FinalizationRegistry cleanup — FinalizationRegistry marks cleanup callbacks and held values, but never marks registered targets or unregister tokens. Sweeping visits the cells newest first; it empties each dead cell's target, moves the cell to the registry's pending cells and queues one cleanup job for it through the microtask queue's finalization lane. A pending cell is still a cell of the registry (ES2026 §9.9.3), so
unregisterremoves it too. Each cleanup job takes the oldest pending cell left, if any, and calls the callback with its held value, so the callbacks for one collection run from the newest registration to the oldest. Taking a cell advances a head index instead of shifting the list, so draining n cleanup jobs costs O(n). The registry marks the held values of pending cells, and a queued job roots the registry through the job function's captured root until it runs. - GC behavior — WeakMap/WeakSet do not mark weak keys/values during normal
TraceReferences. WeakMap's weak tracing hook marks a value only when its key is already live from outside the map, and sweeping removes entries whose keys remain unmarked. WeakSet sweeping removes unmarked members. WeakRef clears an unmarked target. FinalizationRegistry removes unmarked-target cells and schedules cleanup.
Promises
TGocciaPromiseValue extends TGocciaObjectValue (Goccia.Values.PromiseValue.pas). Represents an ECMAScript Promise with three possible states.
- State machine — Each Promise has a
TGocciaPromiseState:gpsPending,gpsFulfilled, orgpsRejected. Once settled, the state and result are immutable (double-resolve/reject is a no-op). - Result —
PromiseResult: TGocciaValueholds the fulfillment value or rejection reason after settlement. - Reactions —
FReactions: TList<TGocciaPromiseReaction>stores pending.then()reactions. When the Promise settles, all reactions are enqueued as microtasks. When.then()is called on an already-settled Promise, the reaction is enqueued immediately. - Thenable adoption — If a Promise is resolved with another Promise,
SubscribeTodefers settlement via a microtask (per the spec's PromiseResolveThenableJob) rather than resolving synchronously. For already-settled inner Promises, the settlement is enqueued as a microtask; for pending inner Promises, a reaction is added to the inner's reaction list. - Self-rejection — Resolving a Promise with itself throws a
TypeErrorper ECMAScript spec. - Shared prototype singleton — All Promise instances within an engine share a single per-engine prototype, stored in a realm slot. Methods (
then,catch,finally) are registered once duringInitializePrototypeon aTGocciaSharedPrototypeheld in a realm-owned slot. - GC integration —
TraceReferencesmarks thePromiseResult, all pending reaction callbacks, and reaction result Promises.
Functions
User-Defined Functions (TGocciaBytecodeFunctionValue)
Every source-defined function — ordinary function, arrow, method, async function, generator, and async generator — is a TGocciaBytecodeFunctionValue (Goccia.VM), a sealed TGocciaFunctionBase subclass. It wraps a TGocciaBytecodeClosure (Goccia.VM.Closure): the compiled TGocciaFunctionTemplate, the upvalue cells the function captured, and, for methods, HomeObject, HomeClass and PrivateClass. The template's IsArrow, IsAsync and IsGenerator flags select the call behaviour; there is no subclass per function form. See Bytecode VM for compilation and calls.
- Async functions —
Callcreates aTGocciaPromiseValue, runs the closure, resolves the promise with the completion value, and rejects it with a thrown value. - Generators —
Callreturns a generator object instead of running the body (see Generator Values).
Arrow Functions
An arrow's template has IsArrow set. An arrow has no this binding of its own: the compiler resolves this in its body to the enclosing function's this through an upvalue, so the call-site receiver is ignored. An arrow also takes new.target from its closure.
Generator Values (Goccia.Values.GeneratorValue.pas)
Goccia.Values.GeneratorValue holds the generator object base classes (TGocciaGeneratorBaseValue, TGocciaAsyncGeneratorBaseValue) and the next/return/throw methods on the generator prototypes. The VM's generator objects, TGocciaBytecodeGeneratorObjectValue and TGocciaBytecodeAsyncGeneratorObjectValue, live in Goccia.VM.
Sync generators expose next, return, throw, and [Symbol.iterator]; async generators expose the async iterator protocol and return Promises from next, return, and throw.
this Binding
this binding follows the function form:
| Function form | this binding |
|---|---|
| Ordinary function, shorthand method, class method | Call-site (receiver) |
| Arrow function | Lexical (the enclosing function's this, captured as an upvalue) |
| Async and generator variants | Same as the non-async, non-generator form |
Standalone calls to ordinary, method, async, and generator functions receive undefined as this by default (strict mode, no implicit global). Arrow functions ignore the call-site receiver and keep their lexical this from the closure scope walk. With script source --compat-non-strict-mode, ordinary non-arrow functions coerce nullish this to globalThis; module source remains strict.
Arguments Object (Goccia.Values.ArgumentsObjectValue.pas)
Compatibility arguments objects are created by Goccia.Values.ArgumentsObjectValue. Unmapped objects are ordinary TGocciaObjectValue instances. Sloppy simple-parameter functions use a mapped arguments-object subclass that keeps an internal parameter map and overrides get/set/define/delete so indexed properties alias parameter bindings until deletion, accessor conversion, or non-writable descriptor changes break the mapping. Mapped objects store the parameter cells.
Array Method Callbacks
When array prototype methods (map, filter, reduce, forEach, etc.) invoke user-provided callbacks, they pass undefined as ThisValue. This means:
- Arrow function callbacks inherit
thisfrom their lexical scope (e.g., the enclosing class method), which is the correct ECMAScript behavior. - Shorthand method references passed as callbacks receive
undefinedasthis(matching strict mode semantics for unbound method extraction).
Methods
A method is a TGocciaBytecodeFunctionValue whose closure carries HomeObject (the [[HomeObject]] that super property lookups start from), HomeClass (the class that declared the method), and PrivateClass (the innermost class body the function was created in, used for private-name resolution).
Function Prototype (TGocciaFunctionSharedPrototype)
All functions share a prototype that provides call, apply, and bind:
| Method | Description |
|---|---|
fn.call(thisArg, ...args) | Call with explicit this and individual arguments |
fn.apply(thisArg, argsArray) | Call with explicit this and argument array. Fast path: when argsArray is a TGocciaArrayValue, elements are accessed directly via Elements[I] instead of IntToStr(I) + GetProperty, avoiding per-element string allocation and property lookup. Falls back to the generic array-like object path otherwise. |
fn.bind(thisArg, ...args) | Return a new function with bound this and pre-filled arguments |
bind returns a TGocciaBoundFunctionValue that combines bound arguments with call-time arguments. Bound functions compute length as max(0, original.length - boundArgs.length) and name as "bound " + original.name per ECMAScript spec.
Native Functions (TGocciaNativeFunctionValue)
Wraps a Pascal callback exposed to GocciaScript. Native functions may back core language built-ins, runtime globals, or host-provided embedding APIs:
TGocciaNativeFunctionCallback = function(const AArgs: TGocciaArgumentsCollection;const AThisValue: TGocciaValue): TGocciaValue of object;
Classes
Class Values (TGocciaClassValue)
Represent class constructors. Store:
- Constructor method
- Instance methods (on prototype)
- Static methods
- Static symbol-keyed properties (the
FSymbolDescriptorsmap inherited fromTGocciaObjectValue) — supportsstatic get [Symbol.species]()and similar computed symbol accessors. UseDefineSymbolPropertyto register andGetSymbolPropertyWithReceiverto look up (preserves receiver for getterthiscontext across superclass chain) - Public getters and setters (on prototype via accessor descriptors)
- Static private getters and setters (in
FPrivateGetters/FPrivateSetters, separate from public ones) - Private instance and static fields/methods
- Instance field declaration order (
FFieldOrder, one entry per public or private instance field, alongside theFInstancePropertyDefs/FPrivateInstancePropertyDefsmaps) - Superclass reference for inheritance
Instance Values (TGocciaInstanceValue)
Created by new ClassName(). Extend TGocciaObjectValue with:
- Virtual property dispatch —
GetPropertyandAssignPropertyoverride the base class methods to intercept property access and assignment. This enables getter/setter invocation: reads check the prototype for accessor descriptors and invoke getters with the instance asthis; writes call the setter of an own or inherited accessor, and fail when that accessor has none, before falling back to direct property creation. - Private property storage keyed by each class's own brand token — this enables proper inheritance shadowing where
Base.#xandDerived.#xare distinct fields even when they share the same name. - Class reference for
instanceofchecks
Instantiation Flow
flowchart TDNew["new Foo(args)"]New --> Create["Create TGocciaInstanceValue"]Create --> Proto["Set prototype = Foo.prototype"]Proto --> Init["Create TGocciaClassInitScope\nthis = instance\nowningClass = Foo"]Init --> Derived{"Foo extends\nanother class?"}Derived -- no --> Fields["Initialize Foo's public and private\ninstance fields (one declaration order)"]Fields --> Body["Run Foo's constructor body"]Derived -- yes --> BodyStart["Run Foo's constructor body\nup to super(...)"]BodyStart --> Super["super(...): superclass fields,\nthen superclass constructor body"]Super --> DerivedFields["Initialize Foo's public and private\ninstance fields (one declaration order)"]DerivedFields --> Rest["Run the rest of Foo's constructor body"]Body --> Return["Return instance"]Rest --> Return
Public and private fields share one declaration order (FFieldOrder), so a = …; #p = …; c = … initializes a, #p, then c. Field initializers have access to this (the instance being constructed) and can reference previously-initialized fields. A public field is defined on the instance rather than assigned (ES2026 §7.3.32 DefineField), so it never calls a setter of the same name and replaces a configurable accessor the instance already has.
Enums
Enum Values (TGocciaEnumValue)
Created by enum declarations (TC39 proposal-enum). Extend TGocciaObjectValue with:
- Null prototype —
Object.create(null)semantics - Non-extensible —
Object.preventExtensionsapplied after construction - Non-writable, non-configurable members — defined via
TGocciaPropertyDescriptorDatawith[pfEnumerable]flags only - Ordered entries (
FEntries: TGocciaArrayValue) — array of[key, value]pair arrays preserving declaration order Symbol.iterator— native function returning an array iterator overFEntriesSymbol.toStringTag— set to the enum name- Value type restriction — member values must be Number, String, or Symbol; other types throw
TypeErrorduring evaluation
Self-references in initializers are supported via a child scope that binds each member name as it is evaluated, plus the enum object itself under the enum name.
ArrayBuffer
TGocciaArrayBufferValue extends TGocciaInstanceValue (Goccia.Values.ArrayBufferValue.pas). A raw binary data buffer backed by a zero-initialized TBytes array. It is fixed-length by default, resizable when constructed with { maxByteLength }, and can be detached (by transfer) or made immutable.
- Internal storage —
FData: TBytesholds the raw bytes, and its length is the byte length.FMaxByteLengthis set only for resizable buffers (NO_MAX_BYTE_LENGTHotherwise);FDetachedandFImmutablerecord the other two states. - Shared prototype singleton — All ArrayBuffer instances within an engine share a single per-engine prototype, held by a
TGocciaSharedPrototypein a realm-owned slot. Members are registered once duringInitializePrototype. - Prototype members — Methods
slice,resize,transfer,transferToFixedLength,transferToImmutableandsliceToImmutable; accessorsbyteLength,maxByteLength,resizable,detachedandimmutable.Symbol.toStringTagis"ArrayBuffer". - Accessor reads — The five accessors are found only through the prototype chain, so a
nullor replaced prototype, an own property, or a getter defined by a subclass or a program is observed.GetPropertyWithContextwalks the chain withResolvePropertyWithoutCall(Goccia.Values.NativeFunction.pas); when the buffer is the receiver and the walk, through plain objects only, reaches a getter carrying theTGocciaNativeIntrinsicKindthatInitializePrototypestamps withMarkIntrinsicGetter, the result is computed from the slots instead of calling the getter; a data property found that way is returned, and a name the walk does not find isundefined. Anything else, including another class's built-in getter, takes the full lookup and the call. slice(begin?, end?)— Returns a new ArrayBuffer containing a byte range copy. Supports negative indices (resolved relative tobyteLength), out-of-range clamping, and defaults (begin= 0,end=byteLength).- Detached and immutable buffers — After
transfer, the source is detached:byteLengthis 0 and methods such asslicethrowTypeError.resizeon an immutable buffer throwsTypeError. GCMarkedintegration —TraceReferencescallsinherited(noTGocciaValuereferences to mark — only holdsTBytes).- structuredClone — Byte contents are copied into a new buffer.
SharedArrayBuffer
TGocciaSharedArrayBufferValue extends TGocciaInstanceValue (Goccia.Values.SharedArrayBufferValue.pas). A distinct type from ArrayBuffer — SharedArrayBuffer instances are not instances of ArrayBuffer and vice versa.
- Internal storage — One zero-initialized
TBytesblock for the buffer's whole life. Every agent that holds the buffer reads and writes that block. A buffer constructed with{ maxByteLength }is growable. Its block is allocated atmaxByteLengthbytes, the way ECMA-262's AllocateSharedArrayBuffer allocates it, and the separateFByteLengthrecords how many of those bytes the buffer exposes.growraisesFByteLengthwith a compare-and-exchange, so concurrent grows are ordered and none is lost. It never allocates or moves bytes. The publicDataproperty is the whole block: callers measure the buffer withByteLength, never withLength(Data). - Shared prototype singleton — All SharedArrayBuffer instances within an engine share a single per-engine prototype, held by its own
TGocciaSharedPrototypein a realm-owned slot, separate from ArrayBuffer's.Symbol.toStringTagis"SharedArrayBuffer". - Prototype members —
sliceandgrow; accessorsbyteLength,maxByteLengthandgrowable. - Accessor reads — As for ArrayBuffer: found only through the prototype chain, with the same slot shortcut for the built-in getters when the buffer is the receiver.
slice(begin?, end?)— Returns a new SharedArrayBuffer (not ArrayBuffer).- structuredClone — Byte contents are copied into a new buffer.
DataView
TGocciaDataViewValue extends TGocciaInstanceValue (Goccia.Values.DataViewValue.pas). It provides endian-aware typed reads and writes over ArrayBuffer or SharedArrayBuffer storage.
- Internal storage —
FBufferValue: TGocciaValuestores the underlying buffer,FBufferData: TBytesmirrors the current backing byte array,FByteOffset: Integerstores the view offset, andFByteLength: Integerstores either a fixed byte length or the auto-length sentinel for a view created without a byte length over a resizable ArrayBuffer or a growable SharedArrayBuffer. - Shared prototype singleton — All DataView instances within an engine share a single per-engine prototype (
TGocciaSharedPrototype), stored in a realm slot. Prototype methods are registered once duringInitializePrototype. - Element access — DataView and TypedArray raw byte encoding use
Goccia.BinaryData, which centralizes endian-aware integer, BigInt, Float16, Float32, and Float64 serialization. - Detached and out-of-bounds checks — Accessors and prototype methods reject detached ArrayBuffers and views that no longer fit after a resizable ArrayBuffer shrink. Auto-length views compute their byte length from the buffer's current byte length (ArrayBufferByteLength), never from the backing array's length.
- GC integration —
TraceReferencesmarksFBufferValue, preserving the viewed ArrayBuffer or SharedArrayBuffer.
TypedArray
TGocciaTypedArrayValue extends TGocciaInstanceValue (Goccia.Values.TypedArrayValue.pas). Provides array-like views over ArrayBuffer data with fixed element types. Ten non-BigInt types are supported: Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float16Array, Float32Array, Float64Array. Float16Array uses IEEE 754 half-precision (binary16) with conversion helpers in Goccia.Float16.pas.
- Internal storage —
FBufferValue: TGocciaValue(the underlying buffer — eitherTGocciaArrayBufferValueorTGocciaSharedArrayBufferValue, returned by.buffer),FBufferData: TBytes(shared reference to the buffer's byte array for element access),FByteOffset: Integer,FLength: Integer,FKind: TGocciaTypedArrayKind. - Shared prototype singleton — All TypedArray instances (regardless of kind) within an engine share a single per-engine prototype (
TGocciaSharedPrototype), stored in a realm slot. Prototype methods are registered once duringInitializePrototype; theTGocciaSharedPrototypepins the prototype and method host until the realm frees it. - Named property reads — Only a canonical numeric string is answered from the elements; every other name is an ordinary lookup, so
length,byteLength,byteOffsetandbuffercome from the accessors on%TypedArray%.prototypeandBYTES_PER_ELEMENTfrom the constructor's prototype. A replaced ornullprototype, an own property, or a getter defined by a subclass or a program is observed.TryGetNamedPropertyWithoutCallwalks the chain while every level is a plain object (the walk ofResolvePropertyWithoutCall, written out); when the property it reaches is a data property it returns the value, and when it is an accessor whose getter carries theTGocciaNativeIntrinsicKindthatInitializePrototypestamps on the four built-in getters withMarkIntrinsicGetter, it computes the getter's result from the internal slots instead of calling it. Anything else takes the full lookup. A name that cannot be a canonical numeric string is recognised by its first character, so it never reaches the String-to-Number round trip ofCanonicalNumericIndexString. - Reads with a receiver —
GetPropertyWithContextanswers a canonical numeric string from the elements too, whatever the receiver, soReflect.get(ta, "0", receiver), a Proxy without agettrap and an array, class instance or other exotic object whose prototype is a typed array all read the element (ES2026 §10.4.5.5). Any other name is the ordinary lookup with that receiver; the slot shortcut ofTryGetNamedPropertyWithoutCallapplies only when the typed array is the receiver, because the built-in getters read the receiver's slots. - Element access —
ReadElement(index): DoubleandWriteElement(index, value)delegate raw byte encoding toGoccia.BinaryData, using the same endian-aware helpers as DataView. Integer types wrap,Uint8ClampedArrayclamps, and float types preserve IEEE 754 encodings. WriteNumberLiteral(index, num)— HandlesTGocciaNumberLiteralValuespecial values (NaN,Infinity,-Infinity) correctly: NaN → 0 for integer types, NaN for float types; Infinity → 255 forUint8ClampedArray, 0 for other integer types; raw IEEE 754 bytes for float types throughGoccia.BinaryData. All write sites (property assignment,fill,set,map,with, constructors,from,of) use this helper.- Buffer sharing — Multiple TypedArrays can share the same ArrayBuffer or SharedArrayBuffer with different byte offsets and element types. Changes through one view are visible in others.
FBufferDatais a FPC dynamic array reference that shares the underlying byte array with the buffer object, so element writes are visible across all views without copying. Bounds come fromBufferByteLength(ArrayBufferByteLength), never from the block's length, because a growable SharedArrayBuffer's block is longer than its contents.FBufferDatais a cache:ArrayBuffer.prototype.resizeand detaching give an ArrayBuffer a new byte array (a SharedArrayBuffer never gets one), andSyncBufferDatarefreshes the cache before the unit's own reads. Code outside the unit reads the publicBufferDataproperty, which syncs on every read, soBufferDataandLengthdescribe the same block while no script code runs between the two reads; a per-byte loop readsBufferDataonce before the loop rather than once per byte. - SharedArrayBuffer support — TypedArrays can be constructed from both
TGocciaArrayBufferValueandTGocciaSharedArrayBufferValue. The.bufferproperty returns the original buffer object (preserving its type).subarraycreates a new view sharing the same buffer;slicealways creates a newTGocciaArrayBufferValuecopy. - Prototype methods —
at,fill,copyWithin,slice,subarray,set,reverse,sort,indexOf,lastIndexOf,includes,find,findIndex,findLast,findLastIndex,every,some,forEach,map,filter,reduce,reduceRight,join,toString,toReversed,toSorted,with,values,keys,entries,[Symbol.iterator]. - Static methods —
TypedArray.from(source [, mapFn]),TypedArray.of(...items). - GC integration —
TraceReferencesmarksFBufferValue(the underlying buffer, whether ArrayBuffer or SharedArrayBuffer). - Class values —
TGocciaTypedArrayClassValue(one per kind) handlesnew TypedArray(...)construction.TGocciaTypedArrayStaticFromprovidesfromandofstatic methods.
Search semantics: indexOf and lastIndexOf use strict equality (NaN !== NaN — always returns -1 for NaN). includes uses SameValueZero (NaN === NaN — finds NaN in float arrays via Math.IsNaN). All three handle Infinity/-Infinity by comparing actual IEEE 754 doubles for float arrays (where Infinity is stored as-is) and returning -1/false for integer arrays (where Infinity truncates to 0, losing identity).
Design Rationale
Number Representation
Numbers are represented by a single Double payload (FValue) using standard IEEE 754 bit patterns. Special values (NaN, Infinity, -Infinity, -0) are detected via property accessors (IsNaN, IsInfinity, IsNegativeInfinity, IsNegativeZero) that delegate to Math.IsNaN, Math.IsInfinite, and NumberBits.IsNegativeZero — the same helpers described in the Numbers section above.
This replaced an earlier enum-based design. See ADR 0001 and ADR 0016 for the history of this change.
Why property accessors matter:
- NaN identity — IEEE 754
NaN ≠ NaN, but JavaScript operations need reliable classification. Always useIsNaNrather than raw numeric comparison. - Negative zero —
-0and+0are equal in IEEE 754 but distinguishable in JavaScript (Object.is(-0, +0)isfalse). TheIsNegativeZeroaccessor encapsulates the sign-bit check. - Display correctness —
NaN.toString()must return"NaN", not a floating-point artifact. The accessors ensure correct string conversion.
Pitfall: raw Value = 0 checks. Value = 0 is true for both +0 and -0 (and false for NaN). That is right where the spec treats the zeros alike — NumberExponentiation (Goccia.NumberExponentiation.pas) returns 1 for any zero exponent, so (-0) ** 0 === 1. Where the sign matters, follow the zero test with an explicit IsNegativeZero check, as NumberExponentiation does for a zero base and as Object.is requires. Array sort does not compare doubles itself: CallCompareFunc in Goccia.Values.ArrayValue.pas normalises the comparator's result (NaN → 0, +Infinity → 1, -Infinity → -1).
this Binding Design
GocciaScript distinguishes two function forms — arrow functions and shorthand methods — with distinct this semantics that match ECMAScript strict mode.
The problem: By default (the recommended profile) there is no function keyword; it is off unless --compat-function is enabled. Arrow functions and shorthand methods have fundamentally different this semantics, but they need distinct representation at both the AST and runtime levels.
The solution: Separate AST nodes, compiled into function templates the VM tells apart:
| Syntax | AST Node | this binding |
|---|---|---|
(x) => x + 1 | TGocciaArrowFunctionExpression | Lexical (enclosing function's this) |
method() { ... } | TGocciaObjectMethodDefinition | Call-site (receiver) |
class { method() {} } | TGocciaClassMethod | Call-site (receiver) |
All three become a TGocciaBytecodeFunctionValue. An arrow's template has IsArrow set and its body reads this from the enclosing function through an upvalue; the other forms bind the call-site receiver.
Why this design?
- ECMAScript fidelity — Arrow functions always capture
thisfrom their defining scope; methods receivethisfrom their call site. This matches the spec exactly. - Strict mode by default — Standalone calls to either form receive
undefinedasthis, matching strict mode. There is no implicit globalthisunless script source enables--compat-non-strict-mode. - Callback correctness — Array prototype methods (
map,filter,reduce) passundefinedasThisValueto callbacks. Arrow function callbacks correctly inherit their enclosing method'sthis; extracted method references receiveundefined, preventing accidentalthisleakage.
Property Descriptor System
Object properties follow ECMAScript's property descriptor model:
- Data descriptors —
{ value, writable, enumerable, configurable } - Accessor descriptors —
{ get, set, enumerable, configurable } - Insertion order — Properties maintain their creation order, matching JavaScript's
Object.keys()ordering guarantee. - Descriptor merging —
Object.definePropertymerges the new descriptor with the existing one when the property already exists. Unspecified attributes retain their current values rather than resetting to defaults. This matches ECMAScript specification behavior (e.g.,Object.defineProperty(obj, "x", { enumerable: false })only changesenumerable, preservingwritable,configurable, andvalue). - Strict mode
delete— Deleting a non-configurable property throwsTypeErrorby default, matching ECMAScript strict mode semantics.DeletePropertyreturnsFalsefor non-configurable properties, and delete call sites convert this into aTypeErrorunless script source--compat-non-strict-modeis enabled. Deleting a non-existent property returnstrue(no error). - Strict mode assignment — Failed object
[[Set]]results, such as writes to non-writable data properties, setter-less accessors, or non-extensible objects, becomeTypeErrorby default. With script source--compat-non-strict-mode, the failed write stays silent while the assignment expression returns the assigned value.
This is more complex than a simple key-value map, but it's necessary for Object.defineProperty, getters/setters, and non-enumerable properties like prototype methods.
Class getters and setters are stored as accessor descriptors on the class prototype. TGocciaObjectValue.GetProperty and AssignProperty are virtual, and TGocciaInstanceValue overrides both to intercept property access — checking the prototype for accessor descriptors and invoking getter/setter functions with the instance as this context.
Private Field Storage
A private name is stored under a key that includes the brand token of the class that declares it (#slot:<token>:x). This solves the inheritance shadowing problem where a base class and a derived class both declare a private field with the same name — in JavaScript, Base.#x and Derived.#x are completely separate slots.
- Storage — A class instance keeps its private fields and brands in
TGocciaInstanceValue.FPrivateProperties, and a class keeps its static private elements in its own tables. Private methods and instance accessors, and the private elements of an object that is not a class instance (a constructor's return value), are kept inTGocciaObjectValue.PrivateElements, never among the object's properties. - Private names are not property keys — The compiler puts a private name's storage key in the constant pool as a
bckPrivateNameconstant, and the VM takes the private path only for an instruction that names one (or for theTGocciaPrivateNameKeyValuethatOP_LOAD_CONSTloads from it), never because of a key's text. A property named"#slot:0$x"is an ordinary property: it enumerates, serializes and answersinlike any other, and no property key reaches a private element. - Access resolution — When a method accesses
this.#x, the VM resolves the class body that declares the name, starting from the running closure'sPrivateClassand walking outward through enclosing class bodies (TGocciaVM.LexicalBytecodePrivateClass), and builds the key from that class (TGocciaVM.ResolveBytecodePrivateRuntimeKey). - Private getters/setters — Static ones are stored on
TGocciaClassValueinFPrivateGetters/FPrivateSetters; instance ones are accessor descriptors among the prototype'sPrivateElements. - Declaration order — Instance property initializers run in source declaration order, recorded in the class value's
FFieldOrder.
Garbage Collector
The GC design rationale (why mark-and-sweep, why not reference counting, AST literal ownership) lives in Garbage Collector.
Error Values
See Errors for the complete list of error types and user-facing display format, and JSON Output for the JSON output envelope.
JavaScript error objects are represented as TGocciaObjectValue instances with name, message, and stack string properties. Error constructors (new TypeError(...), new RangeError(...), etc.) create these objects via CreateErrorObject in Goccia.Values.ErrorHelper.pas.
Throwing is implemented via TGocciaThrowValue, a Pascal Exception subclass that wraps any TGocciaValue (the thrown value). The VM catches TGocciaThrowValue and hands the wrapped value to the catch handler (Architecture § Error Handling Strategy).
TGocciaError is a separate Pascal Exception subclass (not a TGocciaValue) used for internal Pascal-side exceptions: early parser/lexer errors (TGocciaSyntaxError and its subclass TGocciaLexerError) and runtime engine errors (TGocciaRuntimeError). These are internal Pascal exceptions, not JavaScript error objects. The subclass relationship mirrors the ES spec: all early errors (lexer and parser) are SyntaxError.