Commit graph

666 commits

Author SHA1 Message Date
Linus Groh
cf9da66b3e LibJS: Use Value::to_index() in typed array constructors 2020-12-02 23:49:00 +01:00
Linus Groh
eaa85969c4 LibJS: Add Value::to_{index,length,integer_or_infinity} abstract operations
We should pay more attention to using the well-defined abstract
operations from the spec rather than making up our own, often slightly
different rules. This is another step in that direction.
2020-12-02 23:49:00 +01:00
Linus Groh
6de4f1fcb3 LibJS: Add generic InvalidLength error type
We have multiple array types now, so ArrayInvalidLength has been
replaced with a generic InvalidLength.

Also fixes a small issue in the Array constructor, it should throw
RangeError for invalid lengths, not TypeError.
2020-12-02 23:49:00 +01:00
Linus Groh
0b086c759a LibJS: Move TypedArray length getter to prototype 2020-12-02 14:39:53 +01:00
Linus Groh
ddaab598a7 LibJS: Add TypedArray.BYTES_PER_ELEMENT 2020-12-02 12:52:31 +01:00
Linus Groh
3d05836a3e LibJS: Make TypedArray constructor (somewhat) spec-compliant
- Calling without 'new' is an error
- If the first argument is an object, we need a separate code path to
  initialize from TypedArray, ArrayBuffer, Iterable or Array-like
  object (marked TODO for now)
- Don't insert values into array if more than one argument is present
  (that's not part of the spec)
2020-12-02 12:52:31 +01:00
Linus Groh
1bff65c591 LibJS: Add ErrorType::ConstructorWithoutNew
...and use it in Proxy::call(), rather than having a specific error
type just for that.
2020-12-02 12:52:31 +01:00
Linus Groh
7fb299fe46 LibJS: Clean up TypedArray constructors and prototypes
The current implementation is not entirely correct yet. Two classes have
been added:
- TypedArrayConstructor, which the various typed array constructors now
  inherit from. Calling or constructing this class (from JS, that is)
  directly is not possible, we might want to move this abstract class
  functionality to NativeFunction at a later point.
- TypedArrayPrototype, which the various typed array prototypes now have
  as their own prototype. This will be the place where most of the
  functionality is being shared.

Relevant parts from the spec:

22.2.1 The %TypedArray% Intrinsic Object
The %TypedArray% intrinsic object:
- is a constructor function object that all of the TypedArray
  constructor objects inherit from.
- along with its corresponding prototype object, provides common
  properties that are inherited by all TypedArray constructors and their
  instances.

22.2.2 Properties of the %TypedArray% Intrinsic Object
The %TypedArray% intrinsic object:
- has a [[Prototype]] internal slot whose value is %Function.prototype%.

22.2.2.3 %TypedArray%.prototype
The initial value of %TypedArray%.prototype is the %TypedArray%
prototype object.

22.2.6 Properties of the TypedArray Constructors
Each TypedArray constructor:
- has a [[Prototype]] internal slot whose value is %TypedArray%.

22.2.6.2 TypedArray.prototype
The initial value of TypedArray.prototype is the corresponding
TypedArray prototype intrinsic object (22.2.7).

22.2.7 Properties of the TypedArray Prototype Objects
Each TypedArray prototype object:
- has a [[Prototype]] internal slot whose value is %TypedArray.prototype%.

22.2.7.2 TypedArray.prototype.constructor
The initial value of a TypedArray.prototype.constructor is the
corresponding %TypedArray% intrinsic object.
2020-12-02 12:52:31 +01:00
Andreas Kling
3565d3c60c LibJS: Add six typed arrays (signed and unsigned 8/16/32-bit)
This patch adds six of the standard type arrays and tries to share as
much code as possible:

- Uint8Array
- Uint16Array
- Uint32Array
- Int8Array
- Int16Array
- Int32Array
2020-12-01 21:05:25 +01:00
Andreas Kling
93feb7a81f LibJS: Have Uint8ClampedArray delegate OOB accesses to JS::Object
Uint8ClampedArray itself only cares about legitimate in-bounds accesses
since that's what where the specialization happens.
2020-12-01 17:12:04 +01:00
Andreas Kling
f2c7caf2db LibJS: Zero out memory in newly allocated Uint8ClampedArray objects 2020-12-01 17:06:48 +01:00
Linus Groh
48c19cdb06 LibJS: Remove ProxyPrototype
Proxy is an "exotic object" and doesn't have its own prototype. Use the
regular object prototype instead, but most stuff is happening on the
target object anyway. :^)
2020-12-01 09:54:37 +01:00
Andreas Kling
2d9d883274 LibJS: Add a basic implementation of String.prototype.substr() 2020-11-29 20:29:49 +01:00
Andreas Kling
2e4832c3da LibJS: Constructor function's "prototype" property should be writable
This matches other engines.
2020-11-29 19:49:27 +01:00
Andreas Kling
01c8765519 LibJS+LibWeb: Log JavaScript exceptions raised by web content
Instead of hiding JS exceptions raised on the web, we now print them to
the debug log. This will make it a bit easier to work out why some web
pages aren't working right. :^)
2020-11-29 16:50:32 +01:00
Andreas Kling
42b1b36eb4 LibJS: Run clang-format on WithScope.h 2020-11-28 17:36:38 +01:00
Andreas Kling
9de6443ab7 LibJS: Add basic support for "with" statements
with statements evaluate an expression and put the result of it at the
"front" of the scope chain. This is implemented by creating a WithScope
object and placing it in front of the VM's current call frame's scope.
2020-11-28 17:16:48 +01:00
Andreas Kling
c3fe9b4df8 LibJS: Add a scope object abstraction
Both GlobalObject and LexicalEnvironment now inherit from ScopeObject,
and the VM's call frames point to a ScopeObject chain rather than just
a LexicalEnvironment chain.

This gives us much more flexibility to implement things like "with",
and also unifies some of the code paths that previously required
special handling of the global object.

There's a bunch of more cleanup that can be done in the wake of this
change, and there might be some oversights in the handling of the
"super" keyword, but this generally seems like a good architectural
improvement. :^)
2020-11-28 17:16:48 +01:00
Andreas Kling
e1bbc7c075 LibJS: Make JS::Value constructors take const cell pointers
Taking non-const cell pointers is asking for trouble, since passing e.g
a "const Object*" to Value(Object*) will actually call Value(bool),
which is most likely not what you want.
2020-11-28 17:16:48 +01:00
Andreas Kling
98f2da9834 LibJS: Rename Cell::visit_children() => Cell::visit_edges()
The GC heap is really a graph of cells, so "children" didn't quite feel
appropriate here.
2020-11-28 17:16:48 +01:00
Andreas Kling
97a05ac9ac LibJS: Allow Shape without a global object
It would be nice to be able to cache some shapes globally in the VM,
but then they can't be tied to a specific global object. So let's just
get rid of the requirement that shapes are tied to a global object.
2020-11-28 17:16:48 +01:00
Linus Groh
149b54e26f LibJS: Remove quotes from RegExpCompileError message
They look a bit out of place, especially for multi-line error messages.
2020-11-28 16:46:25 +01:00
Linus Groh
7dd77020ae LibJS: Use enumerator macros to define RegExp.prototype flag getters 2020-11-28 01:20:11 +01:00
Linus Groh
8a9a7f1677 LibJS: Make RegExp.prototype.source spec-compliant
Basically:
- And edge case for this object being RegExp.prototype.source
- Return "(?:)" for empty pattern
- Escape some things properly
2020-11-28 01:20:11 +01:00
Linus Groh
b6e5442d55 LibJS: Make RegExp.prototype.toString() spec-compliant
It should use the 'source' and 'flags' properties of the object, and
therefore work with non-RegExp objects as well.
2020-11-28 01:20:11 +01:00
Linus Groh
ee66eaa1b0 LibJS: Make RegExp.prototype.flags spec-compliant
This should be using the individual flag boolean properties rather than
the [[OriginalFlags]] internal slot.
Use an enumerator macro here for brevity, this will be useful for other
things as well. :^)
2020-11-28 01:20:11 +01:00
Linus Groh
5cb45e4feb LibJS: Make RegExp() constructor spec-compliant
- Default values should depend on arguments being undefined, not being
  missing
- "(?:)" for empty pattern happens in RegExp.prototype.source, not the
  constructor
2020-11-28 01:20:11 +01:00
AnotherTest
210a3db44d LibJS: Implement `RegExpPrototype::exec()'
This implements *only* the builtin exec() function.
2020-11-27 21:32:41 +01:00
AnotherTest
8ba273a2f3 LibJS: Hook up Regex<ECMA262> to RegExpObject and implement `test()'
This makes RegExpObject compile and store a Regex<ECMA262>, adds
all flag-related properties, and implements `RegExpPrototype.test()`
(complete with 'lastIndex' support) :^)
It should be noted that this only implements `test()' using the builtin
`exec()'.
2020-11-27 21:32:41 +01:00
AnotherTest
3200ff5f4f LibJS+js: Rename RegExp.{content => pattern}
The spec talks about it as 'pattern', so let's use that instead.
2020-11-27 21:32:41 +01:00
Linus Groh
f6f0d3cbae LibJS: Support receiver in ProxyObject::get/put()
If a receiver is given, e.g. via Reflect.get/set(), forward it to the
target object's get()/put() or use it as last argument of the trap
function. The default value is the Proxy object itself.
2020-11-24 21:35:03 +01:00
Linus Groh
48369194d2 LibJS: Forward receiver value to native property getters/setters
There's no reason why only (user-defined) accessors would have set the
receiver as this value for their getters/setters, this is an oversight.
2020-11-22 19:00:19 +01:00
Linus Groh
c52739ea4b LibJS: Make call_native_property_{g,s}etter() take a NativeProperty&
Passing in a plain Value and expecting it to be a native property is
error prone, let's use a more narrow type and pass a NativeProperty
reference directly.
2020-11-22 19:00:19 +01:00
Luke
bbc0487ced LibJS: Fix build with VM_DEBUG defined 2020-11-22 11:35:13 +01:00
Linus Groh
5a307836c1 LibJS: Handle symbol PropertyName in primitive assignment error
We can't just to_string() the PropertyName, it might be a symbol.
Instead to_value() it and then use to_string_without_side_effects() as
usual.

Fixes #4062.
2020-11-12 11:40:29 +01:00
Linus Groh
1b0c862f3a LibJS: Throw TypeError when calling class constructor without 'new' 2020-11-12 10:14:00 +01:00
Linus Groh
b07c7f589f LibJS: Refactor ScriptFunction::call() a bit
- Get VM reference once
- Less nesting
- Better variable names
2020-11-12 10:14:00 +01:00
Luke
bb22b04d44 LibWeb+LibJS: Add [LegacyNullToEmptyString] attribute
If specified, to_string() returns an empty string instead of "null" for
null values.
2020-11-11 12:15:05 +01:00
Linus Groh
a02b9983f9 LibJS: Throw RuntimeError when reaching the end of the stack
This prevents stack overflows when calling infinite/deep recursive
functions, e.g.:

    const f = () => f(); f();
    JSON.stringify({}, () => ({ foo: "bar" }));
    new Proxy({}, { get: (_, __, p) => p.foo }).foo;

The VM caches a StackInfo object to not slow down function calls
considerably. VM::push_call_frame() will throw an exception if
necessary (plain Error with "RuntimeError" as its .name).
2020-11-08 16:51:54 +01:00
Linus Groh
9c3ead8f91 LibJS+AK: Move cross-platform stack bounds code from JS::Heap to AK::StackInfo
This will be useful for other things than the Heap, maybe even outside
of LibJS.
2020-11-08 16:51:54 +01:00
Andreas Kling
43ff2ea8d8 LibJS: Use regular stack for VM call frames instead of Vector storage
Keeping the VM call frames in a Vector could cause them to move around
underneath us due to Vector resizing. Avoid this issue by allocating
CallFrame objects on the stack and having the VM simply keep a list
of pointers to each CallFrame, instead of the CallFrames themselves.

Fixes #3830.
Fixes #3951.
2020-11-07 13:58:28 +01:00
Luke
f5aad71c15 LibJS: Remove unused variable m_has_property_table in Shape 2020-11-07 10:09:55 +01:00
Luke
020b782474 LibJS: Use pow instead of __bulitin_pow on clang
__bulitin_pow doesn't seem to exist on clang, at least
it didn't build with it.
2020-11-07 10:09:55 +01:00
Linus Groh
06a3625545 LibJS: Set prototype of GlobalObject to ObjectPrototype
As the global object is constructed and initialized in a different way
than most other objects we were not setting its prototype! This made
things like "globalThis.toString()" fail unexpectedly.
2020-11-07 10:08:05 +01:00
Linus Groh
965050796f LibJS: Don't create StringOrSymbol(String) if from_value() fails
If value.to_string() throws an exception and returns a null string we
must create an invalid StringOrSymbol, not one from the null string
(which ASSERT()s).
2020-11-07 10:08:05 +01:00
Linus Groh
021c8dea1f LibJS: Skip trailing empty values in IndexedPropertyIterator
When we reach the end of the pre-computed indices vector we can just
skip to the end (array-like size) as only empty values will follow.

Fixes #3970.
2020-11-07 10:03:58 +01:00
Linus Groh
82b42cefbd LibJS: Handle circular references in Array.prototype.toLocaleString()
Also use ArmedScopeGuard for removing seen objects to account for early
returns.

Fixes #3963.
2020-11-06 15:50:18 +01:00
Linus Groh
dec6c0a207 LibJS: Use array-like size for IndexedProperties::is_empty()
Some things, like (the non-generic version of) Array.prototype.pop(),
check is_empty() to determine whether an action, like removing elements,
can be performed. We need to know the array-like size for that, not the
size of the underlying storage, which can be different - and is not
something IndexedProperties should expose so I removed its size().

Fixes #3948.
2020-11-05 20:01:30 +01:00
Linus Groh
0bb66890c8 LibJS: Fix Object::delete_property() with numeric string property
- We have to check if the property name is a string before calling
  as_string() on it
- We can't as_number() the same property name but have to use the parsed
  index number

Fixes #3950.
2020-11-05 19:15:00 +01:00
Linus Groh
8d96f428ef LibJS: ASSERT(property_name.is_valid()) in more Object methods 2020-11-05 19:15:00 +01:00
Linus Groh
2cf8649d0e LibJS: Fix ProxyObject get/set with symbol property name
We can't assume that property names can be converted to strings anymore,
as we have symbols. Use name.to_value() instead.

This makes something like this possible:

    new Proxy(Object, { get(t, p) { return t[p] }  })[Symbol.hasInstance]
2020-11-04 23:06:44 +01:00
Linus Groh
44e38b8457 LibJS: Replace a bunch of vm() calls in ProxyObject with reference
This was probably a result of search & replace, it's quite ridiculous in
some places. Let use the existing pattern of getting a reference to the
VM once at each function start consistently.
2020-11-04 23:06:44 +01:00
Linus Groh
2645dfafcf LibJS: Implement Object(value) constructor
Not sure why we didn't have this yet, it's super simple :^)
2020-11-04 23:06:44 +01:00
Linus Groh
0603402c80 LibJS: Handle circular references in Array.prototype.join()
This fixes Array.prototype.{join,toString}() crashing with arrays
containing themselves, i.e. circular references.

The spec is suspiciously silent about this, and indeed engine262, a
"100% spec compliant" ECMA-262 implementation, can't handle these cases.
I had a look at some major engines instead and they all seem to keep
track or check for circular references and return an empty string for
already seen objects.

- SpiderMonkey: "AutoCycleDetector detector(cx, obj)"
- V8: "CycleProtectedArrayJoin<JSArray>(...)"
- JavaScriptCore: "StringRecursionChecker checker(globalObject, thisObject)"
- ChakraCore: "scriptContext->CheckObject(thisArg)"

To keep things simple & consistent this uses the same pattern as
JSONObject, MarkupGenerator and js: simply putting each seen object in a
HashTable<Object*>.

Fixes #3929.
2020-11-04 19:35:43 +01:00
Linus Groh
e5845ba3a0 LibJS: Use "," separator in Array.prototype.join() if first arg is undefined
This is how the spec describes it, not "if the first arg is missing".
Also swap length & separator steps to match spec.
2020-11-04 19:35:43 +01:00
Linus Groh
fb89c324c5 LibJS: Implement spec-compliant OrdinaryToPrimitive
This renames Object::to_primitive() to Object::ordinary_to_primitive()
for two reasons:

- No confusion with Value::to_primitive()
- To match the spec's name

Also change existing uses of Object::to_primitive() to
Value::to_primitive() when the spec uses the latter (which will still
call Object::ordinary_to_primitive()). Object::to_string() has been
removed as it's not needed anymore (and nothing the spec uses).

This makes it possible to overwrite an object's toString and valueOf and
have them provide results for anything that uses to_primitive() - e.g.:

    const o = { toString: undefined, valueOf: () => 42 };
    Number(o) // 42, previously NaN
    ["foo", o].toString(); // "foo,42", previously "foo,[object Object]"
    ++o // 43, previously NaN

etc.
2020-11-04 19:33:49 +01:00
Linus Groh
e163db248d LibJS: Implement RegExp.prototype.toString() as standalone function
This should not just inherit Object.prototype.toString() (and override
Object::to_string()) but be its own function, i.e.
'RegExp.prototype.toString !== Object.prototype.toString'.
2020-11-04 19:33:49 +01:00
Linus Groh
41837f548d LibJS: Don't create "valid" PropertyName from null string
When value.to_string() throws an exception it returns a null string in
which case we must not construct a valid PropertyName.

Also ASSERT in PropertyName(String) and PropertyName(FlyString) to
prevent this from happening in the future.

Fixes #3941.
2020-11-04 15:31:39 +01:00
Linus Groh
8afe1c8165 LibJS: Fix incorrect exception checks in ProxyObject
We must *never* call some method that expects a non-empty value on the
result of a function call without checking for exceptions first. It
won't work reliably.

Fixes #3939.
2020-11-04 14:21:06 +01:00
Linus Groh
565a26808d LibJS: Fix crashing exception in Value::ordinary_has_instance()
Two issues:

- throw_exception() with ErrorType::InstanceOfOperatorBadPrototype would
  receive rhs_prototype.to_string_without_side_effects(), which would
  ASSERT_NOT_REACHED() as to_string_without_side_effects() must not be
  called on an empty value. It should (and now does) receive the RHS
  value instead as the message is "'prototype' property of {} is not an
  object".
- Value::instance_of() was missing an exception check after calling
  has_instance_method, to_boolean() on an empty value result would crash
  as well.

Fixes #3930.
2020-11-03 19:14:13 +01:00
Linus Groh
39a1c9d827 LibJS: Implement 'new.target'
This adds a new MetaProperty AST node which will be used for
'new.target' and 'import.meta' meta properties. The parser now
distinguishes between "in function context" and "in arrow function
context" (which is required for this).
When encountering TokenType::New we will attempt to parse it as meta
property and resort to regular new expression parsing if that fails,
much like the parsing of labelled statements.
2020-11-02 22:40:59 +01:00
Linus Groh
a10d09faba LibJS: Tweak generated source in 'new Function()' to match ES 2015 spec
ES 5(.1) described parsing of the function body string as:

https://www.ecma-international.org/ecma-262/5.1/#sec-15.3.2.1

7. If P is not parsable as a FormalParameterList[opt] then throw a SyntaxError exception.
8. If body is not parsable as FunctionBody then throw a SyntaxError exception.

We implemented it as building the source string of a complete function
and feeding that to the parser, with the same outcome. ES 2015+ does
exactly that, but with newlines at certain positions:

https://tc39.es/ecma262/#sec-createdynamicfunction

16. Let bodyString be the string-concatenation of 0x000A (LINE FEED), ? ToString(bodyArg), and 0x000A (LINE FEED).
17. Let prefix be the prefix associated with kind in Table 49.
18. Let sourceString be the string-concatenation of prefix, " anonymous(", P, 0x000A (LINE FEED), ") {", bodyString, and "}".

This patch updates the generated source string to match these
requirements. This will make certain edge cases work, e.g.
'new Function("-->")', where the user supplied input must be placed on
its own line to be valid syntax.
2020-10-29 22:27:55 +01:00
Andreas Kling
619cd613d0 LibJS: Give VM a cache of single-ASCII-character PrimitiveString
A large number of JS strings are a single ASCII character. This patch
adds a 128-entry cache for those strings to the VM. The cost of the
cache is 1536 byte of GC heap (all in same block) + 2304 bytes malloc.

This avoids a lot of GC heap allocations, and packing all of these
in the same heap block is nice for fragmentation as well.
2020-10-22 17:48:12 +02:00
Andreas Kling
5c2520e6b2 LibJS: Simplify environment access a little bit in VM::construct() 2020-10-22 17:23:40 +02:00
Andreas Kling
07f76cd980 LibJS: Shrink sizeof(LexicalEnvironment) by reorganizing members 2020-10-22 17:03:40 +02:00
Linus Groh
a82c56f9f7 LibJS: Speed up IndexedPropertyIterator by computing non-empty indices
This provides a huge speed-up for objects with large numbers as property
keys in some situation. Previously we would simply iterate from 0-<max>
and check if there's a non-empty value at each index - now we're being
smarter and compute a list of non-empty indices upfront, by checking
each value in the packed elements vector and appending the sparse
elements hashmap keys (for GenericIndexedPropertyStorage).

Consider this example, an object with a single own property, which is a
number increasing by a factor of 10 each iteration:

    for (let i = 0; i < 10; ++i) {
        const o = {[10 ** i]: "foo"};
        const start = Date.now();
        Object.getOwnPropertyNames(o);  // <-- IndexedPropertyIterator
        const end = Date.now();
        console.log(`${10 ** i} -> ${(end - start) / 1000}s`);
    }

Before this change:

    1 -> 0.0000s
    10 -> 0.0000s
    100 -> 0.0000s
    1000 -> 0.0000s
    10000 -> 0.0005s
    100000 -> 0.0039s
    1000000 -> 0.0295s
    10000000 -> 0.2489s
    100000000 -> 2.4758s
    1000000000 -> 25.5669s

After this change:

    1 -> 0.0000s
    10 -> 0.0000s
    100 -> 0.0000s
    1000 -> 0.0000s
    10000 -> 0.0000s
    100000 -> 0.0000s
    1000000 -> 0.0000s
    10000000 -> 0.0000s
    100000000 -> 0.0000s
    1000000000 -> 0.0000s

Fixes #3805.
2020-10-20 08:51:41 +02:00
Andreas Kling
77c1957961 LibJS: Use allocate_without_global_object for allocating Shapes 2020-10-17 23:47:07 +02:00
Andreas Kling
d3dfd55472 LibJS: Prebake the empty object ({}) with a prototype
Instead of performing a prototype transition for every new object we
create via {}, prebake the object returned by Object::create_empty()
with a shape with ObjectPrototype as the prototype.

We also prebake the shape for the object assigned to the "prototype"
property of new ScriptFunction objects, since those are extremely
common and that code broke from this change anyway.

This avoid a large number of transitions and is a small speed-up on
test-js.
2020-10-17 23:23:53 +02:00
Linus Groh
b98b83712f LibJS: constexpr some Number object constant values 2020-10-16 17:06:57 +02:00
Andreas Kling
2c956ac132 LibJS: Reorganize Shape members to reduce sizeof(Shape) a bit 2020-10-16 16:46:27 +02:00
Andreas Kling
2c0e153396 LibJS: Don't bother deferring GC during ensure_property_table()
This is not actually necessary, since no GC allocations are made during
this process. If we ever make property tables into heap cells, we'd
have to rethink this.
2020-10-16 08:59:51 +02:00
Andreas Kling
4387590e65 LibJS: Support move semantics for StringOrSymbol
This allows us to rehash property tables without a bunch of ref count
churn happening.
2020-10-15 23:49:53 +02:00
Andreas Kling
1d96ecf148 Everywhere: Add missing <AK/TemporaryChange.h> includes
Don't rely on HashTable.h pulling this in.
2020-10-15 23:49:53 +02:00
Linus Groh
e07490ce13 LibJS: Don't assume value for index < size in IndexedPropertyIterator
This assumption only works for the m_packed_elements Vector where a
missing value at a certain index still returns an empty value, but not
for the m_sparse_elements HashMap, which is being used for indices
>= 200 - in that case the Optional<ValueAndAttributes> result will not
have a value.

This fixes a crash in the js REPL where printing an array with a hole at
any index >= 200 would crash.
2020-10-14 00:52:47 +02:00
Andreas Kling
a1029738fd LibJS: Add some more items to CommonPropertyNames that I missed 2020-10-14 00:10:49 +02:00
Andreas Kling
8f535435dc LibJS: Avoid property lookups during object initialization
When we're initializing objects, we're just adding a bunch of new
properties, without transition, and without overlap (we never add
the same property twice.)

Take advantage of this by skipping lookups entirely (no need to see
if we're overwriting an existing property) during initialization.

Another nice test-js speedup :^)
2020-10-13 23:57:45 +02:00
Andreas Kling
7b863330dc LibJS: Cache commonly used FlyStrings in the VM
Roughly 7% of test-js runtime was spent creating FlyStrings from string
literals. This patch frontloads that work and caches all the commonly
used names in LibJS on a CommonPropertyNames struct that hangs off VM.
2020-10-13 23:57:45 +02:00
Linus Groh
a5bf6cfff9 LibJS: Don't change offset when reconfiguring property in unique shape
When changing the attributes of an existing property of an object with
unique shape we must not change the PropertyMetadata offset.
Doing so without resizing the underlying storage vector caused an OOB
write crash.

Fixes #3735.
2020-10-10 23:25:00 +02:00
Matthew Olsson
6e05685ad4 LibJS: Fix return statements not working properly in loops
Previously, when a loop detected an unwind of type ScopeType::Function
(which means a return statement was executed inside of the loop), it
would just return undefined. This set the VM's last_value to undefined,
when it should have been the returned value. This patch makes all loop
statements return the appropriate value in the above case.
2020-10-08 23:23:55 +02:00
Linus Groh
bc78e4b7da LibJS: Fix PropertyName::from_value() for negative and non-int numbers
It was converting *any* number to an i32 index, which obviously is not
correct for negative ints, doubles, infinity and nan.

Fixes #3712.
2020-10-08 10:02:47 +02:00
Andreas Kling
8baacda03d LibJS: Fix weird self-including header 2020-10-06 18:37:58 +02:00
Andreas Kling
4c33209011 LibJS: Add Object::define_property_without_transition() helper
This allows us to avoid transitioning in two common cases, saving some
time during object construction.
2020-10-06 17:43:51 +02:00
Andreas Kling
148c4161d9 LibJS: Avoid work in Shape::lookup() if there are no properties 2020-10-05 20:53:00 +02:00
Andreas Kling
69bae3fd9a LibJS: Prevent object shape transitions during runtime object buildup
While initialization common runtime objects like functions, prototypes,
etc, we don't really care about tracking transitions for each and every
property added to them.

This patch puts objects into a "disable transitions" mode while we call
initialize() on them. After that, adding more properties will cause new
transitions to be generated and added to the chain.

This gives a ~10% speed-up on test-js. :^)
2020-10-05 20:53:00 +02:00
Andreas Kling
50ab87f651 LibJS: Make use of existing property tables when reifying new ones
When reifying a shape transition chain, look for the nearest previous
shape in the transition chain that has a property table already, and
use that as the starting point.

This achieves two things:

1. We do less work when reifying property tables that already have
   partial property tables earlier in the chain.

2. This enables adding properties to a shape without performing a
   transition. This will be useful for initializing runtime objects
   with way fewer allocations. See next patch. :^)
2020-10-05 20:53:00 +02:00
Nico Weber
d8d00d3ac7 LibJS: Add StringOrSymbol::as_string_impl() helper 2020-10-05 17:35:27 +02:00
Nico Weber
cc765e14ca AK: Move StringImpl::operator== implementation into StringImpl 2020-10-05 17:35:27 +02:00
Andreas Kling
ec55490198 LibJS: Make global objects have unique shape from the start
There's no point in trying to achieve shape sharing for global objects,
so we can simply make the shape unique from the start and avoid making
a transition chain.
2020-10-04 22:56:45 +02:00
Andreas Kling
2864cb66c0 LibJS: Avoid an unnecessary MarkedValueList copy in VM::call_internal() 2020-10-04 22:42:24 +02:00
Andreas Kling
ad0d377e4c LibJS: Pre-size the hash map and vector used in ensure_property_table() 2020-10-04 19:25:49 +02:00
Andreas Kling
b7975abef8 LibJS: Don't force property table reification on Shape::property_count()
Previously whenever you would ask a Shape how many properties it had,
it would reify the property table into a HashMap and use HashMap::size()
to answer the question.

This can be a huge waste of time if we don't need the property table for
anything else, so this patch implements property count tracking in a
separate integer member of Shape. :^)
2020-10-04 19:25:49 +02:00
Andreas Kling
d01b746d88 LibJS: Add StringOrSymbol constructor that takes a FlyString
This avoids refcount churn from implicit conversion in some places.
2020-10-04 19:25:49 +02:00
Andreas Kling
3d053f244f LibJS: Avoid creating a temporary String in StringOrSymbol::operator== 2020-10-04 19:25:49 +02:00
Andreas Kling
d542049596 LibJS: Avoid StringImpl refcount churn when hashing StringOrSymbol
Add a StringOrSymbol::hash() helper function so we can compute the hash
without having to construct a temporary String.
2020-10-04 19:25:49 +02:00
Andreas Kling
cfd141b4f9 LibJS: Avoid unnecessary StringImpl copy in StringOrSymbol(String) 2020-10-04 19:25:49 +02:00
Linus Groh
5de5af60c1 LibJS: Replace a few dbg() with dbgln() 2020-10-04 19:22:02 +02:00
Linus Groh
123f98201e LibJS: Use String::formatted() in various other places 2020-10-04 19:22:02 +02:00
Linus Groh
2e2571743b LibJS: Use string::formatted() in to_string() functions 2020-10-04 19:22:02 +02:00
Linus Groh
f9eaac62d9 LibJS: Use String::formatted() for throw_exception() message 2020-10-04 19:22:02 +02:00
Andreas Kling
bfa97b9357 LibJS: Remove Cell::interpreter()
It's never necessary to find the current Interpreter for a given Cell
anymore. Get rid of this accessor.
2020-10-04 17:03:33 +02:00
Andreas Kling
a007b3c379 LibJS: Move "strict mode" state to the call stack
Each call frame now knows whether it's executing in strict mode.
It's no longer necessary to access the scope stack to find this mode.
2020-10-04 17:03:33 +02:00
Matthew Olsson
6eb6752c4c LibJS: Strict mode is now handled by Functions and Programs, not Blocks
Since blocks can't be strict by themselves, it makes no sense for them
to store whether or not they are strict. Strict-ness is now stored in
the Program and FunctionNode ASTNodes. Fixes issue #3641
2020-10-04 10:46:12 +02:00
Andreas Kling
fa18baf3e8 LibJS: Add Value::is_nullish() 2020-10-02 18:01:27 +02:00
Andreas Kling
e4bda2e1e7 LibJS: Move Console from Interpreter to GlobalObject
Each JS global object has its own "console", so it makes more sense to
store it in GlobalObject.

We'll need some smartness later to bundle up console messages from all
the different frames that make up a page later, but this works for now.
2020-09-29 21:15:06 +02:00
Andreas Kling
be055b3ddd LibJS: Reduce use of Interpreter in Reference 2020-09-29 16:45:39 +02:00
Andreas Kling
3df604ad12 LibJS: Reduce use of Interpreter in LexicalEnvironment 2020-09-29 16:41:28 +02:00
Andreas Kling
ebe1288aea LibJS: Add missing <AK/Function.h> include in JSONObject.cpp 2020-09-28 09:17:33 +02:00
AnotherTest
5fbec2b003 AK: Move trim_whitespace() into StringUtils and add it to StringView
No behaviour change; also patches use of `String::TrimMode` in LibJS.
2020-09-27 21:14:18 +02:00
Andreas Kling
340d6b0ef7 LibJS: Stop using Interpreter& in the iterator operations helpers 2020-09-27 20:26:58 +02:00
Andreas Kling
2bc5bc64fb LibJS: Remove a whole bunch of includes of <LibJS/Interpreter.h> 2020-09-27 20:26:58 +02:00
Andreas Kling
063acda76e LibJS: Remove a bunch of unnecessary uses of Cell::interpreter()
We'll want to get rid of all uses of this, to free up the engine from
the old assumption that there's always an Interpreter available.
2020-09-27 20:26:58 +02:00
Andreas Kling
591b7b7031 LibJS: Remove js_string(Interpreter&, ...) 2020-09-27 20:26:58 +02:00
Andreas Kling
adf0a537af LibJS: Remove js_bigint(Interpreter&, ...) 2020-09-27 20:26:58 +02:00
Andreas Kling
a61ede51e2 LibJS: Don't require Interpreter& for constructing an Accessor 2020-09-27 20:26:58 +02:00
Andreas Kling
c59a8d84d3 LibJS: Reduce Interpreter& usage in the Object class 2020-09-27 20:26:58 +02:00
Andreas Kling
b9793e603c LibJS: Don't require Interpreter& in PropertyName and StringOrSymbol 2020-09-27 20:26:58 +02:00
Andreas Kling
1df18c58f5 LibJS: Make all the JS::Value binary op helpers take GlobalObject&
We don't need the Interpreter& for anything here, the GlobalObject is
enough for getting to the VM and possibly throwing exceptions.
2020-09-27 20:26:58 +02:00
Andreas Kling
30ca9acd9c LibJS: Remove unused js_symbol(Interpreter&, ...) 2020-09-27 20:26:58 +02:00
Andreas Kling
aaa8b48a4c LibJS: Remove use of Interpreter& in JSONObject code 2020-09-27 20:26:58 +02:00
Andreas Kling
f79d4c7347 LibJS: Remove Interpreter& argument to Function::construct()
This is no longer needed, we can get everything we need from the VM.
2020-09-27 20:26:58 +02:00
Andreas Kling
340a115dfe LibJS: Make native function/property callbacks take VM, not Interpreter
More work on decoupling the general runtime from Interpreter. The goal
is becoming clearer. Interpreter should be one possible way to execute
code inside a VM. In the future we might have other ways :^)
2020-09-27 20:26:58 +02:00
Andreas Kling
1ff9d33131 LibJS: Make Function::call() not require an Interpreter&
This makes a difference inside ScriptFunction::call(), which will now
instantiate a temporary Interpreter if one is not attached to the VM.
2020-09-27 20:26:58 +02:00
Andreas Kling
be31805e8b LibJS: Move scope stack from VM back to Interpreter
Okay, my vision here is improving. Interpreter should be a thing that
executes an AST. The scope stack is irrelevant to the VM proper,
so we can move that to the Interpreter. Same with execute_statement().
2020-09-27 20:26:58 +02:00
Andreas Kling
6861c619c6 LibJS: Move most of Interpreter into VM
This patch moves the exception state, call stack and scope stack from
Interpreter to VM. I'm doing this to help myself discover what the
split between Interpreter and VM should be, by shuffling things around
and seeing what falls where.

With these changes, we no longer have a persistent lexical environment
for the current global object on the Interpreter's call stack. Instead,
we push/pop that environment on Interpreter::run() enter/exit.
Since it should only be used to find the global "this", and not for
variable storage (that goes directly into the global object instead!),
I had to insert some short-circuiting when walking the environment
parent chain during variable lookup.

Note that this is a "stepping stone" commit, not a final design.
2020-09-27 20:26:58 +02:00
Ben Wiederhake
08f9bc26a6 Meta+LibHTTP through LibWeb: Make clang-format-10 clean 2020-09-25 21:18:17 +02:00
Andreas Kling
69bbf0285b LibJS: Let the VM cache an empty ("") PrimitiveString
Empty string is extremely common and we can avoid a lot of heap churn
by simply caching one in the VM. Primitive strings are immutable anyway
so there is no observable behavior change outside of fewer collections.
2020-09-22 20:10:20 +02:00
Andreas Kling
d1b58ee9ad LibJS: Move well-known symbols to the VM
No need to instantiate unique symbols for each Interpreter; they can
be VM-global. This reduces the memory cost and startup time anyway.
2020-09-22 20:10:20 +02:00
Andreas Kling
676cb87a8f LibJS: Use VM::exception() instead of Interpreter::exception() a bunch
There's a lot more of these things to fix. We'll also want to move from
passing Interpreter& around to VM& instead wherever that is enough.
2020-09-22 20:10:20 +02:00
Andreas Kling
d74bb87d46 LibJS: Add a way to get from a Cell to the VM 2020-09-22 20:10:20 +02:00
Andreas Kling
4a8bfcdd1c LibJS: Move the current exception from Interpreter to VM
This will allow us to throw exceptions even when there is no active
interpreter in the VM.
2020-09-22 20:10:20 +02:00
Andreas Kling
5b6ccbb918 LibJS: VM::interpreter() should just assert when no active interpreter
I accidentally committed some code here to force a crash, but this
should just assert.
2020-09-21 14:42:26 +02:00
Andreas Kling
df3ff76815 LibJS: Rename InterpreterScope => InterpreterExecutionScope
To make it a little clearer what this is for. (This is an RAII helper
class for adding and removing an Interpreter to a VM's list of the
currently active (executing code) Interpreters.)
2020-09-21 14:35:12 +02:00
Andreas Kling
fbe2907510 LibJS: GC should gather roots from all active interpreters
If we are in a nested execution context, we shouldn't only mark things
used by the active interpreter.
2020-09-21 14:34:40 +02:00
Andreas Kling
1c43442be4 LibJS+Clients: Add JS::VM object, separate Heap from Interpreter
Taking a big step towards a world of multiple global object, this patch
adds a new JS::VM object that houses the JS::Heap.

This means that the Heap moves out of Interpreter, and the same Heap
can now be used by multiple Interpreters, and can also outlive them.

The VM keeps a stack of Interpreter pointers. We push/pop on this
stack when entering/exiting execution with a given Interpreter.
This allows us to make this change without disturbing too much of
the existing code.

There is still a 1-to-1 relationship between Interpreter and the
global object. This will change in the future.

Ultimately, the goal here is to make Interpreter a transient object
that only needs to exist while you execute some code. Getting there
will take a lot more work though. :^)

Note that in LibWeb, the global JS::VM is called main_thread_vm(),
to distinguish it from future worker VM's.
2020-09-20 19:24:44 +02:00
Andreas Kling
976e55e942 LibJS: Remove some unnecessary indirection in Object constructors 2020-09-20 19:18:05 +02:00
Andreas Kling
893df28e80 LibJS: Don't allocate property table during GC marking phase
Shape was allocating property tables inside visit_children(), which
could cause garbage collection to happen. It's not very good to start
a new garbage collection while you are in the middle of one already.
2020-09-20 19:11:49 +02:00
Andreas Kling
4036ff9d91 LibJS: Remove unused argument in NativeFunction constructor 2020-09-20 19:11:11 +02:00
Linus Groh
c0e4353bde LibJS: Handle getter exception in JSONObject::serialize_json_property()
In the case of an exception in a property getter function we would not
return early, and a subsequent attempt to call the replacer function
would crash the interpreter due to call_internal() asserting.

Fixes #3548.
2020-09-19 14:17:22 +02:00
Linus Groh
ec43f73b74 LibJS: Extract most of Interpreter's run() into execute_statement()
Interpreter::run() was so far being used both as the "public API entry
point" for running a JS::Program as well as internally to execute
JS::Statement|s of all kinds - this is now more distinctly separated.
A program as returned by the parser is still going through run(), which
is responsible for creating the initial global call frame, but all other
statements are executed via execute_statement() directly.

Fixes #3437, a regression introduced by adding ASSERT(!exception()) to
run() without considering the effects that would have on internal usage.
2020-09-12 09:31:16 +02:00
Andreas Kling
d830c107ce LibJS: Deal with a FIXME in Shape::ensure_property_table()
Prevent GC while messing with the shape transition chain.
2020-09-09 21:34:02 +02:00
Andreas Kling
d467a0ffef LibJS: ArrayIterator needs to mark the array it's iterating 2020-09-08 16:20:34 +02:00
Andreas Kling
3143fea1eb LibJS: GlobalObject needs to mark the iterator prototypes
Otherwise they all disappear in the first garbage collection.
2020-09-08 15:37:39 +02:00
Andreas Kling
b32c0c8181 LibJS: Convert two suspicious Vector<Value> to MarkedValueList 2020-09-08 14:16:59 +02:00
Andreas Kling
d85eed585c LibJS: get_iterator_values() should pass Value to callback (not Value&)
Value& implies that the callback is expected/able to modify the value,
which is not the case.
2020-09-08 14:15:13 +02:00
AnotherTest
699e1fdc07 LibJS: Eliminate some (unnecessary) Vector copies 2020-09-08 13:43:03 +02:00
AnotherTest
8d9c5a8e70 LibJS: Make MarkedValueList inherit from Vector<Value>
This makes the nicer vector API available to MVL without extra wrapper
functions.
2020-09-08 13:43:03 +02:00
AnotherTest
9a00699983 LibJS: Format IndexedProperties.cpp 2020-09-08 13:43:03 +02:00
Linus Groh
b27d90db1f LibJS: Actually change size in generic storage's set_array_like_size()
Looks like an oversight to me - we were not actually setting a new value
for m_array_size, which would cause arrays created with generic storage
to report a .length of 0.
2020-09-01 21:35:59 +02:00
Linus Groh
ae9d64e544 LibJS: Let set_array_like_size() switch to generic storage if necessary
This is already considered in put()/insert()/append_all() but not
set_array_like_size(), which crashed the interpreter with an assertion
when creating an array with more than SPARSE_ARRAY_THRESHOLD (200)
initial elements as the simple storage was being resized beyond its
limit.

Fixes #3382.
2020-09-01 21:35:59 +02:00
Ben Wiederhake
d8e22fedc3 Libraries: Unbreak building with extra debug macros 2020-08-30 09:43:49 +02:00