Commit graph

1219 commits

Author SHA1 Message Date
sin-ack
c5073cb287 LibJS: Do not trim whitespace from property names when they're numbers
Fixes #7803.
2021-06-18 19:18:15 +01:00
Luke
8be7bdaac3 LibJS: Add %TypedArray%.prototype.some 2021-06-18 18:13:31 +01:00
Luke
68f11a272b LibJS: Add %TypedArray%.prototype.forEach 2021-06-18 18:13:31 +01:00
Luke
91af985718 LibJS: Add %TypedArray%.prototype.findIndex 2021-06-18 18:13:31 +01:00
Luke
61a8c19556 LibJS: Add %TypedArray%.prototype.find 2021-06-18 18:13:31 +01:00
Luke
65ca2d98af LibJS: Add %TypedArray%.prototype.every 2021-06-18 18:13:31 +01:00
Luke
02de3cbce3 LibJS: Add Number.parseInt
This is initialized to be the same function object as the initial value
of the parseInt function on the global object.
2021-06-18 10:29:33 +01:00
Idan Horowitz
cc5c1df64b LibJS: Add the TypedArray.of() method 2021-06-17 18:13:20 +01:00
Luke
9cbd90fdb6 LibJS: Add BigInt64Array and BigUint64Array
This fixes ~297 test262 test cases :^)
2021-06-17 02:20:03 +01:00
Luke
8d90e137a5 LibJS: Fix check for byteOffset instead of byteLength in byteLength test 2021-06-17 02:20:03 +01:00
Linus Groh
7489189645 LibJS/Tests: Use Object.prototype.toString() for values in test details
Using String() like we did before depends on objects having either
toString, valueOf, or  @@toPrimitive, which is not the case for objects
with no prototype.
2021-06-16 22:49:04 +01:00
Idan Horowitz
c619ad4fec LibJS: Allow no-op define property calls on non-configurable objects
This brings us slightly closer to the specification's 10.1.6.3
ValidateAndApplyPropertyDescriptor.
2021-06-16 12:57:48 +01:00
Idan Horowitz
2299be474b LibJS: Add the String.fromCodePoint() method 2021-06-16 10:29:10 +01:00
Idan Horowitz
e1b0719435 LibJS: Add all of the FinalizationRegistry.prototype methods
More specifically: cleanupSome, register & unregister.

FinalizationRegistery.prototype.cleanupSome is actually still a stage 2
proposal, but since test262 test cases already exist for it, i decided
to go for it :)
2021-06-15 23:59:21 +01:00
Idan Horowitz
de9fa6622a LibJS: Add the FinalizationRegistry built-in object
As well as the needed functionality in VM to enqueue and run cleanup
jobs for the FinalizationRegistry instances.
2021-06-15 23:59:21 +01:00
Ali Mohammad Pur
3194177dce LibJS: Correctly parse yield-from expressions
This commit implements parsing for `yield *expr`, and the multiple
ways something can or can't be parsed like that.
Also makes yield-from a TODO in the bytecode generator.
Behold, the glory of javascript syntax:
```js
// 'yield' = expression in generators.
function* foo() {
    yield
    *bar; // <- Syntax error here, expression can't start with *
}

// 'yield' = identifier anywhere else.
function foo() {
    yield
    *bar; // Perfectly fine, this is just `yield * bar`
}
```
2021-06-14 13:06:08 +01:00
Ali Mohammad Pur
d374295a26 LibJS: Parse generator functions in object literals
Also add some parser tests
2021-06-14 13:06:08 +01:00
Ali Mohammad Pur
2661a88108 LibJS: Add a test file for generator function parsing
Note that the yield-from expression tests are skipped for now since
they're not implemented yet.
2021-06-14 13:06:08 +01:00
davidot
ae8b55a80a LibJS: Add additional generic Array.prototype.slice tests 2021-06-14 09:57:06 +01:00
davidot
6c13cc67c6 LibJS: Implement Array.prototype.copyWithin generically 2021-06-14 09:57:06 +01:00
davidot
417f752306 LibJS: Implement Array.prototype.entries 2021-06-14 09:57:06 +01:00
davidot
910b803d8d LibJS: Implement Array.prototype.flatMap
Also made recursive_array_flat more compliant with the spec
So renamed it to flatten_into_array
2021-06-14 09:57:06 +01:00
davidot
4152409ac5 LibJS: Make Array.prototype.concat generic 2021-06-14 09:57:06 +01:00
davidot
2ef9df989f LibJS: Make Array.prototype.reverse generic 2021-06-14 09:57:06 +01:00
davidot
516f6240e8 LibJS: Add additional Array.prototype.reverse tests 2021-06-14 09:57:06 +01:00
davidot
d723c01af7 LibJS: Make Array.prototype.unshift generic 2021-06-14 09:57:06 +01:00
davidot
7c1e2adf8a LibJS: Make Array.prototype.shift generic 2021-06-14 09:57:06 +01:00
Idan Horowitz
690eb3bb8a LibJS: Add support for hex, octal & binary big integer literals 2021-06-14 01:45:04 +01:00
Idan Horowitz
e4e6e03364 LibJS: Add tests for DataView.prototype getters and setters 2021-06-14 01:45:04 +01:00
Idan Horowitz
e4d267d4fb LibJS: Add the DataView built-in object 2021-06-14 01:45:04 +01:00
Luke
d72aeb2e1a LibJS: Rewrite Array.prototype.slice to be spec compliant
This makes it generic in the process (which is required by jQuery)
This fixes 19 test262 test cases :^)
2021-06-13 16:21:34 +01:00
Linus Groh
33eea1f722 LibJS: Fix Object.prototype.valueOf() behavior
No idea why it was implemented like this, but a value_of() call on the
coerced object is not part of the spec. Also added some tests.
2021-06-13 01:06:36 +01:00
Idan Horowitz
322c8a3995 LibJS: Add the MapIterator built-in and the key/values/entries methods
While this implementation should be complete it is based on HashMap's
iterator, which currently follows bucket-order instead of the required
insertion order. This can be simply fixed by replacing the underlying
HashMap member in Map with an enhanced one that maintains a linked
list in insertion order.
2021-06-13 00:33:18 +01:00
Idan Horowitz
6c0d5163a1 LibJS: Add most of the Map.prototype methods
Specifically all aside from "keys", "values" and "entries" which
require an implementation of the MapIterator object.
2021-06-13 00:33:18 +01:00
Idan Horowitz
a96ac8bd56 LibJS: Add the Map built-in object 2021-06-13 00:33:18 +01:00
Idan Horowitz
3c83298a26 LibJS: Use undefined as the fallback value for iterable entry key/value
As defined in OdinaryGet in the specification.
2021-06-12 22:34:28 +01:00
Idan Horowitz
bd9e20ef79 LibJS: Add the Object.getOwnPropertySymbols method 2021-06-12 18:39:23 +01:00
Idan Horowitz
a2da3f97ef LibJS: Remove argument count checks in Object.* methods
These are inconsistent with the specification.
2021-06-12 18:39:23 +01:00
Idan Horowitz
b9d4dd6850 LibJS: Add the WeakRef.prototype.deref method
This is the only exposed method of the WeakRef built-in.
2021-06-12 18:39:23 +01:00
Idan Horowitz
7eba63a8a3 LibJS: Add the WeakRef built-in object 2021-06-12 18:39:23 +01:00
davidot
e044a3e428 LibJS: Add Array.prototype.keys() 2021-06-12 14:40:34 +01:00
Linus Groh
7e1bffdeb8 LibJS: Implement Object.assign() 2021-06-12 11:36:17 +01:00
Idan Horowitz
77c2db4183 LibJS: Add all of the WeakMap.prototype methods (delete, get, has, set) 2021-06-12 10:44:28 +01:00
Linus Groh
862ba64037 LibJS: Implement the Error Cause proposal
Currently stage 3. https://github.com/tc39/proposal-error-cause
2021-06-11 21:34:05 +01:00
Linus Groh
8d77a3297a LibJS: Improve Error/NativeError tests
Some of this stuff is already tested properly in the name and message
prototype tests, so let's focus on covering all error types here as well
instead.
2021-06-11 21:34:05 +01:00
Linus Groh
cbd7437d40 LibJS: Implement AggregateError 2021-06-11 18:49:50 +01:00
Luke
bc540de0af LibJS: Pass in actual_delete_count to removed array creation in splice
More specifically, Array.prototype.splice. Additionally adds a missing
exception check to the array creation and a link to the spec.

Fixes create-non-array-invalid-len.js in the splice tests in test262.
This test timed out instead of throwing an "Invalid array length"
exception.
2021-06-10 10:04:06 +01:00
Linus Groh
f932da095e LibJS: Use create_list_from_array_like() in Reflect.{apply,construct}() 2021-06-09 23:46:37 +01:00
Andreas Kling
4bc98fd39f LibJS: Only "var" declarations go in the global object at program level
"let" and "const" go in the lexical environment.

This fixes one part of #4001 (Lexically declared variables are mixed up
with global object properties)
2021-06-09 23:25:16 +02:00
Idan Horowitz
a00d154522 LibJS: Notify WeakSets when heap cells are sweeped
This is an implementation of the following optional optimization:
https://tc39.es/ecma262/#sec-weakref-execution
2021-06-09 21:52:25 +01:00
Idan Horowitz
fb63aeae4d LibJS: Add all of the WeakSet.prototype methods (add, delete, has) 2021-06-09 21:52:25 +01:00
Idan Horowitz
8b6beac5ce LibJS: Add the WeakSet built-in object 2021-06-09 21:52:25 +01:00
Idan Horowitz
2a3090d292 LibJS: Add the SetIterator built-in and Set.prototype.{values, entries}
While this implementation should be complete it is based on HashTable's
iterator, which currently follows bucket-order instead of the required
insertion order. This can be simply fixed by replacing the underlying
HashTable member in Set with an enhanced one that maintains a linked
list in insertion order.
2021-06-09 11:48:04 +01:00
Idan Horowitz
0b0f1eda05 LibJS: Add most of the Set.prototype methods
Specifically all aside from "values" and "entries" which require an
implementation of the SetIterator object.
2021-06-09 11:48:04 +01:00
Idan Horowitz
670be04c81 LibJS: Add the Set built-in object 2021-06-09 11:48:04 +01:00
Linus Groh
83be39c91a LibJS: Handle Proxy with Array target in IsArray() abstract operation
This was missing from Value::is_array(), which is equivalent to the
spec's IsArray() abstract operation - it treats a Proxy value with an
Array target object as being an Array.
It can throw, so needs both the global object and an exception check
now.
2021-06-08 23:53:13 +02:00
Linus Groh
9b35231453 LibJS: Implement Proxy.revocable() 2021-06-08 23:53:13 +02:00
Linus Groh
e39dd65cf0 LibJS: Remove Proxy() argument count check
Let's just treat missing arguments as undefined and throw with
'target/handler must be object' - this is more JavaScript-y.
2021-06-08 23:53:13 +02:00
Linus Groh
6c256bb400 LibJS: Add @@toStringTag to Reflect 2021-06-08 19:13:14 +01:00
Linus Groh
b377777208 LibJS: Add @@toStringTag to Promise.prototype 2021-06-08 19:13:14 +01:00
Idan Horowitz
064ed8279e LibJS: Support deleting local variables with operator delete
To make this cleaner i also moved the logic into Reference::delete_.
2021-06-08 15:31:46 +01:00
Linus Groh
4e555fae22 LibJS: Add missing cyclic prototype check to Object.setPrototypeOf() 2021-06-07 22:56:16 +01:00
Idan Horowitz
17afe015a5 LibJS: Add Date.prototype.setTime() 2021-06-06 19:14:11 +01:00
Idan Horowitz
a93b1c7ea0 LibJS: Add Date.prototype.setMonth() 2021-06-06 19:14:11 +01:00
Idan Horowitz
59034554a4 LibJS: Account for differences in month representations (0-11 vs 1-12)
Since DateTime stores months as 1 to 12, while JS accepts months as
0 to 11, we have to account for the difference (by subtracting or
adding 1) where appropriate.
2021-06-06 19:14:11 +01:00
Idan Horowitz
b893963651 LibJS: Add Date.prototype.setDate() 2021-06-06 19:14:11 +01:00
Linus Groh
b661363dfe LibJS: Implement String.prototype[@@toPrimitive]() 2021-06-06 19:34:43 +02:00
Linus Groh
8d7ec28924 LibJS: Remove String.prototype.length
A string's length property is supposed to be a regular non-writable,
non-enumerable, non-configurable property on the StringObject instead.
2021-06-06 19:34:43 +02:00
Linus Groh
d255e6892b LibJS: Update NumberPrototype's this_number_value() to take a Value
This is now about as close to the spec as it gets - instead of querying
the |this| value inside of the function, we now pass it in from the
outside.
Also get rid of the oddly specific error messages, they're nice but
pretty inconsistent with most others. Let's prefer consistency and
simplicity for now.

Other than that, no functionality change.
2021-06-06 19:34:43 +02:00
Linus Groh
3cfd9f51f7 LibJS: Replace some is_nullish() checks with require_object_coercible() 2021-06-06 19:34:43 +02:00
Linus Groh
adc3de4480 LibJS: Implement Number.prototype.valueOf() 2021-06-06 06:56:08 +01:00
Idan Horowitz
0bf597e99d LibJS: Uncomment and add parseInt tests
Added another test that checks radices > 16, as well as uncommented
several "FIXME" tests that are now working.
2021-06-06 01:34:22 +01:00
Idan Horowitz
2a8f4f097c LibJS: Throw TypeError on write to non-writable property in strict mode 2021-06-05 23:54:08 +01:00
Idan Horowitz
442ef63008 LibJS: Add the global escape() & unescape() methods 2021-06-05 18:55:08 +01:00
Ryan Chandler
c66b281856 LibJS: Fix functions binding this to global object in strict mode
This fixes an issue where this would be bound to the global object
by default when operating in strict mode.

According to the specification, the expected value for |this| when
no binding is provided is undefined.
2021-06-04 13:00:37 +01:00
Ali Mohammad Pur
09cf1040ef LibJS/Tests: Catch exceptions in describe() itself
Otherwise exceptions thrown in that state would simply terminate the
test.
2021-06-04 16:07:42 +04:30
Idan Horowitz
67a5e9f018 LibJS: Add left shift & right shift operator support for BigIntegers
Based on https://tc39.es/ecma262/#sec-numeric-types-bigint-leftShift
(This commit also includes the matching tests)
2021-05-31 19:50:29 +01:00
Ali Mohammad Pur
827d94939b LibJS: Add tests for destructuring assignments and function parameters 2021-05-29 23:02:23 +04:30
Luke
4d34802f74 LibJS: Expose TypedArray.prototype.byteOffset 2021-05-21 22:52:35 +01:00
Luke
58afd71ad2 LibJS: Expose TypedArray.prototype.byteLength 2021-05-21 22:52:35 +01:00
Luke
8004a2dc77 LibJS: Expose TypedArray.prototype.buffer 2021-05-21 22:52:35 +01:00
Luke
6f1688279a LibJS: Expose BYTES_PER_ELEMENT on each TypedArray 2021-05-21 22:52:35 +01:00
Andreas Kling
3ee092cd0c LibJS: Implement Object.hasOwn() :^)
This is currently a TC39 Stage 2 proposal, but let's go for it!

https://github.com/tc39/proposal-accessible-object-hasownproperty

I wrote the C++, @linusg found bugs and wrote the test.
2021-05-18 11:18:19 +02:00
Linus Groh
a92dc4e30d LibJS: Ensure function declarations don't leak outside function scopes
When using VM::set_variable() to put the created ScriptFunction onto a
ScopeObject, we would previously unexpectedly reach the global object as
set_variable() checks each traversed scope for an existing Variable with
the given name - which would cause a leak of the inner function past the
outer function (we even had a test expecting that behaviour!). Now we
first declare functions (as DeclarationKind::Var) before setting them.
This will need some more work to make hoisting across non-lexical scopes
work, but it fixes this specific issue for now.

Fixes #6766.
2021-05-13 23:59:00 +01:00
Linus Groh
b221cad659 LibJS/Tests: Add details for toBeTrue() / toBeFalse() expectation error 2021-05-13 23:59:00 +01:00
Linus Groh
f28491dbe7 LibJS/Tests: Add details for toThrowWithMessage did-not-throw case 2021-05-13 23:59:00 +01:00
Linus Groh
5b18bce23c LibJS/Tests: Add prefix to toThrowWithMessage expectation error details
This way we get some more information about where things went wrong.
2021-05-13 23:59:00 +01:00
Linus Groh
0a329d2d70 LibJS: Make super() in catch block work
The TryStatement handler execution creates a new LexicalEnvironment
without a current function set, which we were not accounting for when
trying to get the super constructor while executing a SuperExpression.
This makes it work but isn't pretty - this needs some refactoring to be
close to the spec for that to happen.

Fixes #7045.
2021-05-11 23:31:30 +01:00
Linus Groh
d85b9fd5a0 LibJS: Bring back runtime validation of RegExp flags
This is a partial revert of commit 60064e2, which removed the validation
of RegExp flags during runtime and expected the parser to do that
exclusively - however this was not taking into account the RegExp()
constructor, which was subsequently crashing on invalid flags.

Also adds test for these constructor error cases, which were obviously
missing before.

Fixes #7042.
2021-05-11 22:47:14 +01:00
Linus Groh
431782bcd6 LibJS/Tests: Add details for toThrowWithMessage() expectation error 2021-05-11 22:41:35 +01:00
Luke
c5c9494f48 LibJS: Use u64 instead of u32 in NumberPrototype::to_string
Update to #7033
Partial fix for #7034 (just ups the range to about 2 ** 54 before
losing precision)
2021-05-11 18:29:55 +01:00
Luke
2ff03ecfa8 LibJS: Make number parts unsigned in NumberPrototype::to_string
Fixes #3931
2021-05-11 17:29:37 +01:00
Linus Groh
60064e2049 LibJS: Make invalid RegExp flags a SyntaxError at parse time
This patch changes the validation of RegExp flags (checking for
invalid and duplicate values) from a SyntaxError at runtime to a
SyntaxError at parse time - it's not something that's supposed to be
catchable.
As a nice side effect, this simplifies the RegExpObject constructor a
bit, as it can no longer throw an exception and doesn't have to validate
the flags itself.
2021-05-10 12:01:38 +01:00
Linus Groh
d1a72dc6eb LibJS/Tests: Rename function parameter from 'arguments' to 'arguments_'
The former has a special meaning and should be avoided where possible.
2021-05-10 11:54:01 +01:00
Linus Groh
346560d7c8 LibJS/Tests: Use hasOwnProperty() for duplicate test check
The current way of doing this would also traverse the prototype chain,
and therefore yield false positive results for keys like "toString".
2021-05-05 15:58:53 +01:00
Andreas Kling
3d4afe7614 Everywhere: "indexes" => "indices"
I've wasted a silly amount of time in the past fretting over which
of these words to use. Let's just choose one and use it everywhere. :^)
2021-04-29 22:23:52 +02:00
Linus Groh
7b1ba4bd5c LibJS: Fallback to undefined if last value in eval() is empty
For something like eval(""), the VM's 'last value' is an empty value,
which we must not leak.

Fixes #6643.
2021-04-25 22:52:19 +02:00
Linus Groh
0053816e9d LibJS: Correctly handle mixing +0 and -0 in Math.{min,max}()
The native C++ < and > operators won't handle this correctly, so the
result was different depending on the order of arguments. This is now
fixed by explicitly checking for positive and negative zero values.

Fixes #6589.
2021-04-23 20:51:48 +02:00
Linus Groh
883e8683b2 LibJS/Tests: Remove fileName and lineNumber args from ExpectationError
This is nono-standard, not supported by our Error implementation and not
even used anywhere, so let's just remove it.
2021-04-23 20:30:52 +02:00
Linus Groh
d400be05ec LibJS/Tests: Improve expectation error details 2021-04-23 20:30:52 +02:00
Ali Mohammad Pur
bf9c04a3da LibRegex: Implement multiline stateful matches 2021-04-23 10:05:04 +02:00
Linus Groh
7af1d2c170 LibJS: Make Object.getOwnPropertyDescriptor() work with string indexed property
E.g. for "0" we have to contruct a PropertyName with Type::Number so it
looks in the indexed properties as expected.
2021-04-20 18:53:07 +02:00
Linus Groh
614bad86bc LibJS: Fix Object.getOwnPropertyDescriptor() attributes for numeric property
We were getting the attributes of the existing value and then
immediately assigned the default attributes instead.
2021-04-20 18:42:10 +02:00
Linus Groh
ac3e7ef791 LibJS: Fix crash in Object.{freeze,seal}() with indexed properties
This was failing to take two things into account:

- When constructing a PropertyName from a value, it won't automatically
  convert to Type::Number for something like string "0", even though
  that's how things work internally, since indexed properties are stored
  separately. This will be improved in a future patch, it's a footgun
  and should happen automatically.
- Those can't be looked up on the shape, we have to go through the
  indexed properties instead.

Additionally it now operates on the shape or indexed properties directly
as define_property() was overly strict and would throw if a property was
already non-configurable.

Fixes #6469.
2021-04-20 09:38:22 +02:00
Idan Horowitz
6cd318d784 LibJS: Convert matched regex result to string in Symbol.replace
This would crash on an undefined match (no match), since the matched
result was assumed to be a string (such as on discord.com). The spec
suggests converting it to a string as well:
https://tc39.es/ecma262/#sec-regexp.prototype-@@replace (14#c)
2021-04-17 16:10:45 +02:00
Idan Horowitz
586f10b6e1 LibJS: Accept symbol property in the in operator
This is used by discord.com and allowed by the specification:
https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation
2021-04-17 00:59:36 +02:00
Idan Horowitz
e3c634fdd0 LibJS: Implement initializing a TypedArray from an iterable object
Based on these specifications (which required IterableToList as well):
https://tc39.es/ecma262/#sec-typedarray
https://tc39.es/ecma262/#sec-initializetypedarrayfromlist
2021-04-17 00:24:09 +02:00
Idan Horowitz
06a2173586 LibJS: Implement initializing a TypedArray from an array-like object
Used by twitch.tv and based on the following specification:
https://tc39.es/ecma262/#sec-initializetypedarrayfromarraylike
2021-04-17 00:24:09 +02:00
Idan Horowitz
223472c57f LibJS: Dont try to serialize symbol-keyed properties
As per the specification: "All Symbol-keyed properties will be
completely ignored, even when using the replacer function."
2021-04-16 19:22:29 +02:00
Idan Horowitz
fff7aceb9d LibJS: Accept symbol property in ObjectPrototype::hasOwnProperty
This is used by discord.com and allowed by the specification
(https://tc39.es/ecma262/#sec-topropertykey)
2021-04-16 19:22:29 +02:00
Timothy Flynn
b6093ae2e3 LibJS: Implement String.prototype.substr according to the spec
Fixes #6325

The JavaScript on the HTML Spec site that caused the crash is:
    window.location.hash.substr(1)

Of course, window.location.hash can be the empty string. The spec allows
for calling substr(1) on an empty string, but our partial implementation
wasn't handling it properly.
2021-04-15 08:38:19 +02:00
Idan Horowitz
ba77b40808 LibJS: Implement the encode/decodeURI(Component) family of functions
These are generally useful and in particular needed for twitter.com
2021-04-14 13:30:10 +02:00
Linus Groh
ea60b344eb LibJS: Add name and message properties to NativeError prototypes
Otherwise these will get their name/default message from the Error
prototype, and as a result would always just say "Error" in error
messages, not the specific type.
Something I missed in da177c6, now with tests. :^)
2021-04-14 10:11:04 +02:00
Linus Groh
7cbede4342 LibJS: Fix return value of TryStatement with finalizer
Previously we would always return the result of executing the finalizer,
however the spec dictates the finalizer result must only be returned for
a non-normal completion.
I added some more comments along the way, which should make it more
clear what's going on - the unwinding and exception flow isn't super
straightforward here.
2021-04-13 15:40:52 +02:00
tuqqu
c8ad1df143 LibJS: Array.from mapFn fixes + thisArg support
* Callback mapFn now properly supports second argument (index)
* Support of thisArg to be passed as "this" in vm.call
* Tests for all cases
2021-04-13 15:16:16 +02:00
Linus Groh
da177c6517 LibJS: Make Errors fully spec compliant
The previous handling of the name and message properties specifically
was breaking websites that created their own error types and relied on
the error prototype working correctly - not assuming an JS::Error this
object, that is.

The way it works now, and it is supposed to work, is:

- Error.prototype.name and Error.prototype.message just have initial
  string values and are no longer getters/setters
- When constructing an error with a message, we create a regular
  property on the newly created object, so a lookup of the message
  property will either get it from the object directly or go though the
  prototype chain
- Internal m_name/m_message properties are no longer needed and removed

This makes printing errors slightly more complicated, as we can no
longer rely on the (safe) internal properties, and cannot trust a
property lookup either - get_without_side_effects() is used to solve
this, it's not perfect but something we can revisit later.

I did some refactoring along the way, there was some really old stuff in
there - accessing vm.call_frame().arguments[0] is not something we (have
to) do anymore :^)

Fixes #6245.
2021-04-12 09:38:57 +02:00
AnotherTest
5a14f7ea2f LibRegex: Generate a 'Compare' op for empty character classes
Otherwise it would match zero-length strings.
Fixes #6256.
2021-04-12 08:54:58 +02:00
tuqqu
5438879277 LibJS: Removed a fixme in a test of BigInt.prototype.valueOf 2021-04-11 20:51:58 +02:00
Linus Groh
433a23cfde LibJS: Fix array hole and string object indexing prototype indirection
This fixes two cases of indexed access (array holes, out-of-bounds
string object access) where we would not follow the prototype chain and
incorrectly return undefined:

    // Should be "a", returned undefined
    Object.setPrototypeOf([,], ["a"])[0]

    // Should be "a", returned undefined
    Object.setPrototypeOf(new String(""), new String("a"))[0]

The actual fix is simple, instead of returning early if the requested
index is past the string's length or within the indexed properties size
but has no value, we just continue the prototype chain traversal and get
correct behaviour from that.
2021-04-11 18:15:47 +02:00
Linus Groh
2172e51246 LibJS: Implicitly break for..in loop if the RHS result is nullish
This implements the missing step 6a of 14.7.5.6 ForIn/OfHeadEvaluation:

    a. If exprValue is undefined or null, then
        i. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.

In other words, this should just do nothing instead of throwing during
the undefined to object coercion:

    for (const x in undefined);
2021-04-10 21:00:04 +02:00
Linus Groh
9cd010167a LibJS: Implement Object.create() 2021-04-10 21:00:04 +02:00
Linus Groh
da8a35a79e LibJS: Implement Object.defineProperties() 2021-04-10 21:00:04 +02:00
AnotherTest
1b071455b1 LibRegex: Treat brace quantifiers with invalid contents as literals
Fixes #6208.
2021-04-10 09:16:03 +02:00
AnotherTest
e9279d1790 LibRegex: Allow a '?' suffix for brace quantifiers
This fixes another compat point in #6042.
2021-04-10 09:16:03 +02:00
Amjad Alsharafi
b758654840 LibJS: Added tests for constructing TypeArray from another 2021-04-09 09:05:19 +02:00
Linus Groh
f3264b0dbd LibJS: Implement Object.isFrozen() and Object.isSealed() 2021-04-07 09:05:01 +02:00
Linus Groh
9af07c7803 LibJS: Implement Object.freeze() and Object.seal() 2021-04-07 09:05:01 +02:00
tuqqu
7bd0384fa6 LibJS: Support mapFn argument of Array.from 2021-04-06 22:25:05 +02:00
Linus Groh
abc7b31079 LibJS: Let Object::get_own_properties() return both strings and symbols
The new default return_type argument is GetOwnPropertyReturnType::All,
which returns properties with both string and symbol keys (which is also
the default for [[OwnPropertyKeys]]). This means that in some cases we
need to iterate the ordered property table twice, as we don't store
string and symbol properties separately but symbols must - there's
certainly room for (performance) improvements here. On the other hand
this makes Reflect.ownKeys() return symbol properties now :^)
2021-04-05 19:30:30 +02:00
AnotherTest
ade97d4094 LibRegex: Make sure there are as many group matches as actual matches
Fixes #6131.
2021-04-05 09:02:06 +02:00
AnotherTest
1bdc1cf77e LibRegex: Consider named capture groups as normal capture groups too 2021-04-05 09:02:06 +02:00
AnotherTest
76f63c2980 LibRegex: Allocate entries for all capture groups in RegexResult
Not just the seen ones.
Fixes #6108.
2021-04-04 16:04:06 +02:00
Linus Groh
f1fde01025 LibJS: Fix returning from try statement
Not sure if this regressed at some point or just never worked, it
definitely wasn't tested at all. We would always return undefined when
returning from a try statement block, handler, or finalizer.
2021-04-03 16:34:34 +02:00
Linus Groh
e46fa3ac8b LibJS: Keep RegExp.exec() results in correct order
By using regex::AllFlags::SkipTrimEmptyMatches we get a null string for
unmatched capture groups, which we then turn into an undefined entry in
the result array instead of putting all matches first and appending
undefined for the remaining number of capture groups - e.g. for

    /foo(ba((r)|(z)))/.exec("foobaz")

we now return

    ["foobaz", "baz", "z", undefined, "z"]

and not [

    ["foobaz", "baz", "z", "z", undefined]

Fixes part of #6042.

Also happens to fix selecting an element by ID using jQuery's $("#foo").
2021-04-03 16:34:34 +02:00
Jamie Mansfield
01187e58f2 LibJS: ArrayBuffer.prototype.slice
Implements the aforementioned native Javascript function, following the
specification's [1] implementation.

[1] https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice
2021-04-03 16:24:44 +02:00
Linus Groh
e875513ff7 LibJS: Use empty value for Reference unresolvable state, not undefined
This fixes an issue where `undefined.foo = "bar"` would throw a
ReferenceError instead of a TypeError as undefined was also used for
truly unresolvable references (e.g. `foo() = "bar"`). I also made the
various error messages here a bit nicer, just "primitive value" is not
very helpful.
2021-04-02 22:24:30 +02:00
Timothy Flynn
77a601d52e LibJS: Implement most of String.prototype.replace 2021-04-02 10:48:40 +02:00
Linus Groh
f418115f1b LibJS: Add initial support for Promises
Almost a year after first working on this, it's finally done: an
implementation of Promises for LibJS! :^)

The core functionality is working and closely following the spec [1].
I mostly took the pseudo code and transformed it into C++ - if you read
and understand it, you will know how the spec implements Promises; and
if you read the spec first, the code will look very familiar.

Implemented functions are:

- Promise() constructor
- Promise.prototype.then()
- Promise.prototype.catch()
- Promise.prototype.finally()
- Promise.resolve()
- Promise.reject()

For the tests I added a new function to test-js's global object,
runQueuedPromiseJobs(), which calls vm.run_queued_promise_jobs().
By design, queued jobs normally only run after the script was fully
executed, making it improssible to test handlers in individual test()
calls by default [2].

Subsequent commits include integrations into LibWeb and js(1) -
pretty-printing, running queued promise jobs when necessary.

This has an unusual amount of dbgln() statements, all hidden behind the
PROMISE_DEBUG flag - I'm leaving them in for now as they've been very
useful while debugging this, things can get quite complex with so many
asynchronously executed functions.

I've not extensively explored use of these APIs for promise-based
functionality in LibWeb (fetch(), Notification.requestPermission()
etc.), but we'll get there in due time.

[1]: https://tc39.es/ecma262/#sec-promise-objects
[2]: https://tc39.es/ecma262/#sec-jobs-and-job-queues
2021-04-02 10:47:40 +02:00
AnotherTest
6bbb26fdaf LibRegex: Allow references to capture groups that aren't parsed yet
This only applies to the ECMA262 parser.
This behaviour is an ECMA262-specific quirk, such references always
generate zero-length matches (even on subsequent passes).
Also adds a test in LibJS's test suite.

Fixes #6039.
2021-04-01 21:55:47 +02:00
Linus Groh
1ea8d73628 LibJS: Provide 'details' key in results object for duplicate test
The test-js program expects this to exist for 'result: "fail"' results
and would crash if any duplicated test(message) occurs, as we didn't
provide 'details' in that case.
2021-03-31 23:59:21 +02:00
Andreas Kling
077406dc36 LibJS: Fix two issues with array (length > INT32_MAX)
1. Allow Value(size_t) and use it for array length properties.

If an array length can't fit in an Int32 value, we shouldn't go out of
or way to force it into one. Instead, for values above INT32_MAX,
we simply store them as Double values.

2. Switch to generic indexed property storage for large arrays.

Previously we would always allocate array storage eagerly when the
length property was set. This meant that "a.length = 0x80000000" would
trivially DOS the engine on 32-bit since we don't have that much VM.

We now switch to generic storage when changing the length moves us over
the 4M entry mark.

Fixes #5986.
2021-03-30 13:52:56 +02:00
Petróczi Zoltán
ca49f96b78 LibJS Date: Added "Invalid Date".
Setting an invalid value on a Date object now makes it invalid.
Setting it again but with correct values makes it valid again.
2021-03-22 20:58:22 +01:00
Andreas Kling
0255c8d976 Only apply auto-naming of function expressions based on syntax
The auto naming of function expressions is a purely syntactic
decision, so shouldn't be decided based on the dynamic type of
an assignment. This moves the decision making into the parser.

One icky hack is that we add a field to FunctionExpression to
indicate whether we can autoname. The real solution is to actually
generate a CompoundExpression node so that the parser can make
the correct decision, however this would have a potentially
significant run time cost.

This does not correct the behaviour for class expressions.

Patch from Anonymous.
2021-03-22 12:44:07 +01:00
Andreas Kling
dc8817638e LibJS: Only update anonymous function names when necessary
Previously we would generate function names for anonymous functions
on every AssignmentExpression, even if we weren't assigning a function.

We were also setting names of anonymous functions in arrays, which is
apparently a SpiderMonkey specific behavior not supported by V8, JSC
or required by ECMA262. This patch removes that behavior.

This is a huge performance improvement on the CanvasCycle demo! :^)
2021-03-21 21:39:39 +01:00
Andreas Kling
d0664ce6c9 LibJS: Don't punish large arrays with generic indexed property storage
This patch rethinks the way indexed property storage works:

Instead of having a cut-off point at 200 elements where we always move
to generic property storage, we now allow arrays to stay in simple mode
as long as we don't create a gap/hole larger than 200 elements.

We also simplify generic storage to only have a hash map (for now)
instead of juggling both a vector and a hash map. This is mostly fine
since the vast majority of arrays get to stay simple now.

This is a huge speedup on anything that uses basic JS arrays with more
than 200 elements in them. :^)
2021-03-21 11:37:10 +01:00
Linus Groh
ae95ed5ddd LibJS: Append first sparse element to packed elements in take_first()
Otherwise we continuously lose the first sparse element (at index
SPARSE_ARRAY_THRESHOLD) without noticing, as we overwrite all indices
with the value at index+1.

Fixes #5884.
2021-03-21 09:35:47 +01:00
tuqqu
43f0c92bcd LibJS: Add Date methods: setHours, setMinutes, setSeconds, setMilliseconds 2021-03-19 23:08:21 +01:00
Andreas Kling
3217e6237c LibJS: Add a basic test for arguments.callee 2021-03-17 21:54:52 +01:00
Linus Groh
b985fa989e LibJS: Actually use eval() in non-string arg eval test 2021-03-17 21:28:14 +01:00
Andreas Kling
60e630d5a0 LibJS: eval(x) should return x without evaluation if x is not a string 2021-03-17 20:57:29 +01:00
Linus Groh
fa6bce5087 LibJS: Throw RangeError on BigInt exponentiation with negative exponent
https://tc39.es/ecma262/#sec-numeric-types-bigint-exponentiate
2021-03-16 21:54:51 +01:00
Linus Groh
11138f5c1f LibJS: Throw RangeError on BigInt division/modulo by zero
https://tc39.es/ecma262/#sec-numeric-types-bigint-divide
https://tc39.es/ecma262/#sec-numeric-types-bigint-remainder
2021-03-16 21:54:51 +01:00
Linus Groh
c499239137 LibJS: Implement non-value-producing statements properly
For various statements the spec states:

    Return NormalCompletion(empty).

In those cases we have been returning undefined so far, which is
incorrect.

In other cases it states:

    Return Completion(UpdateEmpty(stmtCompletion, undefined)).

Which essentially means a statement is evaluated and its completion
value returned if non-empty, and undefined otherwise.

While not actually noticeable in normal scripts as the VM's "last value"
can't be accessed from JS code directly (with the exception of eval(),
see below), it provided an inconsistent experience in the REPL:

    > if (true) 42;
    42
    > if (true) { 42; }
    undefined

This also fixes the case where eval() would return undefined if the last
executed statement is not a value-producing one:

    eval("1;;;;;")
    eval("1;{}")
    eval("1;var a;")

As a consequence of the changes outlined above, these now all correctly
return 1.

See https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation,
"NOTE 2".

Fixes #3609.
2021-03-16 10:08:07 +01:00
Linus Groh
d6239b691f LibJS: Throw SyntaxError in eval() when parser has error(s) 2021-03-15 22:43:27 +01:00
Andreas Kling
45e6b5e601 LibJS: Make eval() return the last value from the executed statement
This is kinda awkward but since the statement we're executing is
actually a JS::Program, we have to get the result via VM::last_value().
2021-03-15 21:43:40 +01:00
Linus Groh
202f855055 LibJS: Change non-ScriptFunction source string to "[native code]"
https://tc39.es/ecma262/#sec-function.prototype.tostring - this is how
the spec wants us to do it. :^)

Also change the function name behaviour to only provide a name for
NativeFunctions, which matches other engines - presumably to not expose
Proxy objects, and to prevent "function bound foo() { [native code] }".
2021-03-14 19:22:16 +01:00
Andreas Kling
1db943e146 LibJS: Implement (mostly) String.prototype.match
JavaScript has a couple of different ways to run a regular expression
on a string. This adds support for one more. :^)
2021-03-14 11:04:50 +01:00
Linus Groh
2d8362cceb LibJS: Implement 'Relative Indexing Method' proposal (.at())
Still stage 3, but already implemented in major engines and unlikely to
change - there isn't much to change here anyway. :^)

See:

- https://github.com/tc39/proposal-relative-indexing-method
- https://tc39.es/proposal-relative-indexing-method/
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
2021-03-12 19:01:08 +01:00
Linus Groh
585123127e LibJS: Support @@toPrimitive in ToPrimitive abstract operation
Fixes #3961.
2021-03-03 11:04:06 +01:00
speles
be9df404fd LibJS: Re-enable "reassignment to const" test
It passes now :^)
2021-02-26 16:59:37 +01:00
Linus Groh
a72276407b LibJS: Make ArrayPrototype an Array object
https://tc39.es/ecma262/#sec-properties-of-the-array-prototype-object

The Array prototype object: [...] is an Array exotic object and has the
internal methods specified for such objects.

NOTE: The Array prototype object is specified to be an Array exotic
object to ensure compatibility with ECMAScript code that was created
prior to the ECMAScript 2015 specification.
2021-02-24 10:22:17 +01:00
Breno Silva
cfb0f3309d LibJS: Implement tests for Array.prototype.flat 2021-02-18 00:22:45 +01:00
Linus Groh
4e2a961a3d LibJS: Add BigInt equality tests for some large numbers 2021-02-14 10:51:00 +01:00
Linus Groh
83c29bd8d7 LibJS: Don't assume match for each capture group in RegExp.prototype.exec()
This was not implementing the following part of the spec correctly:

    27. For each integer i such that i ≥ 1 and i ≤ n, do
        a. Let captureI be ith element of r's captures List.
        b. If captureI is undefined, let capturedValue be undefined.

Expecting a capture group match to exist for each of the RegExp's
capture groups would assert in Vector's operator[] if that's not the
case, for example:

    /(foo)(bar)?/.exec("foo")

Append undefined instead.

Fixes #5256.
2021-02-08 18:01:23 +01:00
Andreas Kling
16a0e7a66d LibJS: Improve correctness of rounding and bitwise operations
Patch from Anonymous
2021-02-05 09:38:45 +01:00
Andreas Kling
f6c6047e49 LibJS: Add overflow checks when creating TypedArray from ArrayBuffer
Thanks to Iliad for finding this! :^)
2021-01-27 07:57:07 +01:00
Andreas Kling
7a71d4b887 LibJS: Add some assertions and tests for TypedArray limitations 2021-01-24 19:08:44 +01:00
Linus Groh
766f30f593 LibJS: Check if class extends value has a valid prototype
If we have a function as class extends value, we still cannot assume
that it has a prototype property and that property has a function or
null as its value - blindly calling to_object() on it may fail.

Fixes #5075.
2021-01-24 00:09:18 +01:00
Andreas Kling
13d7c09125 Libraries: Move to Userland/Libraries/ 2021-01-12 12:17:46 +01:00