Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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
105 changes: 56 additions & 49 deletions src/jsc/bindings/ErrorStackFrame.cpp
Original file line number Diff line number Diff line change
@@ -1,65 +1,59 @@
#include "root.h"
#include "ErrorStackFrame.h"
#include "JavaScriptCore/CodeBlock.h"
#include "headers-handwritten.h"
#include "JavaScriptCore/BytecodeIndex.h"
#include "wtf/Assertions.h"
#include "JavaScriptCore/StackFrame.h"
#include "wtf/text/OrdinalNumber.h"

namespace Bun {
using namespace JSC;

/// Adjust a `ZigStackFramePosition` by a number of bytes. This accounts for when the adjustment
/// crosses line boundaries, and thus requires the source code in order to properly compute
/// the result.
void adjustPositionBackwards(ZigStackFramePosition& pos, int amount, CodeBlock* code)
// The LineTerminator set JSC's lexer counts lines with (LF, CR, U+2028, U+2029).
static bool isLineTerminator(char16_t c)
{
if (pos.byte_position - amount < 0) {
pos.line_zero_based = 0;
pos.column_zero_based = 0;
pos.byte_position = 0;
return c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029;
}

/// Moves the divot in `pos` back `amount` code units, recounting line/column when that crosses a line break.
static void adjustPositionBackwards(ZigStackFramePosition& pos, int amount, CodeBlock* code)
{
if (amount <= 0 || pos.byte_position < amount)
return;

int start = pos.byte_position - amount;

if (pos.column_zero_based >= amount) {
pos.column_zero_based -= amount;
pos.byte_position = start;
return;
}

pos.column_zero_based = pos.column_zero_based - amount;
if (pos.column_zero_based < 0) {
auto* provider = code->source().provider();
if (!provider) {
pos.line_zero_based = 0;
pos.column_zero_based = 0;
pos.byte_position = 0;
return;
}

auto source = provider->source();
if (!source.is8Bit()) {
// Debug-only assertion
// Bun does not yet use 16-bit sources anywhere. The transpiler ensures everything
// fit's into latin1 / 8-bit strings for on-average lower memory usage.
ASSERT_NOT_REACHED("16-bit source re-mapping is not implemented here.");

pos.line_zero_based = 0;
pos.column_zero_based = 0;
pos.byte_position = 0;
return;
}

for (int i = 0; i < amount; i++) {
if (source[pos.byte_position - i] == '\n') {
pos.line_zero_based = pos.line_zero_based - 1;
}
}

int columns = 0;
// Initial -1 to skip the newline that gets counted.
int i = pos.byte_position - amount - 1;
while (i > 0 && source[i] != '\n') {
columns += 1;
i -= 1;
}
pos.column_zero_based = columns;
auto* provider = code->source().provider();
if (!provider)
return;

// Untranspiled sources (eval, new Function, node:vm) can be 16-bit; indexing handles both.
WTF::StringView source = provider->source();
if (static_cast<unsigned>(pos.byte_position) > source.length())
return;

for (int i = start; i < pos.byte_position; i++) {
if (!isLineTerminator(source[i]))
continue;
pos.line_zero_based--;
if (source[i] == '\r' && i + 1 < pos.byte_position && source[i + 1] == '\n')
i++;
}

pos.byte_position -= amount;
int column = 0;
int i = start - 1;
for (; i >= 0 && !isLineTerminator(source[i]); i--)
column++;
Comment thread
claude[bot] marked this conversation as resolved.
// JSC's columns on the first line of a source include its start column (node:vm columnOffset).
if (i < 0)
column += provider->startPosition().m_column.zeroBasedInt();

pos.column_zero_based = column;
pos.byte_position = start;
Comment thread
claude[bot] marked this conversation as resolved.
}

ZigStackFramePosition getAdjustedPositionForBytecode(JSC::CodeBlock* code, JSC::BytecodeIndex bc)
Expand Down Expand Up @@ -98,4 +92,17 @@ ZigStackFramePosition getAdjustedPositionForBytecode(JSC::CodeBlock* code, JSC::
return pos;
}

ZigStackFramePosition getAdjustedPositionForStackFrame(const JSC::StackFrame& frame)
{
if (!frame.hasLineAndColumnInfo() || !frame.hasBytecodeIndex()) {
return ZigStackFramePosition {
.line_zero_based = -1,
.column_zero_based = -1,
.byte_position = -1,
};
}

return getAdjustedPositionForBytecode(frame.codeBlock(), frame.bytecodeIndex());
}

} // namespace Bun
11 changes: 11 additions & 0 deletions src/jsc/bindings/ErrorStackFrame.h
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
#pragma once

#include "root.h"
#include "headers-handwritten.h"
#include "JavaScriptCore/BytecodeIndex.h"

namespace JSC {
class CodeBlock;
class StackFrame;
}

namespace Bun {

/// Position of the bytecode at `bc` where V8 would report it: `new X(...)` at `new`, not after `X`.
ZigStackFramePosition getAdjustedPositionForBytecode(JSC::CodeBlock* code, JSC::BytecodeIndex bc);

/// Same for a captured frame. Frames without a code block get -1 in every field (invalid position).
ZigStackFramePosition getAdjustedPositionForStackFrame(const JSC::StackFrame& frame);

} // namespace Bun
30 changes: 15 additions & 15 deletions src/jsc/bindings/FormatStackTraceForJS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

#include "BunClientData.h"
#include "CallSite.h"
#include "ErrorStackFrame.h"
#include "ErrorStackTrace.h"
#include "headers-handwritten.h"

Expand Down Expand Up @@ -243,11 +244,11 @@ WTF::String formatStackTrace(
// file's map once instead of per frame.
WTF::Vector<ZigStackFrame, 8> remappedFrames;
WTF::Vector<WTF::String, 8> sourceURLs;
WTF::Vector<LineColumn, 8> originalLineColumns;
WTF::Vector<ZigStackFramePosition, 8> originalPositions;
remappedFrames.grow(framesCount);
memset(remappedFrames.begin(), 0, sizeof(ZigStackFrame) * framesCount);
sourceURLs.grow(framesCount);
originalLineColumns.grow(framesCount);
originalPositions.grow(framesCount);
bool anyRemap = false;

for (size_t i = 0; i < framesCount; i++) {
Expand All @@ -260,11 +261,12 @@ WTF::String formatStackTrace(
remappedFrame.position.line_zero_based = -1;
remappedFrame.position.column_zero_based = -1;
remappedFrame.position.byte_position = -1;
originalLineColumns[i] = {};
originalPositions[i] = remappedFrame.position;

if (!frame.hasLineAndColumnInfo()) continue;

originalLineColumns[i] = frame.computeLineAndColumn();
// Same position as Bun.inspect and CallSite; source maps have a mapping at `new`, not at JSC's divot.
originalPositions[i] = Bun::getAdjustedPositionForStackFrame(frame);
Comment thread
claude[bot] marked this conversation as resolved.
Outdated

JSC::JSGlobalObject* globalObjectForFrame = lexicalGlobalObject;
if (auto* callee = frame.callee()) {
Expand All @@ -280,8 +282,7 @@ WTF::String formatStackTrace(
if (isDefinitelyNotRunninginNodeVMGlobalObject || isDefaultGlobalObjectInAFinalizer) {
// https://github.com/oven-sh/bun/issues/3595
if (!sourceURLs[i].isEmpty()) {
remappedFrame.position.line_zero_based = OrdinalNumber::fromOneBasedInt(originalLineColumns[i].line).zeroBasedInt();
remappedFrame.position.column_zero_based = OrdinalNumber::fromOneBasedInt(originalLineColumns[i].column).zeroBasedInt();
remappedFrame.position = originalPositions[i];
remappedFrame.source_url = Bun::toStringRef(sourceURLs[i]);
anyRemap = true;
}
Expand Down Expand Up @@ -314,10 +315,12 @@ WTF::String formatStackTrace(
OrdinalNumber displayLine = {};
OrdinalNumber displayColumn = {};
WTF::String sourceURLForFrame = sourceURLs[i];
// Still -1 for the frames pass 1 skipped (no code block) or could not position.
bool hasPosition = originalPositions[i].line_zero_based >= 0;

if (frame.hasLineAndColumnInfo()) {
originalLine = OrdinalNumber::fromOneBasedInt(originalLineColumns[i].line);
originalColumn = OrdinalNumber::fromOneBasedInt(originalLineColumns[i].column);
if (hasPosition) {
originalLine = originalPositions[i].line();
originalColumn = originalPositions[i].column();
displayLine = originalLine;
displayColumn = originalColumn;

Expand Down Expand Up @@ -370,14 +373,11 @@ WTF::String formatStackTrace(

if (!sourceURLForFrame.isEmpty()) {
sb.append(sourceURLForFrame);
if (displayLine.zeroBasedInt() > 0 || displayColumn.zeroBasedInt() > 0) {
if (hasPosition) {
sb.append(':');
sb.append(displayLine.oneBasedInt());

if (displayColumn.zeroBasedInt() > 0) {
sb.append(':');
sb.append(displayColumn.oneBasedInt());
}
sb.append(':');
sb.append(displayColumn.oneBasedInt());
}
}

Expand Down
17 changes: 3 additions & 14 deletions src/jsc/bindings/ZigException.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -144,20 +144,9 @@ static void populateStackFramePosition(const JSC::StackFrame& stackFrame, BunStr
if (sourceString.isNull()) [[unlikely]]
return;

if (!stackFrame.hasBytecodeIndex()) {
if (stackFrame.hasLineAndColumnInfo()) {
auto lineColumn = stackFrame.computeLineAndColumn();
position.line_zero_based = OrdinalNumber::fromOneBasedInt(lineColumn.line).zeroBasedInt();
position.column_zero_based = OrdinalNumber::fromOneBasedInt(lineColumn.column).zeroBasedInt();
}

position.byte_position = -1;
return;
}

auto location = Bun::getAdjustedPositionForBytecode(code, stackFrame.bytecodeIndex());
memcpy(&position, &location, sizeof(ZigStackFramePosition));
if (flags == PopulateStackTraceFlags::OnlyPosition)
auto location = Bun::getAdjustedPositionForStackFrame(stackFrame);
position = location;
if (flags == PopulateStackTraceFlags::OnlyPosition || location.byte_position < 0)
return;

if (source_lines_count > 1 && source_lines != nullptr && sourceString.is8Bit()) {
Expand Down
4 changes: 3 additions & 1 deletion test/bake/dev/server-sourcemap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ export async function getStaticPaths() {
// Strip ANSI codes for cleaner checking
const cleanLines = lines.replace(/\x1b\[[0-9;]*m/g, "");

const hasCorrectThrowLine = cleanLines.includes("myFunc") && cleanLines.includes("6:16");
// Frames remap to the declaration position here, like the `throwError`/`6:1`
// and `helperFunction`/`5:1` expectations below.
const hasCorrectThrowLine = /at myFunc \(.*pages[/\\]\[\.\.\.slug\]\.tsx:6:1\)/.test(cleanLines);
// const hasCorrectCallLine = cleanLines.includes("MyPage") && cleanLines.includes("2") && cleanLines.includes("3");
const hasCorrectFileName = cleanLines.includes("pages/[...slug].tsx");

Expand Down
Loading