Commit graph

1100 commits

Author SHA1 Message Date
Linus Groh
2dbea60fe2 LibJS: Multiple 'default' clauses in switch statement are a syntax error 2020-10-19 11:30:14 +02:00
Linus Groh
f8886ef5ba LibJS: Handle continue in switch statement unwinding 2020-10-18 19:08:52 +02:00
Linus Groh
8f54edb7a0 LibJS: Handle return value in switch statement unwinding
Fixes #3790.
2020-10-18 19:08:52 +02:00
Stephan Unverwerth
2c888b3c6e LibJS: Fix parsing of invalid numeric literals
i.e. "1e" "0x" "0b" "0o" used to be parsed as valid literals.
They now produce invalid tokens. Fixes #3716
2020-10-18 15:38:57 +02:00
Andreas Kling
77c1957961 LibJS: Use allocate_without_global_object for allocating Shapes 2020-10-17 23:47:07 +02:00
Andreas Kling
d8269c343c LibJS: Avoid creating temporary Strings to look up tokens while lexing
It would be cool to solve this in a general way so that looking up
a string literal or StringView in a HashMap with String keys avoids
creating a temp string.

For now, this patch simply addresses the issue in JS::Lexer.
This is a 2-3% speed-up on test-js.
2020-10-17 23:44:41 +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
Andreas Kling
9f6c5f68b6 LibJS: Tidy up CallExpression::execute() a little bit 2020-10-13 19:13:37 +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
e8da5f99b1 LibJS: break or continue with nonexistent label is a syntax error 2020-10-08 23:27:16 +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
Matthew Olsson
d980073122 LibJS: Handle unwinding in while and do-while statements
For some reason, this was never added. So something like "while (true)
{ return }" would loop infinitely.
2020-10-08 23:23:55 +02:00
Matthew Olsson
e49ea1b520 LibJS: Disallow 'continue' & 'break' outside of their respective scopes
'continue' is no longer allowed outside of a loop, and an unlabeled
'break' is not longer allowed outside of a loop or switch statement.
Labeled 'break' statements are still allowed everywhere, even if the
label does not exist.
2020-10-08 10:20:49 +02:00
Matthew Olsson
9a82c22a85 LibJS: Disallow 'return' outside of a function 2020-10-08 10:03:21 +02:00
Linus Groh
5feb7e8d28 LibJS: Use PropertyName::from_value() in MemberExpression::computed_property_name()
No need for duplicating this logic.
2020-10-08 10:02:47 +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
c541310e19 LibJS: Use IntrusiveList for Allocator's block lists
This way we don't need to deal with shifting vector storage, and most
operations are upgraded from O(n) to O(1) :^)
2020-10-07 14:07:31 +02:00
Andreas Kling
d1592643a6 LibJS: Make sure the HeapBlock cell storage is alignas(Cell) 2020-10-07 13:09:59 +02:00
Andreas Kling
48f13b7c3f LibJS: Split Heap into per-cell-size allocators
Instead of keeping all the HeapBlocks in one big list, we now split it
into two levels:

- Heap has a set of Allocators, each with a specific cell size.
- Allocators have two lists of blocks, "full" and "usable".

Allocating a new cell no longer has to scan the entire set of blocks,
but instead just needs to find the right allocator and then pop a cell
from its freelist. If all the blocks in the allocator are full, a new
block will be created.

Blocks are moved from the "full" to "usable" list after sweeping has
determined that they are not completely empty and not completely full.

There are certainly many ways we can improve on this. This patch is
mostly about getting the new allocator architecture in place. :^)
2020-10-06 18:50: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
Linus Groh
aa71dae03c LibJS: Implement logical assignment operators (&&=, ||=, ??=)
TC39 proposal, stage 4 as of 2020-07.
https://tc39.es/proposal-logical-assignment/
2020-10-05 17:57:26 +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
Linus Groh
2d4cd5b49b LibJS: Evaluate AssignmentExpression LHS before RHS according to the spec
Fixes #3689.
2020-10-05 14:34:37 +02:00
Linus Groh
f4d0babd5d LibJS: Make assignment to CallExpression a syntax error in strict mode 2020-10-05 09:25:04 +02:00
Linus Groh
283ee678f7 LibJS: Validate all assignment expressions, not just "="
The check for invalid lhs and assignment to eval/arguments in strict
mode should happen for all kinds of assignment expressions, not just
AssignmentOp::Assignment.
2020-10-05 09:25:04 +02:00
Linus Groh
e80217a746 LibJS: Unify syntax highlighting
So far we have three different syntax highlighters for LibJS:

- js's Line::Editor stylization
- JS::MarkupGenerator
- GUI::JSSyntaxHighlighter

This not only caused repetition of most token types in each highlighter
but also a lot of inconsistency regarding the styling of certain tokens:

- JSSyntaxHighlighter was considering TokenType::Period to be an
  operator whereas MarkupGenerator categorized it as punctuation.
- MarkupGenerator was considering TokenType::{Break,Case,Continue,
  Default,Switch,With} control keywords whereas JSSyntaxHighlighter just
  disregarded them
- MarkupGenerator considered some future reserved keywords invalid and
  others not. JSSyntaxHighlighter and js disregarded most

Adding a new token type meant adding it to ENUMERATE_JS_TOKENS as well
as each individual highlighter's switch/case construct.

I added a TokenCategory enum, and each TokenType is now associated to a
certain category, which the syntax highlighters then can use for styling
rather than operating on the token type directly. This also makes
changing a token's category everywhere easier, should we need to do that
(e.g. I decided to make TokenType::{Period,QuestionMarkPeriod}
TokenCategory::Operator for now, but we might want to change them to
Punctuation.
2020-10-04 23:41:31 +02:00
Andreas Kling
fdb0ac7c1e LibJS: Remove some unused Interpreter member functions 2020-10-04 23:10:07 +02:00
Andreas Kling
94b95a4924 LibJS: Remove Interpreter::call()
Just use VM::call() directly everywhere.
2020-10-04 23:08:49 +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
2852ce4954 LibJS: Always inline HeapBlock::allocate()
This thing is so simple and sits on the hot path so just inline it.
2020-10-04 19:25:49 +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
bc701658f8 LibJS: Use String::formatted() for parser error messages 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
Linus Groh
a27668cbae LibJS: Use String::formatted() in MarkupGenerator 2020-10-04 19:22:02 +02:00
Andreas Kling
4237089a21 LibJS: Remove unused Heap::interpreter() 2020-10-04 17:03:33 +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
Nico Weber
ef1b21004f Everywhere: Fix typos
Mostly in comments, but sprintf() now prints "August" instead of
"Auguest" so that's something.
2020-10-02 16:03:17 +02:00
Andreas Kling
bd5abbc454 LibJS: Fix fatal mistake in HeapBlock::cell_from_possible_pointer()
When scanning for potential heap pointers during conservative GC,
we look for any value that is an address somewhere inside a heap cell.

However, we were failing to account for the slack at the end of a
block (which occurs whenever the block storage size isn't an exact
multiple of the cell size.) Pointers inside the trailing slack were
misidentified as pointers into "last_cell+1".

Instead of skipping over them, we would treat this garbage data as a
live cell and try to mark it. I believe this is the test-js crash that
has been terrorizing Travis for a while. :^)
2020-10-01 21:07:12 +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
Andreas Kling
111d63c676 LibJS: Remove two unused Interpreter member functions 2020-09-26 21:23:14 +02:00
Linus Groh
7d83665635 LibJS+LibGUI+js: Handle UnterminatedRegexLiteral in syntax highlighters 2020-09-25 23:58:42 +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
c8baf29d82 LibJS: Assert if garbage collection is restarted while ongoing
We can't GC while we're already in GC. Assert if this happens.
2020-09-21 14:35:19 +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
668e73df8a LibJS: Make Interpreter::in_strict_mode() work outside of scope
This one is a little weird. I don't know why it's okay for this
function to assume that there is a current scope on the scope stack
when it can be called during global object initialization etc.

For now, just make it say "we are in strict mode" when there is no
currently active scope.
2020-09-20 19:16:34 +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
AnotherTest
21f513fe0f LibJS: Do not revisit already visited values in update_function_name()
Fixes #3471, adds a test.
2020-09-19 00:33:56 +02:00
Linus Groh
a9f5b0339d LibJS: Simplify toEval() implementation 2020-09-18 20:49:35 +02:00
Linus Groh
5fd87ccd16 LibJS: Add FIXMEs for parsing increment operators with function LHS/RHS
The parser considers it a syntax error at the moment, other engines
throw a ReferenceError during runtime for ++foo(), --foo(), foo()++ and
foo()--, so I assume the spec defines this.
2020-09-18 20:49:35 +02:00
Linus Groh
fd32f00839 LibJS: Mark more ASTNode classes as final 2020-09-18 20:49:35 +02:00
Linus Groh
568d53c9b1 LibJS: Check validity of computed_property_name() result before using it
This fixes two cases obj[expr] and obj[expr]() (MemberExpression and
CallExpression respectively) when expr throws an exception and results
in an empty value, causing a crash by passing the invalid PropertyName
created by computed_property_name() to Object::get() without checking it
first.

Fixes #3459.
2020-09-12 11:29:39 +02:00
Linus Groh
75dac35d0e LibJS: Stop unwinding and reset exception for TryStatement finalizer
This fixes two issues with running a TryStatement finalizer:

- Temporarily store and clear the exception, if any, so we can run the
  finalizer block statement without it getting in our way, which could
  have unexpected side effects otherwise (and will likely return early
  somewhere).
- Stop unwinding so more than one child node of the finalizer
  BlockStatement is executed if an exception has been thrown previously
  (which would have called unwind(ScopeType::Try)). Re-throwing as
  described above ensures we still unwind after the finalizer, if
  necessary.

Also add some tests specifically for try/catch/finally blocks, we
didn't have any!
2020-09-12 09:31:16 +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
Ben Wiederhake
5d3c437cce LibJS: Fix start position of multi-line tokens
This broke in case of unterminated regular expressions, causing goofy location
numbers, and 'source_location_hint' to eat up all memory:

Unexpected token UnterminatedRegexLiteral. Expected statement (line: 2, column: 4294967292)
2020-09-12 00:13:29 +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
55c4866370 LibJS: Add tests for issue #3382 2020-09-01 21:35:59 +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
db422fa499 LibJS: Avoid unnecessary lambda
Especially when it's evaluated immediately and unconditionally.
2020-08-30 10:31:04 +02:00
Ben Wiederhake
d8e22fedc3 Libraries: Unbreak building with extra debug macros 2020-08-30 09:43:49 +02:00
AnotherTest
a2113909c3 LibJS: Do not consider un-labeled Block scopes as breakable 2020-08-28 20:19:56 +02:00
AnotherTest
8e89233bba LibJS: Demonstrate weird behaviour with 'break' 2020-08-28 20:19:56 +02:00
Ben Wiederhake
9f7ec33180 Meta: Force semi-colon after MAKE_AK_NONXXXABLE()
Before, we had about these occurrence counts:
COPY: 13 without, 33 with
MOVE: 12 without, 28 with

Clearly, 'with' was the preferred way. However, this introduced double-semicolons
all over the place, and caused some warnings to trigger.

This patch *forces* the usage of a semi-colon when calling the macro,
by removing the semi-colon within the macro. (And thus also gets rid
of the double-semicolon.)
2020-08-27 10:12:04 +02:00
Nico Weber
2c1b84b3e1 LibJS: Add some more tests, mostly around leap years 2020-08-26 08:52:07 +02:00
AnotherTest
394e4c04cd LibJS: Add a helper for calling JS::Function's with arguments
The fact that a `MarkedValueList` had to be created was just annoying,
so here's an alternative.
This patchset also removes some (now) unneeded MarkedValueList.h includes.
2020-08-26 08:45:01 +02:00
Nico Weber
e4dac38127 JS Tests: Disable the one failing test when running test-js in Serenity 2020-08-25 21:23:10 +02:00
Linus Groh
9ea6ef4ed1 LibJS: Make Interpreter::throw_exception() a void function
The motivation for this change is twofold:

- Returning a JS::Value is misleading as one would expect it to carry
  some meaningful information, like maybe the error object that's being
  created, but in fact it is always empty. Supposedly to serve as a
  shortcut for the common case of "throw and return empty value", but
  that's just leading us to my second point.
- Inconsistent usage / coding style: as of this commit there are 114
  uses of throw_exception() discarding its return value and 55 uses
  directly returning the call result (in LibJS, not counting LibWeb);
  with the first style often having a more explicit empty value (or
  nullptr in some cases) return anyway.
  One more line to always make the return value obvious is should be
  worth it.

So now it's basically always these steps, which is already being used in
the majority of cases (as outlined above):

- Throw an exception. This mutates interpreter state by updating
  m_exception and unwinding, but doesn't return anything.
- Let the caller explicitly return an empty value, nullptr or anything
  else itself.
2020-08-25 18:30:31 +02:00
AnotherTest
54036d660a Meta: Move prettier config files to the root of the repository 2020-08-24 18:21:33 +02:00
Nico Weber
697faba147 LibJS: Make Date.getUTCSeconds() call through to LibC
The tzset documentation says that TZ allows a per-second local timezone,
so don't be needlessly clever here.

No observable behavior difference at this point, but if we ever
implement tzset, this will have a small effect.
2020-08-24 18:21:16 +02:00
Nico Weber
2191ec591f LibJS: Make Date's tuple constructor correctly handle out-of-range arguments
Milliseconds need extra handling, but everything else just works
now that mktime() handles this case.
2020-08-24 18:20:07 +02:00
Nico Weber
84f729c2b4 LibJS+LibC: Add tests for Date tuple ctor overflow and make mktime()/timegm() handle month overflow 2020-08-24 09:30:11 +02:00
Nico Weber
ad00462daa LibJS: Implement Date.getUTC*
Test files created with:
    $ for f in Libraries/LibJS/Tests/builtins/Date/Date.prototype.get*js; do
          cp $f $(echo $f | sed -e 's/get/getUTC/') ;
      done
    $ rm Libraries/LibJS/Tests/builtins/Date/Date.prototype.getUTCTime.js
    $ git add Libraries/LibJS/Tests/builtins/Date/Date.prototype.getUTC*.js
    $ ls Libraries/LibJS/Tests/builtins/Date/Date.prototype.getUTC*.js | \
          xargs sed -i -e 's/get/getUTC/g'
2020-08-23 22:00:05 +02:00
Nico Weber
d5eaefe87b LibJS: Move datetime access out of DatePrototype
How Date keeps time internally should be an implementation detail
of Date, so move it behind accessors.

No behavior change.
2020-08-23 22:00:05 +02:00
Nico Weber
5f595e7e1b LibC: Make localtime() and gmtime() handle years before 1970
Year computation has to be based on seconds, not days, in case
t is < 0 but t / __seconds_per_day is 0.

Year computation also has to consider negative timestamps.

With this, days is always positive and <= the number of days in the
year, so base the tm_wday computation directly on the timestamp,
and do it first, before t is modified in the year computation.
In C, % can return a negative number if the left operand is negative,
compensate for that.

Tested via test-js. (Except for tm_wday, since we don't implement
Date.prototype.getUTCDate() yet.)
2020-08-23 10:42:37 +02:00
Nico Weber
cec467fe35 LibJS: Enable Date.parse.js tests that pass after c399caf27f 2020-08-23 10:42:37 +02:00
Nico Weber
c399caf27f LibC: Make mktime() and timegm() handle years before 1970
And also years that don't fit in 32-bit.

Lovingly tested via LibJS's Date.UTC(), which happens to call
timegm().
2020-08-22 10:53:33 +02:00
Nico Weber
96891669c3 test-js: Sometimes include more details for failures
LibJS doesn't store stacks for exception objects, so this
only amends test-common.js's __expect() with an optional
`details` function that can produce a more detailed error
message, and it lets test-js.cpp read and print that
error message.  I added the optional details parameter to
a few matchers, most notably toBe() where it now prints
expected and actual value.

It'd be nice to have line numbers of failures, but that
seems hard to do with the current design, and this is already
much better than the current state.
2020-08-22 10:52:40 +02:00
Nico Weber
ebd510ef5e LibJS: Allow conversion from Symbol to String via explicit String() call
https://tc39.es/ecma262/#sec-string-constructor-string-value has an
explicit special case for Symbols allowing this:

    If NewTarget is undefined and Type(value) is Symbol,
    return SymbolDescriptiveString(value).
2020-08-22 10:52:40 +02:00
Nico Weber
116c0c0ab3 LibJS: Implement Date's string constructor
... by calling Date.parse().

With this, dates on http://45.33.8.238/ and
http://45.33.8.238/linux/summary.html are correctly converted to local
time :^)
2020-08-21 21:12:54 +02:00
Nico Weber
6e5aa5d5df LibJS: Implement Date.parse()
The spec says Date.parse() should accept at least a simplified form
of ISO 8601, so that's all this implements.
2020-08-21 21:12:54 +02:00
Muhammad Zahalqa
5a2ec86048 LibJS: Parser refactored to use constexpr precedence table
Replaced implementation dependent on HashMap with a constexpr PrecedenceTable
based on array lookup.
2020-08-21 16:14:14 +02:00
Nico Weber
c8cf465174 LibJS: Implement Date.valueOf()
It does exactly the same thing as Date.getTime().
2020-08-21 16:03:34 +02:00
Nico Weber
a6b68451dc LibJS: Implement Date.prototype.toISOString() 2020-08-21 12:11:48 +02:00
Nico Weber
1eac1b360b LibJS: Implement Date.UTC() 2020-08-21 12:11:48 +02:00
Nico Weber
d4d9222eea LibJS: Basic implementation of most of Date's constructor arguments
The constructor with a string argument isn't implemented yet, but
this implements the other variants.

The timestamp constructor doens't handle negative timestamps correctly.

Out-of-bound and invalid arguments aren't handled correctly.
2020-08-20 20:53:43 +02:00
Nico Weber
a3908732ad LibJS: Add toLocaleString(), toLocaleDateString(), toLocaleTimeString() to Date
These just return a "readable" implementation of the date for now.
2020-08-17 21:23:11 +02:00
Nico Weber
8ebef785eb LibJS: Implement basic functionality of Array.from()
The optional 2nd and 3rd arguments are not yet implemented.

This assumes that `this` is the Array constructor and doesn't yet
implement the more general behavior in the ES6 spec that allows
transferring this method to other constructors.
2020-08-17 21:23:11 +02:00
Andreas Kling
bbd3192535 LibJS: Add API for doing GC with a little debug log report at end
You can now pass print_report=true to Heap::collect_garbage() and it
will print out a little summary of the time spent, and counts of
live vs freed cells and blocks.
2020-08-16 20:33:56 +02:00
Andreas Kling
6444f49d22 LibJS: Make StringOrSymbol not leak strings
Ideally this thing would not allocate strings at all, but I'll leave
that as a separate exercise.
2020-08-16 20:31:05 +02:00
Nico Weber
430b265cd4 AK: Rename KB, MB, GB to KiB, MiB, GiB
The SI prefixes "k", "M", "G" mean "10^3", "10^6", "10^9".
The IEC prefixes "Ki", "Mi", "Gi" mean "2^10", "2^20", "2^30".

Let's use the correct name, at least in code.

Only changes the name of the constants, no other behavior change.
2020-08-16 16:33:28 +02:00
Andreas Kling
bbe2d4a2d9 LibJS+LibWeb: Clear exceptions after call'ing JavaScript functions
Decorated Interpreter::call() with [[nodiscard]] to provoke thinking
about the returned value at each call site. This is definitely not
perfect and we should really start thinking about slimming down the
public-facing LibJS interpreter API.

Fixes #3136.
2020-08-14 17:31:07 +02:00
Andreas Kling
c5127389ca LibJS: Assert that there's no exception on entry in Interpreter::call() 2020-08-14 17:30:34 +02:00
Linus Groh
d1d9545875 LibJS: Add missing reserved words to Token::is_identifier_name()
This is being used in match_identifier_name(), for example when parsing
property keys - the list was incomplete, likely as some token types were
added later, leading to some unexpected syntax errors:

> var e = {};
undefined
> e.extends = "a";
e.extends = "a";
  ^
Uncaught exception: [SyntaxError]: Unexpected token Extends. Expected IdentifierName (line: 1, column: 3)

Fixes #3128.
2020-08-14 10:58:51 +02:00
Linus Groh
36c738d9bf LibJS: Assert when exception is not cleared before Interpreter::run()
This is to prevent bugs like #3091 (fixed in
9810f8872c21eaf2aefff25347d957cd26f34c2d) in the future; we generally
don't want Interpreter::run() to be called if the interpreter still has
an exception stored. Sure, it could clear those itself but letting users
of the interpreter do it explicitly seems sensible.
2020-08-11 21:08:30 +02:00
Nico Weber
ce95628b7f Unicode: Try s/codepoint/code_point/g again
This time, without trailing 's'. Ran:

    git grep -l 'codepoint' | xargs sed -ie 's/codepoint/code_point/g
2020-08-05 22:33:42 +02:00
Nico Weber
19ac1f6368 Revert "Unicode: s/codepoint/code_point/g"
This reverts commit ea9ac3155d.
It replaced "codepoint" with "code_points", not "code_point".
2020-08-05 22:33:42 +02:00
Melissa Goad
192b2383ac LibJS: The Math.ceil() of a number between -1 and 0 should be -0,
according to the spec.
2020-08-04 11:31:11 +02:00
Andreas Kling
ea9ac3155d Unicode: s/codepoint/code_point/g
Unicode calls them "code points" so let's follow their style.
2020-08-03 19:06:41 +02:00
Ben Wiederhake
801058e514 LibJS: Soothe gcc about printf-%s on (non-)nullptr 2020-07-28 19:10:10 +02:00
Andreas Kling
3ee6ed965f LibJS: Use allocate_without_global_object for primitive cell types
More steps towards multiple global object support. Primitive cells
like strings, bigints, etc, don't actually have any connection to
the global object. Use the explicit API to clarify this.
2020-07-25 13:12:17 +02:00
Nico Weber
c4d9d5cc54 Browser: Escape JS source operators for HTML display in console
Console inputs to try before and after this patch:
- `0xffff & 0xff`
- `"a & b"`
- `"<div>"`
- `a &` (to see the escaping in the error hint)
2020-07-23 23:01:16 +02:00
Andreas Kling
aaf6014ae1 LibJS: Simplify Cell::initialize()
Remove the Interpreter& argument and pass only GlobalObject&. We can
find everything we need via the global object anyway.
2020-07-23 17:31:08 +02:00
Nico Weber
79a5ba58a5 LibJS: Add tests for bitwise & and ^
And fix some edge case conversion bugs found by the tests.
2020-07-23 13:06:49 +02:00
Nico Weber
b9ce56aee6 LibWeb: Make btoa() and atob() correctly handle values between 128 and 255
btoa() takes a byte string, so it must decode the UTF-8 argument into
a Vector<u8> before calling encode_base64.

Likewise, in atob() decode_base64 returns a byte string, so that needs
to be converted to UTF-8.

With this, `btoa(String.fromCharCode(255))` is '/w==' as it should
be, and `atob(btoa(String.fromCharCode(255))) == String.fromCharCode(255)`
remains true.
2020-07-22 19:22:00 +02:00
Nico Weber
9e32ad6c99 LibJS: Fix \x escapes of bytes with high bit set
With this, typing `"\xff"` into Browser's console no longer
makes the app crash.

While here, also make the \u handler call append_codepoint()
instead of calling an overload where it's not immediately clear
which overload is getting called. This has no behavior change.
2020-07-22 19:21:35 +02:00
Nico Weber
248b79d687 LibJS: Add FIXMEs to a few functions that need UTF-16 handling 2020-07-22 17:26:34 +02:00
Nico Weber
979e02c0a8 LibJS: Implement String.prototype.charCodeAt
It's broken for strings with characters outside 7-bit ASCII, but
it's broken in the same way as several existing functions (e.g.
charAt()), so that's probably ok for now.
2020-07-22 15:48:01 +02:00
Matthew Olsson
02305d01ea LibJS: Add Number.prototype.toString 2020-07-15 18:24:55 +02:00
Matthew Olsson
6075defd55 LibJS: Add Symbol.hasInstance tests 2020-07-14 20:15:19 +02:00
Matthew Olsson
b0296735a5 LibJS: Implement Symbol.hasInstance 2020-07-14 20:15:19 +02:00
Matthew Olsson
dd49ec17a2 LibJS: Implement spec-complient instance_of operation 2020-07-14 20:15:19 +02:00
Matthew Olsson
a51b2393f2 LibJS: Integrate iterator protocol into language features
Finally use Symbol.iterator protocol in language features :) currently
only used in for-of loops and spread expressions, but will have more
uses later (Maps, Sets, Array.from, etc).
2020-07-14 17:58:42 +02:00
Matthew Olsson
4c3a415dc3 LibJS: Add String Iterator tests 2020-07-13 15:07:29 +02:00
Matthew Olsson
c831fb17bf LibJS: Add StringIterator 2020-07-13 15:07:29 +02:00
Matthew Olsson
43d955014d LibJS: Implement Symbol.toStringTag 2020-07-11 23:13:29 +02:00
Matthew Olsson
5ecd504f4e LibJS: Implement spec-compliant Object.prototype.toString 2020-07-11 23:13:29 +02:00
Matthew Olsson
531fdb2e82 LibJS: Prefer "define_property" over "put" 2020-07-11 18:54:13 +02:00
Matthew Olsson
c485c86015 LibJS: Use macros to enumerate well-known symbols
Not only is this a much nicer api (can't pass a typo'd string into the
get_well_known_symbol function), it is also a bit more performant since
there are no hashmap lookups.
2020-07-11 18:54:13 +02:00
Matthew Olsson
2ea85355fe LibJS: Start implementing iterable framework, add ArrayIterator
With the addition of symbol keys, work can now be done on starting to
implement the well-known symbol functionality. The most important of
these well-known symbols is by far Symbol.iterator.

This patch adds IteratorPrototype, as well as ArrayIterator and
ArrayIteratorPrototype. In the future, sometime after StringIterator has
also been added, this will allow us to use Symbol.iterator directly in
for..of loops, enabling the use of custom iterator objects. Also makes
adding iterator support to native objects much easier (as will have to
be done for Map and Set, when they get added).
2020-07-11 18:54:13 +02:00
Matthew Olsson
51bfc6c6b3 LibJS: Renamed Object::GetOwnPropertyReturnMode to Object::PropertyKind
This enum will be used by iterators, so it makes sense to use a more
general name.
2020-07-11 18:54:13 +02:00
Linus Groh
7241b9ca0c LibJS: Remove a few superfluous exception checks
We don't need to check for exceptions when defining properties on an
array we literally created ourselves a few lines earlier.
2020-07-11 18:38:51 +02:00
Matthew Olsson
119386ffb0 LibJS: Add tests for symbol object integration 2020-07-09 23:33:00 +02:00
Matthew Olsson
7a1d485b19 LibJS: Integrate Symbols into objects as valid keys
This allows objects properties to be created for symbol keys in addition
to just plain strings/numbers
2020-07-09 23:33:00 +02:00
Matthew Olsson
9783a4936c LibJS: Add test for well-known symbols 2020-07-09 23:29:28 +02:00
Matthew Olsson
ffb569fd5d LibJS: Uncomment remaining symbol tests 2020-07-09 23:29:28 +02:00
Matthew Olsson
d9db6bec42 LibJS: Move global symbol map from SymbolObject to Interpreter
This allows different instances of the Interpreter to have their own
global symbols. Also makes Symbol non-copyable and non-moveable.
2020-07-09 23:29:28 +02:00
Matthew Olsson
93ebd320ef LibJS: Object.preventExtensions should allow property modfication
Existing properties on a non-extensible object should be changable and
deletable.
2020-07-07 10:47:10 +02:00
Linus Groh
461d90d042 LibJS: Convert Array tests to new testing framework 2020-07-06 23:40:35 +02:00
Linus Groh
8ebdf685a6 LibJS: Split isNaN tests into multiple sections 2020-07-06 23:40:35 +02:00
Matthew Olsson
1ef573eb30 LibJS: Indent tests with 4 spaces instead of 2 2020-07-06 23:40:35 +02:00
Matthew Olsson
15de2eda2b LibJS: Convert all remaining non-Array tests to the new system :) 2020-07-06 23:40:35 +02:00
Matthew Olsson
918f4affd5 LibJS: Convert remaining top-level tests to new system 2020-07-06 23:40:35 +02:00
Matthew Olsson
6d58c48c2f test-js: Use prettier and format all files 2020-07-06 23:40:35 +02:00
Matthew Olsson
a2dbd955f2 test-js: Display messages from console.log in test output
This will help greatly with debugging!
2020-07-06 23:40:35 +02:00
Matthew Olsson
82fa65135a test-js: Allow skipping tests with "test.skip(name, callback)"
Skipped tests count as a "pass" rather than a "fail" (i.e. a test suite
with a skipped test will pass), however it does display a message when
the test is printing.

This is intended for tests which _should_ work, but currently do not.
This should be preferred over "// FIXME" notes if possible.
2020-07-06 23:40:35 +02:00
Matthew Olsson
cf537311e4 test-js: Remove run-tests.sh
The shell script is no longer necessary -- simply run "test-js" from
inside Serenity, or $SERENITY_ROOT/Build/Meta/Lagom/test-js from the
host.
2020-07-06 23:40:35 +02:00
Matthew Olsson
26acc8ba88 LibJS/test-js: Clean up test-js code
This commit also exposes JSONObject's implementation of stringify to the
public, so that it can be used by test-js without having to go through
the interpreter's environment.
2020-07-06 23:40:35 +02:00
Matthew Olsson
4c6fd49169 LibJS: Fix String.raw.length 2020-07-06 23:40:35 +02:00
Matthew Olsson
3f97d75778 LibJS: Convert most builtin tests to new system 2020-07-06 23:40:35 +02:00
Linus Groh
46581773c1 LibJS: Convert Reflect object tests to new testing framework 2020-07-06 23:40:35 +02:00
Matthew Olsson
fc08222f46 LibJS: Add more test matchers 2020-07-06 23:40:35 +02:00
Matthew Olsson
5e971c91e3 LibJS: Hide some debug output behind flags
This hides some Object.cpp output, as well as removing the "debugger"
debug output.
2020-07-06 23:40:35 +02:00
Matthew Olsson
449a1cf3a2 LibJS: Convert Proxy tests 2020-07-06 23:40:35 +02:00
Matthew Olsson
b86faeaeef LibJS: Add test-common.js tests, remove unused matchers
Now that test-common.js is quite a bit more complicated, we need tests
for test-common to make sure all of the matchers behave correctly
2020-07-06 23:40:35 +02:00
Matthew Olsson
eea6041302 LibJS: Convert some top-level tests to the new system
First test conversions! These look really good :)
2020-07-06 23:40:35 +02:00
Matthew Olsson
4b8a3e6d78 LibJS: Refactor run-tests.sh to use the new test-js program 2020-07-06 23:40:35 +02:00
Matthew Olsson
b9cf7a833f LibJS/test-js: Create test-js program, prepare for test suite refactor
This moves most of the work from run-tests.sh to test-js.cpp. This way,
we have a lot more control over how the test suite runs, as well as how
it outputs. This should result in some cool functionality!

This commit also refactors test-common.js to mimic the jest library.
This should allow tests to be much more expressive :)
2020-07-06 23:40:35 +02:00
Matthew Olsson
6af3fff0c2 LibJS: Reformat run-tests.sh output
- Use emojis instead of the pass/fail text
- Fix the new version of the script to run inside Serenity
- Don't print erroneous output after 'Output:'; start on a newline
instead
- Skip 'run-tests.sh' while testing
2020-07-03 19:30:13 +02:00
Matthew Olsson
97634d0678 LibJS: Hide interpreter exception debug output behind a flag 2020-07-03 19:30:13 +02:00
Matthew Olsson
4c48c9d69d LibJS: Reorganize tests into subfolders 2020-07-03 19:30:13 +02:00
Matthew Olsson
21064a1883 LibJS: Use correct MarkedValueList append method 2020-07-03 19:30:13 +02:00
Matthew Olsson
02debd8a6d LibJS: Remove extra colon in run-tests.sh output 2020-07-03 19:30:13 +02:00
Matthew Olsson
bda39ef7ab LibJS: Explicitly pass a "Function& new_target" to Function::construct
This allows the proxy handler to pass the proper new.target to construct
handlers.
2020-07-01 11:16:37 +02:00
Matthew Olsson
19411e22d0 LibJS: Add Proxy [[Call]] and [[Construct]] tests 2020-07-01 11:16:37 +02:00
Matthew Olsson
98323e19e5 LibJS: Implement Proxy [[Call]] and [[Construct]] traps
In order to do this, Proxy now extends Function rather than Object, and
whether or not it returns true for is_function() depends on it's
m_target.
2020-07-01 11:16:37 +02:00
Andreas Kling
ed683663cd LibJS: Skip some Math object tests that fail on Serenity
Mark a bunch of these with FIXME so that someone can find them and
fix them eventually. :^)
2020-06-30 23:11:07 +02:00
Jack Karamanian
7533fd8b02 LibJS: Initial class implementation; allow super expressions in object
literal methods; add EnvrionmentRecord fields and methods to
LexicalEnvironment

Adding EnvrionmentRecord's fields and methods lets us throw an exception
when |this| is not initialized, which occurs when the super constructor
in a derived class has not yet been called, or when |this| has already
been initialized (the super constructor was already called).
2020-06-29 17:54:54 +02:00
Jack Karamanian
a535d58cac LibJS: Add Object::define_accessor()
This is a helper function based on the getter/setter definition logic from
ObjectExpression::execute() to look up an Accessor property if it already
exists, define a new Accessor property if it doesn't exist, and set the getter or
setter function on the Accessor.
2020-06-29 17:54:54 +02:00
Jack Karamanian
949bffdc93 LibJS: Define the "constructor" property on ScriptFunction's prototype
and set it to the current function
2020-06-29 17:54:54 +02:00
Matthew Olsson
53f1090b86 LibJS: run-test.sh emits test output if it is not "PASS"
Previously, debugging a test with console.log statements was impossible,
because it would just cause the test to fail with no additional output.
Now, if the output of a test is not "PASS", the output will be printed
under the line where the test failed.

Empty output will have a special message attached to it -- useful when
a test author has forgotten to include `console.log("PASS")` at the end
of a test.
2020-06-26 12:40:07 +02:00
Andreas Kling
200481efb2 LibJS: to_string_without_side_effects() should handle NativeProperty 2020-06-26 00:53:25 +02:00
Linus Groh
afcfea2001 LibJS: Handle "receiver" argument in Reflect.{get,set}() 2020-06-25 15:51:47 +02:00
Andreas Kling
675e7c0e6f LibJS: Explicitly invoke Cell constructor in Object(Object& prototype) 2020-06-23 18:28:28 +02:00
Andreas Kling
0166a1fa74 LibJS: Make NativeProperty a plain Cell instead of an Object
This removes the need for NativeProperty objects to have a prototype,
which just made things confusing.
2020-06-23 17:56:57 +02:00
Andreas Kling
ba641e97d9 LibJS: Clarify Object (base class) construction somewhat
Divide the Object constructor into three variants:

- The regular one (takes an Object& prototype)
- One for use by GlobalObject
- One for use by objects without a prototype (e.g ObjectPrototype)
2020-06-23 17:21:53 +02:00
Andreas Kling
fc4ed8d444 LibWeb: Make wrapper factory functions take JS::GlobalObject&
Instead of taking the JS::Heap&. This allows us to get rid of some
calls to JS::Interpreter::global_object(). We're getting closer and
closer to multiple global objects. :^)
2020-06-23 16:57:39 +02:00
Andreas Kling
9ce25bbf1d LibWeb: Generate CanvasRenderingContext2D bindings from IDL :^)
We're still missing optional argument support, so this implementation
doesn't support fill(), only fill(fill_rule).

Still it's really nice to get rid of so much hand-written wrapper code.
2020-06-22 19:07:25 +02:00
stelar7
9e18005c64 LibJS: expose some more math functions 2020-06-22 10:33:50 +02:00
Andreas Kling
af51dc105a LibJS+LibWeb: Add JS::Object::inherits(class_name)
To allow implementing the DOM class hierarchy in JS bindings, this
patch adds an inherits() function that can be used to ask an Object
if it inherits from a specific C++ class (by name).

The necessary overrides are baked into each Object subclass by the
new JS_OBJECT macro, which works similarly to C_OBJECT in LibCore.

Thanks to @Dexesttp for suggesting this approach. :^)
2020-06-21 15:15:52 +02:00
Andreas Kling
94fdf4fa5a LibWeb+LibJS: Add a naive way to check if a wrapper "is" a certain type
Instead of only checking the class_name(), we now generate an is_foo()
virtual in the wrapper generator. (It's currently something we override
on Bindings::Wrapper, which is not really scalable.)

Longer term we'll need to think up something smarter for verifying that
one wrapper "is" another type of wrapper.
2020-06-21 00:58:55 +02:00
Andreas Kling
3ba17d8df7 LibJS: Make Interpreter::construct() take a GlobalObject& 2020-06-20 17:53:33 +02:00
Andreas Kling
2fe4285693 LibJS: Object::initialize() overrides must always call base class 2020-06-20 17:50:48 +02:00
Andreas Kling
e1f9da142e LibJS: NativeProperty get/put should take a GlobalObject& 2020-06-20 17:50:48 +02:00
Andreas Kling
06e29fac57 LibJS: Split more native object constructors into construct/initialize 2020-06-20 17:50:48 +02:00
Andreas Kling
9610d18ebb LibJS: Remove some Interpreter::global_object() calls in JSONObject 2020-06-20 17:50:48 +02:00
Andreas Kling
32c121a8f7 LibJS: Pass GlobalObject& to Reference get/put 2020-06-20 17:50:48 +02:00
Andreas Kling
8d56e6103e LibJS: Make Value::to_object() take a GlobalObject& 2020-06-20 17:50:48 +02:00
Andreas Kling
cd14ebb11f LibJS: More Interpreter::global_object() removal
Also let's settle on calling the operation of fetching the "this" value
from the Interpreter and converting it to a specific Object pointer
typed_this() since consistency is nice.
2020-06-20 17:50:48 +02:00
Andreas Kling
a9e4babdaf LibJS: Pass GlobalObject& when constructing an Accessor 2020-06-20 17:50:48 +02:00
Andreas Kling
64513f3c23 LibJS: Move native objects towards two-pass construction
To make sure that everything is set up correctly in objects before we
start adding properties to them, we split cell allocation into 3 steps:

1. Allocate a cell of appropriate size from the Heap
2. Call the C++ constructor on the cell
3. Call initialize() on the constructed object

The job of initialize() is to define all the initial properties.
Doing it in a second pass guarantees that the Object has a valid Shape
and can find its own GlobalObject.
2020-06-20 15:46:30 +02:00
Andreas Kling
e4add19915 LibJS: Pass GlobalObject& to native functions and property accessors
More work towards supporting multiple global objects. Native C++ code
now get a GlobalObject& and don't have to ask the Interpreter for it.

I've added macros for declaring and defining native callbacks since
this was pretty tedious and this makes it easier next time we want to
change any of these signatures.
2020-06-20 15:45:07 +02:00
Andreas Kling
4aa98052ca LibJS: Remove some more use of Interpreter::global_object()
Let's do some more work towards supporting multiple global objects.
2020-06-20 15:45:07 +02:00
Matthew Olsson
b155e64b67 LibJS: Add JSON.parse 2020-06-13 12:43:22 +02:00
Matthew Olsson
39576b2238 LibJS: Add JSON.stringify 2020-06-13 12:43:22 +02:00
Andreas Kling
fdfda6dec2 AK: Make string-to-number conversion helpers return Optional
Get rid of the weird old signature:

- int StringType::to_int(bool& ok) const

And replace it with sensible new signature:

- Optional<int> StringType::to_int() const
2020-06-12 21:28:55 +02:00
Matthew Olsson
78155a6668 LibJS: Consolidate error messages into ErrorTypes.h
Now, exceptions can be thrown with
interpreter.throw_exception<T>(ErrorType:TYPE, "format", "args",
"here").
2020-06-11 07:46:20 +02:00