Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions JSTests/BUN-TEST-DIFFERENCES.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,9 @@ Not upstream's: a sync neither brings nor changes them. Most are named `stress/b
| `stress/bun-object-assign-calls-indexed-setters-on-the-chain.js` | `Object.assign()` stores with `[[Set]]` on its fast path too: an indexed setter on the target's prototype chain is called, and a read-only element there refuses the store |
| `stress/bun-arrays-become-prototypes-below-immutable-prototypes.js` | with `Object.prototype` and `Array.prototype` immutable and a setter under an index on a class prototype, an array or an object with elements that becomes a prototype keeps the storage it has; reads, stores and changes of length on it and through its heirs answer as the language says |
| `stress/function-prototype-call-not-called-as-a-method.js` | `f.call(...)` is compiled to a call of `f`, so only other ways reach `Function.prototype.call` itself: `call.bind(f)`, `Reflect.apply`, `call.call` and `call.apply`. Through each of them `this`, the arguments and `new.target` arrive as they should, and a callee that is not callable is a `TypeError`, in every tier |
| `modules/export-default-function-name-for-display.js`, `modules/export-default-function-name-for-display-eager.js` | an anonymous default export is bound to the private name `*default*`, and its name is `default`: a stack (also the frame of a failed tail call, and behind an `await`), the two errors that name a class declaration, the name of a code block, and the class names and labels of a heap snapshot show `default`, not the text of that private name (`starDefault`). A function that is really named `starDefault` keeps its name. The second file runs the first with `useLazyModuleFunctionDeclarations` off |
| `stress/sampling-profiler-default-export-name.js` | the sampling profiler names a frame of an anonymous default export `default` when the DFG or the FTL inlined the function: that frame has no function object, and its name comes from the executable |
| `stress/bytecode-cache-default-export-function-declaration-name.js` | a module that is made from a bytecode cache finds the binding of an anonymous default function declaration by the name in the cache, when it makes its environment and when the binding is first read, and the function has the name `default` |
| `stress/regexp-greedy-group-in-tail-position.js` | a greedy `*` or `+` group that nothing can fail after runs without the state of its earlier iterations: `exec()`, `match()` and `replace()` give the listed results |
| `stress/regexp-greedy-group-with-minimum-can-match-empty.js` | `YarrPattern` drops the minimum of a greedy group that has no maximum and whose body can match the empty string: the results are the same as with the minimum |
| `stress/regexp-long-source.js` | the limit of 1 MiB on the source of a pattern does not include the text of character classes made only of characters and ranges, up to 4 MiB in all. Everything else is "too large" where it was before |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
//@ requireOptions("--useLazyModuleFunctionDeclarations=0")
// The same checks where the environment of a module makes the functions of its declarations at once,
// and not when a binding is first read.
import "./export-default-function-name-for-display.js";
119 changes: 119 additions & 0 deletions JSTests/modules/export-default-function-name-for-display.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { shouldBe } from "./resources/assert.js";
import functionDeclaration from "./export-default-function-name-for-display/function-declaration.js";
import generatorDeclaration from "./export-default-function-name-for-display/generator-declaration.js";
import asyncFunctionDeclaration from "./export-default-function-name-for-display/async-function-declaration.js";
import asyncGeneratorDeclaration from "./export-default-function-name-for-display/async-generator-declaration.js";
import ClassDeclaration from "./export-default-function-name-for-display/class-declaration.js";
import DerivedClassDeclaration from "./export-default-function-name-for-display/derived-class-declaration.js";
import ClassWithDefaultConstructor from "./export-default-function-name-for-display/class-with-default-constructor.js";
import DerivedClassWithDefaultConstructor from "./export-default-function-name-for-display/derived-class-with-default-constructor.js";
import arrowFunction from "./export-default-function-name-for-display/arrow-function.js";
import functionExpression from "./export-default-function-name-for-display/function-expression.js";
import ClassExpression from "./export-default-function-name-for-display/class-expression.js";
import namedStarDefault from "./export-default-function-name-for-display/named-star-default.js";
import awaits from "./export-default-function-name-for-display/awaits.js";
import tailCall from "./export-default-function-name-for-display/tail-call.js";

// An anonymous default export is bound to the private name "*default*", whose text is "starDefault".
// Its name is "default", and that is what a stack, an error message, a code block and a heap snapshot show.
// https://tc39.es/ecma262/#sec-exports-runtime-semantics-evaluation

// A line of a stack is `name@url:line:column`.
function frames(stack) {
return stack.replace(/@.*/g, "").split("\n").join(" < ");
}

function messageOf(run) {
try {
run();
} catch (error) {
return error.message;
}
return "no error";
}

const anonymous = [functionDeclaration, generatorDeclaration, asyncFunctionDeclaration, asyncGeneratorDeclaration, ClassDeclaration, DerivedClassDeclaration, ClassWithDefaultConstructor, DerivedClassWithDefaultConstructor, arrowFunction, functionExpression, ClassExpression, tailCall];

// A call in tail position that throws leaves no function object for its frame, and the frame has the name of its code.
// A caller that inlined the function has no such frame at all.
noInline(tailCall);

function checkFrames() {
shouldBe(frames(functionDeclaration()), "default < checkFrames < module code");
shouldBe(frames(generatorDeclaration().next().value), "default < checkFrames < module code");
shouldBe(frames(new ClassDeclaration().stack), "default < checkFrames < module code");
shouldBe(frames(arrowFunction()), "default < checkFrames < module code");
shouldBe(frames(functionExpression()), "default < checkFrames < module code");
shouldBe(frames(new ClassExpression().stack), "default < checkFrames < module code");
// A function that is really named starDefault keeps its name.
shouldBe(frames(namedStarDefault()), "starDefault < checkFrames < module code");

let thrown;
try {
tailCall();
} catch (error) {
thrown = error;
}
shouldBe(frames(thrown.stack), "default < checkFrames < module code");
}

// Behind an await the function that waits is an async frame.
async function checkAsyncFrames() {
shouldBe(frames(await asyncFunctionDeclaration()), "default < async checkAsyncFrames");
shouldBe(frames((await asyncGeneratorDeclaration().next()).value), "default");
let caught;
try {
await awaits();
} catch (error) {
caught = error;
}
shouldBe(frames(caught.stack), "thrower < async default < async checkAsyncFrames");
}

// The "name" property is made when it is first looked for. The frames are the same before and after.
// The loops take checkFrames() and what it calls through the tiers that the mode reaches in 300 calls: the DFG and
// the FTL with the thresholds of the eager modes, the baseline JIT with the others.
const loopCount = Math.min(testLoopCount, 300);
for (let i = 0; i < loopCount; ++i)
checkFrames();
await checkAsyncFrames();
for (const target of anonymous) {
shouldBe(target.name, "default");
shouldBe(target.bind().name, "bound default");
}
shouldBe(namedStarDefault.name, "starDefault");
for (let i = 0; i < loopCount; ++i)
checkFrames();
await checkAsyncFrames();

// These two messages have the name of a class declaration.
shouldBe(messageOf(() => ClassDeclaration()), "Cannot call a class constructor default without |new|");
shouldBe(messageOf(() => new DerivedClassDeclaration), "Cannot return a non-object type in the constructor of a derived class default.");

// What tools print for the code of a function: `name#hash`. A default constructor has its code once it ran.
new ClassWithDefaultConstructor;
new DerivedClassWithDefaultConstructor;
for (const target of anonymous)
shouldBe($vm.codeBlockFor(target).split("#")[0], "default");
shouldBe($vm.codeBlockFor(namedStarDefault).split("#")[0], "starDefault");

// A heap snapshot names an object after its constructor and labels a function with its name.
const instances = [new ClassDeclaration, new ClassExpression];
const classNames = generateHeapSnapshot().nodeClassNames;
shouldBe(classNames.includes("default"), true);
shouldBe(classNames.includes("starDefault"), false);

// A node of this snapshot is seven values. The fifth one is the index of its label.
const snapshot = JSON.parse(generateHeapSnapshotForGCDebugging());
function countOfNodesWithLabel(label) {
const index = snapshot.labels.indexOf(label);
let count = 0;
for (let i = 4; i < snapshot.nodes.length; i += 7) {
if (snapshot.nodes[i] === index)
++count;
}
return count;
}
shouldBe(countOfNodesWithLabel("starDefault"), 1);
shouldBe(countOfNodesWithLabel("default") >= anonymous.length, true);
shouldBe(instances.length, 2);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default () => new Error().stack;
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default async function () {
await null;
return new Error().stack;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default async function* () {
await null;
yield new Error().stack;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
async function thrower() {
await null;
throw new Error();
}

export default async function () {
await thrower();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default class {
constructor() {
this.stack = new Error().stack;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default (class {
constructor() {
this.stack = new Error().stack;
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default class { }
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default class extends Object {
constructor() {
super();
return 1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default class extends Object { }
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function () {
return new Error().stack;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default (function () {
return new Error().stack;
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function* () {
yield new Error().stack;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function starDefault() {
return new Error().stack;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const notAFunction = 1;

export default () => notAFunction();
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//@ runBytecodeCache("--diskCachePayloadIsPersistentForTesting=1", "--useLazyModuleFunctionDeclarations=1")
//@ runBytecodeCache("--diskCachePayloadIsPersistentForTesting=1", "--useLazyModuleFunctionDeclarations=0")
//@ runBytecodeCache

// An anonymous default function declaration is bound to the private name "*default*", and its name is "default".
// A bytecode cache holds the name. A module that is made from the cache finds the binding of the declaration by it:
// when it makes its environment (useLazyModuleFunctionDeclarations off), or when the binding is first read.

function assert(condition, message) {
if (!condition)
throw new Error("assertion failed: " + message);
}

async function test() {
const module = await import("./resources/bytecode-cache-default-export-function-declaration-name.js");
const stack = module.default();
assert(stack.startsWith("default@"), "the frame: " + stack);
assert(module.default.name === "default", "the name: " + module.default.name);
}

test().then(() => { }, (e) => { print("FAIL: " + e + "\n" + e.stack); $vm.abort(); });
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function () {
return new Error().stack;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default (work) => work() + 1;
46 changes: 46 additions & 0 deletions JSTests/stress/sampling-profiler-default-export-name.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
if (platformSupportsSamplingProfiler()) {
load("./sampling-profiler/samplingProfiler.js", "caller relative");

// The DFG and the FTL inline the default export into caller(). A frame of an inlined function has no function object,
// so the profiler names it from its executable. An anonymous default export is named "default" there too.
let inlined;
import("./resources/sampling-profiler-default-export-name.js").then((module) => {
inlined = module.default;
});
drainMicrotasks();

function work() {
let sum = 0;
for (let i = 0; i < 1000; ++i)
sum += i % 7;
return sum;
}
noInline(work);

function caller() {
return inlined(work) + 1;
}
noInline(caller);

// Where the DFG cannot compile caller(), the frame has a function object and the name is read from it.
for (let i = 0; i < testLoopCount && !numberOfDFGCompiles(caller); ++i)
caller();
samplingProfilerStackTraces();

// A round has a few samples in work(). The fifth sample with the frame between work() and caller() ends the test.
let found = 0;
for (let round = 0; round < 100 && found < 5; ++round) {
for (let i = 0; i < 1000; ++i)
caller();
for (const trace of samplingProfilerStackTraces().traces) {
const index = trace.frames.findIndex((frame) => frame.name === "work");
if (index < 0 || !trace.frames[index + 2] || trace.frames[index + 2].name !== "caller")
continue;
if (trace.frames[index + 1].name !== "default")
throw new Error(`bad frame name: ${trace.frames.map((frame) => `${frame.name} (${frame.category})`).join(" < ")}`);
++found;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
if (!found)
throw new Error("no sample of the default export");
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
#include "SourceProfiler.h"
#include "Structure.h"
#include "UnlinkedFunctionCodeBlock.h"
#include "UnlinkedFunctionExecutableInlines.h"
#include <wtf/TZoneMallocInlines.h>

namespace JSC {
Expand Down Expand Up @@ -122,7 +123,7 @@ UnlinkedFunctionExecutable::UnlinkedFunctionExecutable(VM& vm, Structure* struct
, m_scalarsAreDeferred(false)
, m_unlinkedCodeBlockForCall()
, m_unlinkedCodeBlockForConstruct()
, m_ecmaName(node->ecmaName())
, m_ecmaName(nameFromSyntaxTree(vm, node->ecmaName()))
, m_members(WTF::move(parentScopeTDZVariables))
{
ASSERT(node->ident().isNull() || node->ident() == node->ecmaName());
Expand Down
13 changes: 6 additions & 7 deletions Source/JavaScriptCore/bytecode/UnlinkedFunctionExecutable.h
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ class UnlinkedFunctionExecutable final : public JSCell {
~UnlinkedFunctionExecutable();

const Identifier& name() const;
// The name of a function declaration of a module as the key of its binding. An anonymous default export is bound to
// the private name "*default*". Its name is "default", and that is the name this executable has.
inline const Identifier& bindingName(VM&) const;
const Identifier& ecmaName() const
{
if (m_nameIsDeferred) [[unlikely]]
Expand All @@ -109,13 +112,7 @@ class UnlinkedFunctionExecutable final : public JSCell {
return nullptr;
return &m_ecmaName;
}
void setEcmaName(const Identifier& name)
{
if (m_nameIsDeferred) [[unlikely]]
materializeDeferredNameSlow();
ASSERT(!m_hasName || name == m_ecmaName);
m_ecmaName = name;
}
inline void setEcmaName(VM&, const Identifier&);
unsigned parameterCount() const { return m_parameterCount; }; // Excluding 'this'!
SourceParseMode parseMode() const { return static_cast<SourceParseMode>(m_sourceParseMode); };

Expand Down Expand Up @@ -367,6 +364,8 @@ class UnlinkedFunctionExecutable final : public JSCell {

DECLARE_VISIT_CHILDREN;

static inline const Identifier& nameFromSyntaxTree(VM&, const Identifier&);

void decodeCachedCodeBlocks(VM&);
JS_EXPORT_PRIVATE void materializeDeferredNameSlow() const;
JS_EXPORT_PRIVATE String ecmaNameWithoutGCSlow() const;
Expand Down
33 changes: 33 additions & 0 deletions Source/JavaScriptCore/bytecode/UnlinkedFunctionExecutableInlines.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@

#pragma once

#include "BuiltinNames.h"
#include "CommonIdentifiers.h"
#include "StructureCreateInlines.h"
#include "UnlinkedFunctionExecutable.h"
#include "VM.h"

namespace JSC {

Expand All @@ -35,4 +38,34 @@ inline Structure* UnlinkedFunctionExecutable::createStructure(VM& vm, JSGlobalOb
return Structure::create(vm, globalObject, proto, TypeInfo(UnlinkedFunctionExecutableType, StructureFlags), info());
}

// https://tc39.es/ecma262/#sec-exports-runtime-semantics-evaluation
// The parser binds an anonymous default export to the private name "*default*" and gives the function or class the name
// of that binding. SetFunctionName gives it the name "default".
inline const Identifier& UnlinkedFunctionExecutable::nameFromSyntaxTree(VM& vm, const Identifier& nameInSyntaxTree)
{
// Every function gets here. The private name is one object for all VMs, so the compare is with a constant address.
if (nameInSyntaxTree.impl() == std::bit_cast<SymbolImpl*>(&Symbols::starDefaultPrivateName)) [[unlikely]]
return vm.propertyNames->defaultKeyword;
return nameInSyntaxTree;
}

inline const Identifier& UnlinkedFunctionExecutable::bindingName(VM& vm) const
{
ASSERT(m_hasName);
const Identifier& name = ecmaName();
// No declaration is written with the name "default": it is a reserved word.
if (name == vm.propertyNames->defaultKeyword) [[unlikely]]
return vm.propertyNames->starDefaultPrivateName;
return name;
}

inline void UnlinkedFunctionExecutable::setEcmaName(VM& vm, const Identifier& nameInSyntaxTree)
{
if (m_nameIsDeferred) [[unlikely]]
materializeDeferredNameSlow();
const Identifier& name = nameFromSyntaxTree(vm, nameInSyntaxTree);
ASSERT(!m_hasName || name == m_ecmaName);
m_ecmaName = name;
}

} // namespace JSC
3 changes: 2 additions & 1 deletion Source/JavaScriptCore/bytecompiler/BytecodeGenerator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
#include "UnlinkedCodeBlock.h"
#include "UnlinkedEvalCodeBlock.h"
#include "UnlinkedFunctionCodeBlock.h"
#include "UnlinkedFunctionExecutableInlines.h"
#include "UnlinkedMetadataTableInlines.h"
#include "UnlinkedModuleProgramCodeBlock.h"
#include "UnlinkedProgramCodeBlock.h"
Expand Down Expand Up @@ -3824,7 +3825,7 @@ RegisterID* BytecodeGenerator::emitNewDefaultConstructor(RegisterID* dst, Constr
const Identifier& ecmaName, const SourceCode& classSource, NeedsClassFieldInitializer needsClassFieldInitializer, PrivateBrandRequirement privateBrandRequirement)
{
UnlinkedFunctionExecutable* executable = m_vm.builtinExecutables()->createDefaultConstructor(constructorKind, name, needsClassFieldInitializer, privateBrandRequirement);
executable->setEcmaName(ecmaName);
executable->setEcmaName(m_vm, ecmaName);
executable->setClassSource(classSource);

unsigned index = m_codeBlock->addFunctionExpr(executable);
Expand Down
3 changes: 2 additions & 1 deletion Source/JavaScriptCore/runtime/CachedTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5329,7 +5329,8 @@ class GenericCacheEntry {
// keep a String's iteration state in their registers too (321765@main, 322172@main; opcode numbering).
// 14: op_profile_control_flow says whether its basic block is in a loop header.
// 15: upstream's op_call_varargs_with_spread (325231@main; opcode numbering).
static constexpr uint32_t cachedTypesFormatRevision = 15;
// 16: an anonymous default export has the name "default", not the private name "*default*".
static constexpr uint32_t cachedTypesFormatRevision = 16;
static uint32_t currentCacheVersion() { return computeJSCBytecodeCacheVersion() ^ (cachedTypesFormatRevision * 0x9E3779B9u); }

GenericCacheEntry(Encoder& encoder, CachedCodeBlockTag tag)
Expand Down
Loading
Loading