fix errors

Former-commit-id: ac66d6af52f6a2340c57a957bed078f94a8cf8ed
This commit is contained in:
Jarred Sumner
2021-08-02 21:22:58 -07:00
parent b6e19438ea
commit dbda84ff87
18 changed files with 1352 additions and 936 deletions

View File

@@ -1,8 +1,8 @@
const generic = opaque {};
pub const Private = c_void;
pub const struct_OpaqueJSContextGroup = opaque {};
pub const struct_OpaqueJSContextGroup = generic;
pub const JSContextGroupRef = ?*const struct_OpaqueJSContextGroup;
pub const struct_OpaqueJSContext = opaque {};
pub const struct_OpaqueJSContext = generic;
pub const JSContextRef = ?*const struct_OpaqueJSContext;
pub const JSGlobalContextRef = ?*struct_OpaqueJSContext;
pub const struct_OpaqueJSString = generic;
@@ -18,7 +18,7 @@ pub const JSPropertyNameArrayRef = ?*struct_OpaqueJSPropertyNameArray;
pub const struct_OpaqueJSPropertyNameAccumulator = generic;
pub const JSPropertyNameAccumulatorRef = ?*struct_OpaqueJSPropertyNameAccumulator;
pub const JSTypedArrayBytesDeallocator = ?fn (?*c_void, ?*c_void) callconv(.C) void;
pub const OpaqueJSValue = opaque {};
pub const OpaqueJSValue = generic;
pub const JSValueRef = ?*OpaqueJSValue;
pub const JSObjectRef = ?*OpaqueJSValue;
pub extern fn JSEvaluateScript(ctx: JSContextRef, script: JSStringRef, thisObject: JSObjectRef, sourceURL: JSStringRef, startingLineNumber: c_int, exception: ExceptionRef) JSValueRef;
@@ -291,10 +291,13 @@ pub const Encoding = enum(u8) {
};
pub const JSCellValue = u64;
pub const CellType = enum(u8) {
pub const LastMaybeFalsyCellPrimitive = 2;
pub const LastJSCObjectType = 73;
CellType = 0,
StringType = 1,
HeapBigIntType = 2,
LastMaybeFalsyCellPrimitive = 2,
SymbolType = 3,
GetterSetterType = 4,
CustomGetterSetterType = 5,
@@ -366,7 +369,7 @@ pub const CellType = enum(u8) {
WebAssemblyModuleType = 71,
StringObjectType = 72,
DerivedStringObjectType = 73,
LastJSCObjectType = 73,
MaxJSType = 255,
_,

View File

@@ -42,7 +42,6 @@ pub const To = struct {
comptime ZigContextType: type,
comptime ctxfn: fn (
this: *ZigContextType,
object: js.JSObjectRef,
) void,
) type {
return struct {
@@ -783,16 +782,28 @@ pub fn NewClass(
return ClassGetter;
}
pub fn customHasInstance(ctx: js.JSContextRef, obj: js.JSObjectRef, value: js.JSValueRef, exception: ExceptionRef) callconv(.C) bool {
return js.JSValueIsObjectOfClass(ctx, obj, get().*);
pub fn customHasInstance(ctx: js.JSContextRef, obj: js.JSObjectRef, value: js.JSValueRef, exception: js.ExceptionRef) callconv(.C) bool {
return js.JSValueIsObjectOfClass(ctx, value, get().*);
}
pub fn make(ctx: js.JSContextRef, ptr: *ZigType) callconv(.C) js.JSObjectRef {
return js.JSObjectMake(
pub fn make(ctx: js.JSContextRef, ptr: *ZigType) js.JSObjectRef {
var real_ptr = JSPrivateDataPtr.init(ptr).ptr();
if (comptime isDebug) {
std.debug.assert(JSPrivateDataPtr.isValidPtr(real_ptr));
std.debug.assert(JSPrivateDataPtr.from(real_ptr).get(ZigType).? == ptr);
}
var result = js.JSObjectMake(
ctx,
get().*,
JSPrivateDataPtr.init(ptr).ptr(),
real_ptr,
);
if (comptime isDebug) {
std.debug.assert(JSPrivateDataPtr.from(js.JSObjectGetPrivate(result)).ptr() == real_ptr);
}
return result;
}
pub fn GetClass(comptime ReceiverType: type) type {
const ClassGetter = struct {
@@ -1274,7 +1285,11 @@ pub fn NewClass(
def.callAsFunction = callback;
} else {
const ctxfn = @field(staticFunctions, function_names[i]).rfn;
const CtxField = @field(staticFunctions, function_names[i]);
if (comptime !@hasField(@TypeOf(CtxField), "rfn")) {
@compileError("Expected " ++ options.name ++ "." ++ function_names[i] ++ " to have .rfn");
}
const ctxfn = CtxField.rfn;
const Func: std.builtin.TypeInfo.Fn = @typeInfo(@TypeOf(ctxfn)).Fn;
const PointerType = std.meta.Child(Func.args[0].arg_type.?);

View File

@@ -139,9 +139,11 @@ void GlobalObject::installAPIGlobals(JSClassRef *globals, int count) {
JSC::Identifier GlobalObject::moduleLoaderResolve(JSGlobalObject *globalObject,
JSModuleLoader *loader, JSValue key,
JSValue referrer, JSValue origin) {
auto res = Zig__GlobalObject__resolve(globalObject, toZigString(key, globalObject),
referrer.isString() ? toZigString(referrer, globalObject)
: ZigStringEmpty);
ErrorableZigString res;
res.success = false;
Zig__GlobalObject__resolve(&res, globalObject, toZigString(key, globalObject),
referrer.isString() ? toZigString(referrer, globalObject)
: ZigStringEmpty);
if (res.success) {
return toIdentifier(res.result.value, globalObject);
@@ -164,9 +166,11 @@ JSC::JSInternalPromise *GlobalObject::moduleLoaderImportModule(JSGlobalObject *g
RETURN_IF_EXCEPTION(scope, promise->rejectWithCaughtException(globalObject, scope));
auto sourceURL = sourceOrigin.url();
auto resolved = Zig__GlobalObject__resolve(
globalObject, toZigString(moduleNameValue, globalObject),
sourceURL.isEmpty() ? ZigStringCwd : toZigString(sourceURL.fileSystemPath()));
ErrorableZigString resolved;
resolved.success = false;
Zig__GlobalObject__resolve(&resolved, globalObject, toZigString(moduleNameValue, globalObject),
sourceURL.isEmpty() ? ZigStringCwd
: toZigString(sourceURL.fileSystemPath()));
if (!resolved.success) {
throwException(scope, resolved.result.err, globalObject);
return promise->rejectWithCaughtException(globalObject, scope);
@@ -201,7 +205,8 @@ JSC::JSInternalPromise *GlobalObject::moduleLoaderFetch(JSGlobalObject *globalOb
res.result.err.code = 0;
res.result.err.ptr = nullptr;
Zig__GlobalObject__fetch(&res, globalObject, moduleKeyZig, ZigStringEmpty);
Zig__GlobalObject__fetch(&res, globalObject, moduleKeyZig,
Zig::toZigString(value1, globalObject));
if (!res.success) {
throwException(scope, res.result.err, globalObject);

View File

@@ -8,6 +8,7 @@
#include <JavaScriptCore/ExceptionScope.h>
#include <JavaScriptCore/FunctionConstructor.h>
#include <JavaScriptCore/Identifier.h>
#include <JavaScriptCore/IteratorOperations.h>
#include <JavaScriptCore/JSArray.h>
#include <JavaScriptCore/JSCInlines.h>
#include <JavaScriptCore/JSCallbackObject.h>
@@ -33,12 +34,40 @@
#include <wtf/text/WTFString.h>
extern "C" {
#pragma mark - JSC::Exception
JSC__Exception *JSC__Exception__create(JSC__JSGlobalObject *arg0, JSC__JSObject *arg1,
unsigned char StackCaptureAction2) {
return JSC::Exception::create(arg0->vm(), JSC::JSValue(arg1),
StackCaptureAction2 == 0
? JSC::Exception::StackCaptureAction::CaptureStack
: JSC::Exception::StackCaptureAction::DoNotCaptureStack);
}
JSC__JSValue JSC__Exception__value(JSC__Exception *arg0) {
return JSC::JSValue::encode(arg0->value());
}
// #pragma mark - JSC::PropertyNameArray
// CPP_DECL size_t JSC__PropertyNameArray__length(JSC__PropertyNameArray* arg0);
// CPP_DECL const JSC__PropertyName*
// JSC__PropertyNameArray__next(JSC__PropertyNameArray* arg0, size_t arg1);
// CPP_DECL void JSC__PropertyNameArray__release(JSC__PropertyNameArray* arg0);
size_t JSC__JSObject__getArrayLength(JSC__JSObject *arg0) { return arg0->getArrayLength(); }
JSC__JSValue JSC__JSObject__getIndex(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1,
uint32_t arg3) {
return JSC::JSValue::encode(arg0->getIndex(arg1, arg3));
}
JSC__JSValue JSC__JSObject__getDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1,
ZigString arg2) {
return JSC::JSValue::encode(arg0->getDirect(arg1->vm(), Zig::toIdentifier(arg2, arg1)));
}
void JSC__JSObject__putDirect(JSC__JSObject *arg0, JSC__JSGlobalObject *arg1, ZigString key,
JSC__JSValue value) {
auto prop = Zig::toIdentifier(key, arg1);
arg0->putDirect(arg1->vm(), prop, JSC::JSValue::decode(value));
}
#pragma mark - JSC::JSCell
@@ -138,7 +167,7 @@ static JSC::JSValue doLink(JSC__JSGlobalObject *globalObject, JSC::JSValue modul
}
JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *globalObject,
JSC__JSValue *errors, uint16_t errors_count,
void **errors, uint16_t errors_count,
ZigString arg3) {
JSC::VM &vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -154,8 +183,8 @@ JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *glob
errors_count))) {
for (uint16_t i = 0; i < errors_count; ++i) {
array->initializeIndexWithoutBarrier(initializationScope, i,
JSC::JSValue::decode(errors[i]));
array->initializeIndexWithoutBarrier(
initializationScope, i, JSC::JSValue(reinterpret_cast<JSC::JSCell *>(errors[i])));
}
}
}
@@ -165,9 +194,10 @@ JSC__JSValue JSC__JSGlobalObject__createAggregateError(JSC__JSGlobalObject *glob
}
JSC::Structure *errorStructure = globalObject->errorStructure(JSC::ErrorType::AggregateError);
return RELEASE_AND_RETURN(scope, JSC::JSValue::encode(JSC::createAggregateError(
globalObject, vm, errorStructure, array, message, options,
nullptr, JSC::TypeNothing, false)));
scope.release();
return JSC::JSValue::encode(JSC::createAggregateError(
globalObject, vm, errorStructure, array, message, options, nullptr, JSC::TypeNothing, false));
}
// static JSC::JSNativeStdFunction* resolverFunction;
// static JSC::JSNativeStdFunction* rejecterFunction;
@@ -177,6 +207,21 @@ JSC__JSValue ZigString__toValue(ZigString arg0, JSC__JSGlobalObject *arg1) {
return JSC::JSValue::encode(JSC::JSValue(JSC::jsOwnedString(arg1->vm(), Zig::toString(arg0))));
}
JSC__JSValue ZigString__toErrorInstance(const ZigString *str, JSC__JSGlobalObject *globalObject) {
JSC::VM &vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSC::JSValue message = Zig::toJSString(*str, globalObject);
JSC::JSValue options = JSC::jsUndefined();
JSC::Structure *errorStructure = globalObject->errorStructure();
JSC::JSObject *result =
JSC::ErrorInstance::create(globalObject, errorStructure, message, options);
RETURN_IF_EXCEPTION(scope, JSC::JSValue::encode(JSC::JSValue()));
scope.release();
return JSC::JSValue::encode(JSC::JSValue(result));
}
static JSC::EncodedJSValue resolverFunctionCallback(JSC::JSGlobalObject *globalObject,
JSC::CallFrame *callFrame) {
return JSC::JSValue::encode(doLink(globalObject, callFrame->argument(0)));
@@ -638,6 +683,33 @@ bool JSC__JSValue__isError(JSC__JSValue JSValue0) {
JSC::JSObject *obj = JSC::JSValue::decode(JSValue0).getObject();
return obj != nullptr && obj->isErrorInstance();
}
bool JSC__JSValue__isAggregateError(JSC__JSValue JSValue0, JSC__JSGlobalObject *global) {
JSC::JSObject *obj = JSC::JSValue::decode(JSValue0).getObject();
if (obj != nullptr) {
if (JSC::ErrorInstance *err = JSC::jsDynamicCast<JSC::ErrorInstance *>(global->vm(), obj)) {
return err->errorType() == JSC::ErrorType::AggregateError;
}
}
return false;
}
bool JSC__JSValue__isIterable(JSC__JSValue JSValue, JSC__JSGlobalObject *global) {
return JSC::hasIteratorMethod(global, JSC::JSValue::decode(JSValue));
}
void JSC__JSValue__forEach(JSC__JSValue JSValue0, JSC__JSGlobalObject *arg1,
void (*ArgFn2)(JSC__VM *arg0, JSC__JSGlobalObject *arg1,
JSC__JSValue JSValue2)) {
JSC::forEachInIterable(
arg1, JSC::JSValue::decode(JSValue0),
[ArgFn2](JSC::VM &vm, JSC::JSGlobalObject *global, JSC::JSValue value) -> void {
ArgFn2(&vm, global, JSC::JSValue::encode(value));
});
}
bool JSC__JSValue__isCallable(JSC__JSValue JSValue0, JSC__VM *arg1) {
return JSC::JSValue::decode(JSValue0).isCallable(reinterpret_cast<JSC::VM &>(arg1));
}
@@ -647,6 +719,9 @@ bool JSC__JSValue__isGetterSetter(JSC__JSValue JSValue0) {
bool JSC__JSValue__isHeapBigInt(JSC__JSValue JSValue0) {
return JSC::JSValue::decode(JSValue0).isHeapBigInt();
}
bool JSC__JSValue__isInt32(JSC__JSValue JSValue0) {
return JSC::JSValue::decode(JSValue0).isInt32();
}
bool JSC__JSValue__isInt32AsAnyInt(JSC__JSValue JSValue0) {
return JSC::JSValue::decode(JSValue0).isInt32AsAnyInt();
}
@@ -700,6 +775,19 @@ JSC__JSValue JSC__JSValue__jsNumberFromU16(uint16_t arg0) {
JSC__JSValue JSC__JSValue__jsNumberFromUint64(uint64_t arg0) {
return JSC::JSValue::encode(JSC::jsNumber(arg0));
};
bool JSC__JSValue__toBoolean(JSC__JSValue JSValue0) {
return JSC::JSValue::decode(JSValue0).asBoolean();
}
int32_t JSC__JSValue__toInt32(JSC__JSValue JSValue0) {
return JSC::JSValue::decode(JSValue0).asInt32();
}
JSC__JSValue JSC__JSValue__getErrorsProperty(JSC__JSValue JSValue0, JSC__JSGlobalObject *global) {
JSC::JSObject *obj = JSC::JSValue::decode(JSValue0).getObject();
return JSC::JSValue::encode(obj->getDirect(global->vm(), global->vm().propertyNames->errors));
}
JSC__JSValue JSC__JSValue__jsTDZValue() { return JSC::JSValue::encode(JSC::jsTDZValue()); };
JSC__JSValue JSC__JSValue__jsUndefined() { return JSC::JSValue::encode(JSC::jsUndefined()); };
JSC__JSObject *JSC__JSValue__toObject(JSC__JSValue JSValue0, JSC__JSGlobalObject *arg1) {
@@ -1045,6 +1133,11 @@ void JSC__JSValue__toZigException(JSC__JSValue JSValue0, JSC__JSGlobalObject *ar
exceptionFromString(exception, value, arg1);
}
void JSC__Exception__getStackTrace(JSC__Exception *arg0, ZigStackTrace *trace) {
populateStackTrace(arg0->stack(), trace);
}
#pragma mark - JSC::PropertyName
bool JSC__PropertyName__eqlToIdentifier(JSC__PropertyName *arg0, const JSC__Identifier *arg1) {

View File

@@ -12,36 +12,53 @@ pub const JSObject = extern struct {
pub const name = "JSC::JSObject";
pub const namespace = "JSC";
pub extern "c" fn putAtIndex(this: *JSObject, globalThis: *JSGlobalObject, property_name: *PropertyName, i: u32) bool;
pub fn getArrayLength(this: *JSObject) usize {
return cppFn("getArrayLength", .{
this,
});
}
pub fn getAtIndex(this: *JSObject, globalThis: *JSGlobalObject, property_name: *PropertyName, i: u32) JSValue {
return cppFn("getAtIndex", .{
pub fn getIndex(this: *JSObject, globalThis: *JSGlobalObject, i: u32) JSValue {
return cppFn("getIndex", .{
this,
property_name,
globalThis,
i,
});
}
pub fn getDirect(this: *JSObject, globalThis: *JSGlobalObject, str: ZigString) JSValue {
return cppFn("getDirect", .{
this,
globalThis,
str,
});
}
pub fn putDirect(this: *JSObject, globalThis: *JSGlobalObject, prop: ZigString, value: JSValue) void {
return cppFn("putDirect", .{
this,
globalThis,
prop,
value,
});
}
pub const Extern = [_][]const u8{
"getArrayLength",
"getAtIndex",
"getIndex",
"putAtIndex",
"getDirect",
"putDirect",
};
};
pub const ZigString = extern struct {
ptr: [*]const u8,
len: usize,
pub const shim = Shimmer("Zig", "ZigString", @This());
pub const shim = Shimmer("", "ZigString", @This());
pub const name = "ZigString";
pub const namespace = "Zig";
pub const namespace = "";
pub fn init(slice_: []const u8) ZigString {
return ZigString{ .ptr = slice_.ptr, .len = slice_.len };
@@ -61,8 +78,13 @@ pub const ZigString = extern struct {
return C_API.JSStringCreateStatic(this.ptr, this.len);
}
pub fn toErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue {
return shim.cppFn("toErrorInstance", .{ this, global });
}
pub const Extern = [_][]const u8{
"toValue",
"toErrorInstance",
};
};
@@ -189,24 +211,28 @@ pub const ScriptArguments = extern struct {
pub fn NewGlobalObject(comptime Type: type) type {
return struct {
const importNotImpl = "Import not implemented";
const resolveNotImpl = "resolve not implemented";
const moduleNotImpl = "Module fetch not implemented";
pub fn import(global: *JSGlobalObject, specifier: ZigString, source: ZigString) callconv(.C) ErrorableZigString {
if (comptime @hasDecl(Type, "import")) {
return @call(.{ .modifier = .always_inline }, Type.import, .{ global, specifier, source });
}
return ErrorableZigString.err(error.ImportFailed, "Import not implemented");
return ErrorableZigString.err(error.ImportFailed, ZigString.init(importNotImpl).toErrorInstance(global).asVoid());
}
pub fn resolve(global: *JSGlobalObject, specifier: ZigString, source: ZigString) callconv(.C) ErrorableZigString {
pub fn resolve(res: *ErrorableZigString, global: *JSGlobalObject, specifier: ZigString, source: ZigString) callconv(.C) void {
if (comptime @hasDecl(Type, "resolve")) {
return @call(.{ .modifier = .always_inline }, Type.resolve, .{ global, specifier, source });
@call(.{ .modifier = .always_inline }, Type.resolve, .{ res, global, specifier, source });
return;
}
return ErrorableZigString.err(error.ResolveFailed, "resolve not implemented");
res.* = ErrorableZigString.err(error.ResolveFailed, ZigString.init(resolveNotImpl).toErrorInstance(global).asVoid());
}
pub fn fetch(ret: *ErrorableResolvedSource, global: *JSGlobalObject, specifier: ZigString, source: ZigString) callconv(.C) void {
if (comptime @hasDecl(Type, "fetch")) {
@call(.{ .modifier = .always_inline }, Type.fetch, .{ ret, global, specifier, source });
return;
}
ret.* = ErrorableResolvedSource.err(error.FetchFailed, "Module fetch not implemented");
ret.* = ErrorableResolvedSource.err(error.FetchFailed, ZigString.init(moduleNotImpl).toErrorInstance(global).asVoid());
}
pub fn promiseRejectionTracker(global: *JSGlobalObject, promise: *JSPromise, rejection: JSPromiseRejectionOperation) callconv(.C) JSValue {
if (comptime @hasDecl(Type, "promiseRejectionTracker")) {
@@ -721,6 +747,11 @@ pub const JSGlobalObject = extern struct {
const cppFn = shim.cppFn;
pub fn ref(this: *JSGlobalObject) C_API.JSContextRef {
return @ptrCast(C_API.JSContextRef, this);
}
pub const ctx = ref;
pub fn objectPrototype(this: *JSGlobalObject) *ObjectPrototype {
return cppFn("objectPrototype", .{this});
}
@@ -794,7 +825,7 @@ pub const JSGlobalObject = extern struct {
return cppFn("asyncGeneratorFunctionPrototype", .{this});
}
pub fn createAggregateError(globalObject: *JSGlobalObject, errors: [*]JSValue, errors_len: u16, message: ZigString) JSValue {
pub fn createAggregateError(globalObject: *JSGlobalObject, errors: [*]*c_void, errors_len: u16, message: ZigString) JSValue {
return cppFn("createAggregateError", .{ globalObject, errors, errors_len, message });
}
@@ -1070,6 +1101,13 @@ pub const JSValue = enum(i64) {
pub const name = "JSC::JSValue";
pub const namespace = "JSC";
pub inline fn cast(ptr: anytype) JSValue {
return @intToEnum(JSValue, @intCast(i64, @ptrToInt(ptr)));
}
pub fn getErrorsProperty(this: JSValue, globalObject: *JSGlobalObject) JSValue {
return cppFn("getErrorsProperty", .{ this, globalObject });
}
pub fn jsNumber(number: anytype) JSValue {
return switch (@TypeOf(number)) {
f64 => @call(.{ .modifier = .always_inline }, jsNumberFromDouble, .{number}),
@@ -1136,6 +1174,9 @@ pub const JSValue = enum(i64) {
pub fn isUInt32AsAnyInt(this: JSValue) bool {
return cppFn("isUInt32AsAnyInt", .{this});
}
pub fn isInt32(this: JSValue) bool {
return cppFn("isInt32", .{this});
}
pub fn isInt32AsAnyInt(this: JSValue) bool {
return cppFn("isInt32AsAnyInt", .{this});
}
@@ -1246,7 +1287,42 @@ pub const JSValue = enum(i64) {
});
}
pub const Extern = [_][]const u8{ "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "get", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isUndefined", "isNull", "isUndefinedOrNull", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" };
pub fn toBoolean(this: JSValue) bool {
return cppFn("toBoolean", .{
this,
});
}
pub fn toInt32(this: JSValue) i32 {
return cppFn("toInt32", .{
this,
});
}
pub fn isAggregateError(this: JSValue, globalObject: *JSGlobalObject) bool {
return cppFn("isAggregateError", .{ this, globalObject });
}
pub fn forEach(this: JSValue, globalObject: *JSGlobalObject, callback: fn (vm: [*c]VM, globalObject: [*c]JSGlobalObject, nextValue: JSValue) callconv(.C) void) void {
return cppFn("forEach", .{ this, globalObject, callback });
}
pub fn isIterable(this: JSValue, globalObject: *JSGlobalObject) bool {
return cppFn("isIterable", .{
this,
globalObject,
});
}
pub inline fn asRef(this: JSValue) C_API.JSValueRef {
return @intToPtr(C_API.JSValueRef, @intCast(usize, @enumToInt(this)));
}
pub inline fn asVoid(this: JSValue) *c_void {
return @intToPtr(*c_void, @intCast(usize, @enumToInt(this)));
}
pub const Extern = [_][]const u8{ "getErrorsProperty", "toInt32", "toBoolean", "isInt32", "isIterable", "forEach", "isAggregateError", "toZigException", "isException", "toWTFString", "hasProperty", "getPropertyNames", "getDirect", "putDirect", "get", "getIfExists", "asString", "asObject", "asNumber", "isError", "jsNull", "jsUndefined", "jsTDZValue", "jsBoolean", "jsDoubleNumber", "jsNumberFromDouble", "jsNumberFromChar", "jsNumberFromU16", "jsNumberFromInt32", "jsNumberFromInt64", "jsNumberFromUint64", "isUndefined", "isNull", "isUndefinedOrNull", "isBoolean", "isAnyInt", "isUInt32AsAnyInt", "isInt32AsAnyInt", "isNumber", "isString", "isBigInt", "isHeapBigInt", "isBigInt32", "isSymbol", "isPrimitive", "isGetterSetter", "isCustomGetterSetter", "isObject", "isCell", "asCell", "toString", "toStringOrNull", "toPropertyKey", "toPropertyKeyValue", "toObject", "toString", "getPrototype", "getPropertyByPropertyName", "eqlValue", "eqlCell", "isCallable" };
};
pub const PropertyName = extern struct {
@@ -1304,9 +1380,21 @@ pub const Exception = extern struct {
);
}
pub const Extern = [_][]const u8{
"create",
};
pub fn value(this: *Exception) JSValue {
return cppFn(
"value",
.{this},
);
}
pub fn getStackTrace(this: *Exception, trace: *ZigStackTrace) void {
return cppFn(
"getStackTrace",
.{ this, trace },
);
}
pub const Extern = [_][]const u8{ "create", "value", "getStackTrace" };
};
pub const JSLock = extern struct {

View File

@@ -26,7 +26,7 @@ pub const ZigGlobalObject = extern struct {
if (!sigaction_installed) {
sigaction_installed = true;
sigaction = std.mem.zeroes(std.os.Sigaction);
sigaction = std.mem.zeroes(std.os.Sigaction);
sigaction.handler = .{ .sigaction = Handler.global_signal_handler_fn };
std.os.sigaction(std.os.SIGABRT, &sigaction, null);
@@ -42,11 +42,11 @@ pub const ZigGlobalObject = extern struct {
return @call(.{ .modifier = .always_inline }, Interface.import, .{ global, specifier, source });
}
pub fn resolve(global: *JSGlobalObject, specifier: ZigString, source: ZigString) callconv(.C) ErrorableZigString {
pub fn resolve(res: *ErrorableZigString, global: *JSGlobalObject, specifier: ZigString, source: ZigString) callconv(.C) void {
if (comptime is_bindgen) {
unreachable;
}
return @call(.{ .modifier = .always_inline }, Interface.resolve, .{ global, specifier, source });
@call(.{ .modifier = .always_inline }, Interface.resolve, .{ res, global, specifier, source });
}
pub fn fetch(ret: *ErrorableResolvedSource, global: *JSGlobalObject, specifier: ZigString, source: ZigString) callconv(.C) void {
if (comptime is_bindgen) {
@@ -107,7 +107,7 @@ pub const ZigGlobalObject = extern struct {
}
};
const ErrorCodeInt = usize;
const ErrorCodeInt = u16;
pub const ErrorCode = enum(ErrorCodeInt) {
_,
@@ -298,9 +298,10 @@ pub const ZigStackTrace = extern struct {
pub fn next(this: *SourceLineIterator) ?SourceLine {
if (this.i < 0) return null;
const source_line = this.trace.source_lines_ptr[@intCast(usize, this.i)];
const result = SourceLine{
.line = this.trace.source_lines_numbers[@intCast(usize, this.i)],
.text = this.trace.source_lines_ptr[@intCast(usize, this.i)].slice(),
.text = source_line.slice(),
};
this.i -= 1;
return result;
@@ -542,26 +543,107 @@ pub const ZigConsoleClient = struct {
) callconv(.C) void {
var console = JS.VirtualMachine.vm.console;
var i: usize = 0;
var writer = console.writer;
var buffered_writer = console.writer;
var writer = buffered_writer.writer();
if (len == 1) {
var str = vals[0].toWTFString(global);
var slice = str.slice();
var written = writer.unbuffered_writer.write(slice) catch 0;
if (written > 0 and slice[slice.len - 1] != '\n') {
_ = writer.unbuffered_writer.write("\n") catch 0;
if (Output.enable_ansi_colors) {
FormattableType.format(@TypeOf(buffered_writer.unbuffered_writer), buffered_writer.unbuffered_writer, vals[0], true) catch {};
} else {
FormattableType.format(@TypeOf(buffered_writer.unbuffered_writer), buffered_writer.unbuffered_writer, vals[0], false) catch {};
}
_ = buffered_writer.unbuffered_writer.write("\n") catch 0;
return;
}
var values = vals[0..len];
defer writer.flush() catch {};
defer buffered_writer.flush() catch {};
var last_count: usize = 0;
var tail: u8 = 0;
while (i < len) : (i += 1) {
var str = values[i].toWTFString(global);
_ = writer.write(str.slice()) catch 0;
if (Output.enable_ansi_colors) {
while (i < len) : (i += 1) {
_ = if (i > 0) (writer.write(" ") catch 0);
FormattableType.format(@TypeOf(writer), writer, values[i], true) catch {};
}
} else {
while (i < len) : (i += 1) {
_ = if (i > 0) (writer.write(" ") catch 0);
FormattableType.format(@TypeOf(writer), writer, values[i], false) catch {};
}
}
_ = writer.write("\n") catch 0;
}
const FormattableType = enum {
Error,
String,
Undefined,
Double,
Integer,
Null,
Boolean,
const CellType = CAPI.CellType;
pub fn format(comptime Writer: type, writer: Writer, value: JSValue, comptime enable_ansi_colors: bool) anyerror!void {
if (value.isCell()) {
if (CAPI.JSObjectGetPrivate(value.asRef())) |private_data_ptr| {
const priv_data = JS.JSPrivateDataPtr.from(private_data_ptr);
switch (priv_data.tag()) {
.BuildError => {
const build_error = priv_data.as(JS.BuildError);
try build_error.msg.formatWriter(Writer, writer, enable_ansi_colors);
return;
},
.ResolveError => {
const resolve_error = priv_data.as(JS.ResolveError);
try resolve_error.msg.formatWriter(Writer, writer, enable_ansi_colors);
return;
},
else => {},
}
}
switch (@intToEnum(CellType, value.asCell().getType())) {
CellType.ErrorInstanceType => {
JS.VirtualMachine.printErrorlikeObject(JS.VirtualMachine.vm, value, null, enable_ansi_colors);
return;
},
CellType.GlobalObjectType => {
_ = try writer.write("[globalThis]");
return;
},
else => {},
}
}
if (value.isInt32()) {
try writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.toInt32()});
} else if (value.isNumber()) {
try writer.print(comptime Output.prettyFmt("<r><yellow>{d}<r>", enable_ansi_colors), .{value.asNumber()});
} else if (value.isUndefined()) {
try writer.print(comptime Output.prettyFmt("<r><d>undefined<r>", enable_ansi_colors), .{});
} else if (value.isNull()) {
try writer.print(comptime Output.prettyFmt("<r><yellow>null<r>", enable_ansi_colors), .{});
} else if (value.isBoolean()) {
if (value.toBoolean()) {
try writer.print(comptime Output.prettyFmt("<r><blue>true<r>", enable_ansi_colors), .{});
} else {
try writer.print(comptime Output.prettyFmt("<r><blue>false<r>", enable_ansi_colors), .{});
}
} else {
var str = value.toWTFString(JS.VirtualMachine.vm.global);
_ = try writer.write(str.slice());
}
}
};
pub fn count(console: ZigConsoleClient.Type, global: *JSGlobalObject, chars: [*]const u8, len: usize) callconv(.C) void {}
pub fn countReset(console: ZigConsoleClient.Type, global: *JSGlobalObject, chars: [*]const u8, len: usize) callconv(.C) void {}
pub fn time(console: ZigConsoleClient.Type, global: *JSGlobalObject, chars: [*]const u8, len: usize) callconv(.C) void {}

View File

@@ -1,4 +1,4 @@
//-- AUTOGENERATED FILE -- 1627867755
//-- AUTOGENERATED FILE -- 1627963169
// clang-format off
#pragma once

View File

@@ -21,7 +21,7 @@ typedef struct ResolvedSource {
ZigString source_code;
ZigString source_url;
uint32_t hash;
uint32_t bytecodecache_fd;
uint64_t bytecodecache_fd;
} ResolvedSource;
typedef union ErrorableResolvedSourceResult {
ResolvedSource value;

View File

@@ -49,3 +49,4 @@ pub const JSC__JSValue = bindings.JSValue;
pub const ZigString = bindings.ZigString;
pub const ZigException = bindings.ZigException;
pub const ResolvedSource = bindings.ResolvedSource;
pub const ZigStackTrace = bindings.ZigStackTrace;

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -125,8 +125,8 @@ static ZigString toZigString(JSC::Identifier *str, JSC::JSGlobalObject *global)
static WTF::StringView toStringView(ZigString str) { return WTF::StringView(str.ptr, str.len); }
static void throwException(JSC::ThrowScope &scope, ZigErrorType err, JSC::JSGlobalObject *global) {
scope.throwException(
global, JSC::Exception::create(global->vm(), JSC::JSValue((JSC::EncodedJSValue)err.ptr)));
scope.throwException(global,
JSC::Exception::create(global->vm(), JSC::JSValue((JSC::JSCell *)err.ptr)));
}
static ZigString toZigString(JSC::JSValue val, JSC::JSGlobalObject *global) {

View File

@@ -93,7 +93,11 @@ pub fn Shimmer(comptime _namespace: []const u8, comptime _name: []const u8, comp
}
pub fn symbolName(comptime typeName: []const u8) []const u8 {
return comptime std.fmt.comptimePrint("{s}__{s}__{s}", .{ namespace, name, typeName });
if (comptime namespace.len > 0) {
return comptime std.fmt.comptimePrint("{s}__{s}__{s}", .{ namespace, name, typeName });
} else {
return comptime std.fmt.comptimePrint("{s}__{s}", .{ name, typeName });
}
}
pub fn exportFunctions(comptime Functions: anytype) [std.meta.fieldNames(@TypeOf(Functions)).len]StaticExport {
@@ -134,11 +138,13 @@ pub fn Shimmer(comptime _namespace: []const u8, comptime _name: []const u8, comp
}
pub inline fn cppFn(comptime typeName: []const u8, args: anytype) (ret: {
@setEvalBranchQuota(99999);
if (!@hasDecl(Parent, typeName)) {
@compileError(@typeName(Parent) ++ " is missing cppFn: " ++ typeName);
}
break :ret std.meta.declarationInfo(Parent, typeName).data.Fn.return_type;
}) {
@setEvalBranchQuota(99999);
if (comptime is_bindgen) {
unreachable;
} else {

View File

@@ -169,7 +169,13 @@ pub const VirtualMachine = struct {
var old = vm.bundler.log;
vm.bundler.log = log;
defer vm.bundler.log = old;
vm.bundler.linker.log = log;
vm.bundler.resolver.log = log;
defer {
vm.bundler.log = old;
vm.bundler.linker.log = old;
vm.bundler.resolver.log = old;
}
var parse_result = vm.bundler.parse(
vm.bundler.allocator,
@@ -231,13 +237,20 @@ pub const VirtualMachine = struct {
},
}
}
inline fn _resolve(global: *JSGlobalObject, specifier: string, source: string) !string {
pub const ResolveFunctionResult = struct {
result: ?resolver.Result,
path: string,
};
inline fn _resolve(ret: *ResolveFunctionResult, global: *JSGlobalObject, specifier: string, source: string) !void {
std.debug.assert(VirtualMachine.vm_loaded);
std.debug.assert(VirtualMachine.vm.global == global);
if (vm.node_modules == null and strings.eqlComptime(specifier, Runtime.Runtime.Imports.Name)) {
return Runtime.Runtime.Imports.Name;
ret.path = Runtime.Runtime.Imports.Name;
return;
} else if (vm.node_modules != null and strings.eql(specifier, vm.bundler.linker.nodeModuleBundleImportPath())) {
return vm.bundler.linker.nodeModuleBundleImportPath();
ret.path = vm.bundler.linker.nodeModuleBundleImportPath();
return;
}
const result: resolver.Result = vm.bundler.resolve_results.get(specifier) orelse brk: {
@@ -251,6 +264,7 @@ pub const VirtualMachine = struct {
try vm.bundler.resolve_results.put(res.path_pair.primary.text, res);
break :brk res;
};
ret.result = result;
if (vm.node_modules != null and result.isLikelyNodeModule()) {
const node_modules_bundle = vm.node_modules.?;
@@ -288,52 +302,114 @@ pub const VirtualMachine = struct {
if (node_modules_bundle.findModuleIDInPackage(package, package_relative_path) == null) break :node_module_checker;
return vm.bundler.linker.nodeModuleBundleImportPath();
ret.path = vm.bundler.linker.nodeModuleBundleImportPath();
return;
}
}
}
return result.path_pair.primary.text;
ret.path = result.path_pair.primary.text;
}
pub fn resolve(global: *JSGlobalObject, specifier: ZigString, source: ZigString) ErrorableZigString {
const result = _resolve(global, specifier.slice(), source.slice()) catch |err| {
return ErrorableZigString.errFmt(err, "ResolveError {s} for \"{s}\"\nfrom\"{s}\"", .{
@errorName(err),
pub fn resolve(res: *ErrorableZigString, global: *JSGlobalObject, specifier: ZigString, source: ZigString) void {
var result = ResolveFunctionResult{ .path = "", .result = null };
_resolve(&result, global, specifier.slice(), source.slice()) catch |err| {
// This should almost always just apply to dynamic imports
const printed = ResolveError.fmt(
vm.allocator,
specifier.slice(),
source.slice(),
});
err,
) catch unreachable;
const msg = logger.Msg{
.data = logger.rangeData(
null,
logger.Range.None,
printed,
),
.metadata = .{
// import_kind is wrong probably
.resolve = .{ .specifier = logger.BabyString.in(printed, specifier.slice()), .import_kind = .stmt },
},
};
{
res.* = ErrorableZigString.err(err, @ptrCast(*c_void, ResolveError.create(vm.allocator, msg, source.slice())));
}
return;
};
return ErrorableZigString.ok(ZigString.init(result));
res.* = ErrorableZigString.ok(ZigString.init(result.path));
}
threadlocal var errors_stack: [256]*c_void = undefined;
pub fn fetch(ret: *ErrorableResolvedSource, global: *JSGlobalObject, specifier: ZigString, source: ZigString) callconv(.C) void {
var log = logger.Log.init(vm.bundler.allocator);
const result = _fetch(global, specifier.slice(), source.slice()) catch |err| {
switch (err) {
error.ParserError => {
std.debug.assert(log.msgs.items.len > 0);
switch (log.msgs.items.len) {
1 => {
return ErrorableResolvedSource.err(error.ParserError, BuildError.create(vm.bundler.allocator, &log.msgs.items[0]));
},
else => {
},
}
},
else => {
ret.* = ErrorableResolvedSource.errFmt(err, "{s}: \"{s}\"", .{
@errorName(err),
specifier.slice(),
});
},
}
const result = _fetch(global, specifier.slice(), source.slice(), &log) catch |err| {
processFetchLog(specifier, source, &log, ret, err);
return;
};
ret.* = ErrorableResolvedSource.ok(result);
if (log.errors > 0) {
processFetchLog(specifier, source, &log, ret, error.LinkError);
return;
}
ret.result.value = result;
ret.success = true;
}
fn processFetchLog(specifier: ZigString, referrer: ZigString, log: *logger.Log, ret: *ErrorableResolvedSource, err: anyerror) void {
switch (log.msgs.items.len) {
0 => {
const msg = logger.Msg{
.data = logger.rangeData(null, logger.Range.None, std.fmt.allocPrint(vm.allocator, "{s} while building {s}", .{ @errorName(err), specifier.slice() }) catch unreachable),
};
{
ret.* = ErrorableResolvedSource.err(err, @ptrCast(*c_void, BuildError.create(vm.bundler.allocator, msg)));
}
return;
},
1 => {
const msg = log.msgs.items[0];
ret.* = ErrorableResolvedSource.err(err, switch (msg.metadata) {
.build => BuildError.create(vm.bundler.allocator, msg).?,
.resolve => ResolveError.create(
vm.bundler.allocator,
msg,
referrer.slice(),
).?,
});
return;
},
else => {
var errors = errors_stack[0..std.math.min(log.msgs.items.len, errors_stack.len)];
for (log.msgs.items) |msg, i| {
errors[i] = switch (msg.metadata) {
.build => BuildError.create(vm.bundler.allocator, msg).?,
.resolve => ResolveError.create(
vm.bundler.allocator,
msg,
referrer.slice(),
).?,
};
}
ret.* = ErrorableResolvedSource.err(
err,
vm.global.createAggregateError(
errors.ptr,
@intCast(u16, errors.len),
ZigString.init(std.fmt.allocPrint(vm.bundler.allocator, "{d} errors building \"{s}\"", .{ errors.len, specifier.slice() }) catch unreachable),
).asVoid(),
);
return;
},
}
}
pub fn loadEntryPoint(this: *VirtualMachine, entry_point: string) !void {
@@ -348,124 +424,270 @@ pub const VirtualMachine = struct {
}
if (promise.status(this.global.vm()) == JSPromise.Status.Rejected) {
var exception_holder = ZigException.Holder.init();
var exception = exception_holder.zigException();
promise.result(this.global.vm()).toZigException(vm.global, exception);
var stderr: std.fs.File = Output.errorStream();
var buffered = std.io.bufferedWriter(stderr.writer());
var writer = buffered.writer();
defer buffered.flush() catch unreachable;
// We are going to print the stack trace backwards
const stack = exception.stack.frames();
if (stack.len > 0) {
var i = @intCast(i16, stack.len - 1);
var result = promise.result(this.global.vm());
var func_name_pad: usize = 0;
while (i >= 0) : (i -= 1) {
const frame = stack[@intCast(usize, i)];
func_name_pad = std.math.max(func_name_pad, std.fmt.count("{any}", .{
frame.nameFormatter(true),
}));
if (result.isException(this.global.vm())) {
var exception = @ptrCast(*Exception, result.asVoid());
if (Output.enable_ansi_colors) {
this.printErrorlikeObject(exception.value(), exception, true);
} else {
this.printErrorlikeObject(exception.value(), exception, false);
}
} else if (Output.enable_ansi_colors) {
this.printErrorlikeObject(result, null, true);
} else {
this.printErrorlikeObject(result, null, false);
}
}
}
i = @intCast(i16, stack.len - 1);
// When the Error-like object is one of our own, it's best to rely on the object directly instead of serializing it to a ZigException.
// This is for:
// - BuildError
// - ResolveError
// If there were multiple errors, it could be contained in an AggregateError.
// In that case, this function becomes recursive.
// In all other cases, we will convert it to a ZigException.
const errors_property = ZigString.init("errors");
pub fn printErrorlikeObject(this: *VirtualMachine, value: JSValue, exception: ?*Exception, comptime allow_ansi_color: bool) void {
var was_internal = false;
while (i >= 0) : (i -= 1) {
const frame = stack[@intCast(usize, i)];
const file = frame.source_url.slice();
const func = frame.function_name.slice();
defer {
if (was_internal) {
if (exception) |exception_| {
var holder = ZigException.Holder.init();
var zig_exception = holder.zigException();
exception_.getStackTrace(&zig_exception.stack);
if (zig_exception.stack.frames_len > 0) {
var buffered_writer = std.io.bufferedWriter(Output.errorWriter());
var writer = buffered_writer.writer();
try writer.print(" {any}", .{frame.sourceURLFormatter(true)});
try writer.writeAll(" in ");
try writer.print(" {any}\n", .{frame.nameFormatter(true)});
if (Output.enable_ansi_colors) {
printStackTrace(@TypeOf(writer), writer, zig_exception.stack, true) catch {};
} else {
printStackTrace(@TypeOf(writer), writer, zig_exception.stack, false) catch {};
}
// if (!frame.position.isInvalid()) {
// if (func.len > 0) {
// writer.print(
// comptime Output.prettyFmt("<r><d>{s}<r> {s}{s} - {s}:{d}:{d}\n", true),
// .{
// if (i > 1) "↓" else "↳",
// frame.code_type.ansiColor(),
// func,
// file,
// frame.position.line,
// frame.position.column_start,
// },
// ) catch unreachable;
// } else {
// writer.print(comptime Output.prettyFmt("<r><d>{s}<r> {u} - {s}{s}:{d}:{d}\n", true), .{
// if (i > 1) "↓" else "↳",
// frame.code_type.emoji(),
// frame.code_type.ansiColor(),
// file,
// frame.position.line,
// frame.position.column_start,
// }) catch unreachable;
// }
// } else {
// if (func.len > 0) {
// writer.print(
// comptime Output.prettyFmt("<r><d>{s}<r> {s}{s} - {s}\n", true),
// .{
// if (i > 1) "↓" else "↳",
// frame.code_type.ansiColor(),
// func,
// file,
// },
// ) catch unreachable;
// } else {
// writer.print(
// comptime Output.prettyFmt("<r><d>{s}<r> {u} - {s}{s}\n", true),
// .{
// if (i > 1) "↓" else "↳",
// frame.code_type.emoji(),
// frame.code_type.ansiColor(),
// file,
// },
// ) catch unreachable;
// }
// }
buffered_writer.flush() catch {};
}
}
}
}
var line_numbers = exception.stack.source_lines_numbers[0..exception.stack.source_lines_len];
var max_line: i32 = -1;
for (line_numbers) |line| max_line = std.math.max(max_line, line);
const max_line_number_pad = std.fmt.count("{d}", .{max_line});
if (value.isAggregateError(this.global)) {
const AggregateErrorIterator = struct {
pub fn iteratorWithColor(_vm: [*c]VM, globalObject: [*c]JSGlobalObject, nextValue: JSValue) callconv(.C) void {
iterator(_vm, globalObject, nextValue, true);
}
pub fn iteratorWithOutColor(_vm: [*c]VM, globalObject: [*c]JSGlobalObject, nextValue: JSValue) callconv(.C) void {
iterator(_vm, globalObject, nextValue, false);
}
inline fn iterator(_vm: [*c]VM, globalObject: [*c]JSGlobalObject, nextValue: JSValue, comptime color: bool) void {
VirtualMachine.vm.printErrorlikeObject(nextValue, null, color);
}
};
if (comptime allow_ansi_color) {
value.getErrorsProperty(this.global).forEach(this.global, AggregateErrorIterator.iteratorWithColor);
} else {
value.getErrorsProperty(this.global).forEach(this.global, AggregateErrorIterator.iteratorWithOutColor);
}
return;
}
if (js.JSValueIsObject(vm.global.ref(), value.asRef())) {
if (js.JSObjectGetPrivate(value.asRef())) |priv| {
was_internal = this.printErrorFromMaybePrivateData(priv, allow_ansi_color);
return;
}
}
was_internal = this.printErrorFromMaybePrivateData(value.asRef(), allow_ansi_color);
}
pub fn printErrorFromMaybePrivateData(this: *VirtualMachine, value: ?*c_void, comptime allow_ansi_color: bool) bool {
const private_data_ptr = JSPrivateDataPtr.from(value);
switch (private_data_ptr.tag()) {
.BuildError => {
defer Output.flush();
const build_error = private_data_ptr.as(BuildError);
build_error.msg.formatNoWriter(Output.printErrorln);
return true;
},
.ResolveError => {
defer Output.flush();
const resolve_error = private_data_ptr.as(ResolveError);
resolve_error.msg.formatNoWriter(Output.printErrorln);
return true;
},
else => {
this.printErrorInstance(@intToEnum(JSValue, @intCast(i64, (@ptrToInt(value)))), allow_ansi_color) catch |err| {
if (comptime isDebug) {
Output.printErrorln("Error while printing Error-like object: {s}", .{@errorName(err)});
Output.flush();
}
};
return false;
},
}
}
pub fn printStackTrace(comptime Writer: type, writer: Writer, trace: ZigStackTrace, comptime allow_ansi_colors: bool) !void {
// We are going to print the stack trace backwards
const stack = trace.frames();
if (stack.len > 0) {
var i = @intCast(i16, stack.len - 1);
var func_name_pad: usize = 0;
while (i >= 0) : (i -= 1) {
const frame = stack[@intCast(usize, i)];
func_name_pad = std.math.max(func_name_pad, std.fmt.count("{any}", .{
frame.nameFormatter(allow_ansi_colors),
}));
}
i = @intCast(i16, stack.len - 1);
while (i >= 0) : (i -= 1) {
const frame = stack[@intCast(usize, i)];
const file = frame.source_url.slice();
const func = frame.function_name.slice();
try writer.print(
comptime Output.prettyFmt(
"<r> <d>at <r>{any} <d>(<r>{any}<d>)<r>\n",
allow_ansi_colors,
),
.{ frame.nameFormatter(allow_ansi_colors), frame.sourceURLFormatter(allow_ansi_colors) },
);
// if (!frame.position.isInvalid()) {
// if (func.len > 0) {
// writer.print(
// comptime Output.prettyFmt("<r><d>{s}<r> {s}{s} - {s}:{d}:{d}\n", true),
// .{
// if (i > 1) "↓" else "↳",
// frame.code_type.ansiColor(),
// func,
// file,
// frame.position.line,
// frame.position.column_start,
// },
// ) catch unreachable;
// } else {
// writer.print(comptime Output.prettyFmt("<r><d>{s}<r> {u} - {s}{s}:{d}:{d}\n", true), .{
// if (i > 1) "↓" else "↳",
// frame.code_type.emoji(),
// frame.code_type.ansiColor(),
// file,
// frame.position.line,
// frame.position.column_start,
// }) catch unreachable;
// }
// } else {
// if (func.len > 0) {
// writer.print(
// comptime Output.prettyFmt("<r><d>{s}<r> {s}{s} - {s}\n", true),
// .{
// if (i > 1) "↓" else "↳",
// frame.code_type.ansiColor(),
// func,
// file,
// },
// ) catch unreachable;
// } else {
// writer.print(
// comptime Output.prettyFmt("<r><d>{s}<r> {u} - {s}{s}\n", true),
// .{
// if (i > 1) "↓" else "↳",
// frame.code_type.emoji(),
// frame.code_type.ansiColor(),
// file,
// },
// ) catch unreachable;
// }
// }
}
}
}
pub fn printErrorInstance(this: *VirtualMachine, error_instance: JSValue, comptime allow_ansi_color: bool) !void {
var exception_holder = ZigException.Holder.init();
var exception = exception_holder.zigException();
error_instance.toZigException(vm.global, exception);
var stderr: std.fs.File = Output.errorStream();
var buffered = std.io.bufferedWriter(stderr.writer());
var writer = buffered.writer();
defer buffered.flush() catch unreachable;
var line_numbers = exception.stack.source_lines_numbers[0..exception.stack.source_lines_len];
var max_line: i32 = -1;
for (line_numbers) |line| max_line = std.math.max(max_line, line);
const max_line_number_pad = std.fmt.count("{d}", .{max_line});
var source_lines = exception.stack.sourceLineIterator();
var last_pad: u64 = 0;
while (source_lines.untilLast()) |source| {
const int_size = std.fmt.count("{d}", .{source.line});
const pad = max_line_number_pad - int_size;
last_pad = pad;
writer.writeByteNTimes(' ', pad) catch unreachable;
writer.print(
comptime Output.prettyFmt("<r><d>{d} | <r>{s}\n", allow_ansi_color),
.{
source.line,
std.mem.trim(u8, source.text, "\n"),
},
) catch unreachable;
}
const name = exception.name.slice();
const message = exception.message.slice();
var did_print_name = false;
if (source_lines.next()) |source| {
if (source.text.len > 0 and exception.stack.frames()[0].position.isInvalid()) {
defer did_print_name = true;
var text = std.mem.trim(u8, source.text, "\n");
var source_lines = exception.stack.sourceLineIterator();
var last_pad: u64 = 0;
while (source_lines.untilLast()) |source| {
const int_size = std.fmt.count("{d}", .{source.line});
const pad = max_line_number_pad - int_size;
last_pad = pad;
writer.writeByteNTimes(' ', pad) catch unreachable;
writer.print(
comptime Output.prettyFmt("<r><d>{d} | <r>{s}\n", true),
comptime Output.prettyFmt(
"<r><d>- |<r> {s}\n",
allow_ansi_color,
),
.{
source.line,
std.mem.trim(u8, source.text, "\n"),
text,
},
) catch unreachable;
}
const name = exception.name.slice();
const message = exception.message.slice();
var did_print_name = false;
if (source_lines.next()) |source| {
if (name.len > 0 and message.len > 0) {
writer.print(comptime Output.prettyFmt(" <r><red><b>{s}<r><d>:<r> <b>{s}<r>\n", allow_ansi_color), .{
name,
message,
}) catch unreachable;
} else if (name.len > 0) {
writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", allow_ansi_color), .{name}) catch unreachable;
} else if (message.len > 0) {
writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", allow_ansi_color), .{message}) catch unreachable;
}
} else if (source.text.len > 0) {
defer did_print_name = true;
const int_size = std.fmt.count("{d}", .{source.line});
const pad = max_line_number_pad - int_size;
writer.writeByteNTimes(' ', pad) catch unreachable;
std.debug.assert(!stack[0].position.isInvalid());
const top = exception.stack.frames()[0];
var remainder = std.mem.trim(u8, source.text, "\n");
const prefix = remainder[0..@intCast(usize, stack[0].position.column_start)];
const underline = remainder[@intCast(usize, stack[0].position.column_start)..@intCast(usize, stack[0].position.column_stop)];
const suffix = remainder[@intCast(usize, stack[0].position.column_stop)..];
const prefix = remainder[0..@intCast(usize, top.position.column_start)];
const underline = remainder[@intCast(usize, top.position.column_start)..@intCast(usize, top.position.column_stop)];
const suffix = remainder[@intCast(usize, top.position.column_stop)..];
writer.print(
comptime Output.prettyFmt("<r><d>{d} |<r> {s}<red>{s}<r>{s}<r>\n<r>", true),
comptime Output.prettyFmt(
"<r><d>{d} |<r> {s}<red>{s}<r>{s}<r>\n<r>",
allow_ansi_color,
),
.{
source.line,
prefix,
@@ -473,55 +695,45 @@ pub const VirtualMachine = struct {
suffix,
},
) catch unreachable;
var first_non_whitespace = @intCast(u32, stack[0].position.column_start);
var first_non_whitespace = @intCast(u32, top.position.column_start);
while (first_non_whitespace < source.text.len and source.text[first_non_whitespace] == ' ') {
first_non_whitespace += 1;
}
std.debug.assert(stack.len > 0);
const indent = @intCast(usize, pad) + " | ".len + first_non_whitespace + 1;
writer.writeByteNTimes(' ', indent) catch unreachable;
writer.print(comptime Output.prettyFmt(
"<red><b>^<r>\n",
true,
allow_ansi_color,
), .{}) catch unreachable;
if (name.len > 0 and message.len > 0) {
writer.print(comptime Output.prettyFmt(" <r><red><b>{s}<r><d>:<r> <b>{s}<r>\n", true), .{
writer.print(comptime Output.prettyFmt(" <r><red><b>{s}<r><d>:<r> <b>{s}<r>\n", allow_ansi_color), .{
name,
message,
}) catch unreachable;
} else if (name.len > 0) {
writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", true), .{name}) catch unreachable;
writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", allow_ansi_color), .{name}) catch unreachable;
} else if (message.len > 0) {
writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", true), .{message}) catch unreachable;
}
did_print_name = true;
}
if (!did_print_name) {
if (name.len > 0 and message.len > 0) {
writer.print(comptime Output.prettyFmt("<r><red><b>{s}<r><d>:<r> <b>{s}<r>\n", true), .{
name,
message,
}) catch unreachable;
} else if (name.len > 0) {
writer.print(comptime Output.prettyFmt("<r><b>{s}<r>\n", true), .{name}) catch unreachable;
} else if (message.len > 0) {
writer.print(comptime Output.prettyFmt("<r><b>{s}<r>\n", true), .{name}) catch unreachable;
writer.print(comptime Output.prettyFmt(" <r><b>{s}<r>\n", allow_ansi_color), .{message}) catch unreachable;
}
}
// Output.prettyErrorln("<r><red>{s}<r><d>:<r> <b>{s}<r>\n<blue>{s}<r>:{d}:{d}\n{s}", .{
// exception.name.slice(),
// exception.message.slice(),
// exception.sourceURL.slice(),
// exception.line,
// exception.column,
// exception.stack.slice(),
// });
}
if (!did_print_name) {
if (name.len > 0 and message.len > 0) {
writer.print(comptime Output.prettyFmt("<r><red><b>{s}<r><d>:<r> <b>{s}<r>\n", true), .{
name,
message,
}) catch unreachable;
} else if (name.len > 0) {
writer.print(comptime Output.prettyFmt("<r><b>{s}<r>\n", true), .{name}) catch unreachable;
} else if (message.len > 0) {
writer.print(comptime Output.prettyFmt("<r><b>{s}<r>\n", true), .{name}) catch unreachable;
}
}
try printStackTrace(@TypeOf(writer), writer, exception.stack, allow_ansi_color);
}
};
@@ -706,12 +918,32 @@ pub const ResolveError = struct {
allocator: *std.mem.Allocator,
referrer: ?Fs.Path = null,
pub fn fmt(allocator: *std.mem.Allocator, specifier: string, referrer: string, err: anyerror) !string {
switch (err) {
error.ModuleNotFound => {
if (resolver.isPackagePath(specifier)) {
return try std.fmt.allocPrint(allocator, "Cannot find package \"{s}\" from \"{s}\"", .{ specifier, referrer });
} else {
return try std.fmt.allocPrint(allocator, "Cannot find module \"{s}\" from \"{s}\"", .{ specifier, referrer });
}
},
else => {
if (resolver.isPackagePath(specifier)) {
return try std.fmt.allocPrint(allocator, "{s} while resolving package \"{s}\" from \"{s}\"", .{ @errorName(err), specifier, referrer });
} else {
return try std.fmt.allocPrint(allocator, "{s} while resolving \"{s}\" from \"{s}\"", .{ @errorName(err), specifier, referrer });
}
},
}
}
pub const Class = NewClass(
ResolveError,
.{
.name = "ResolveError",
.read_only = true,
},
.{},
.{
.@"referrer" = .{
.@"get" = getReferrer,
@@ -744,20 +976,22 @@ pub const ResolveError = struct {
.ts = d.ts{ .@"return" = "string" },
},
},
.{},
);
pub fn create(
msg: logger.Msg,
allocator: *std.mem.Allocator,
msg: logger.Msg,
referrer: string,
) js.JSObjectRef {
var resolve_error = allocator.create(ResolveError) catch unreachable;
resolve_error.* = ResolveError{
.msg = msg,
.allocator = allocator,
.referrer = Fs.Path.init(referrer),
};
return Class.make(VirtualMachine.vm.global, resolve_error);
var ref = Class.make(VirtualMachine.vm.global.ctx(), resolve_error);
js.JSValueProtect(VirtualMachine.vm.global.ref(), ref);
return ref;
}
pub fn getPosition(
@@ -771,44 +1005,44 @@ pub const ResolveError = struct {
}
pub fn getMessage(
this: *BuildError,
this: *ResolveError,
ctx: js.JSContextRef,
thisObject: js.JSObjectRef,
prop: js.JSStringRef,
exception: js.ExceptionRef,
) js.JSValueRef {
return ZigString.init(this.msg.data.text).toValue(VirtualMachine.vm.global);
return ZigString.init(this.msg.data.text).toValue(VirtualMachine.vm.global).asRef();
}
pub fn getSpecifier(
this: *BuildError,
this: *ResolveError,
ctx: js.JSContextRef,
thisObject: js.JSObjectRef,
prop: js.JSStringRef,
exception: js.ExceptionRef,
) js.JSValueRef {
return ZigString.init(this.msg.metadata.Resolve.specifier.slice(this.msg.data.text)).toValue(VirtualMachine.vm.global);
return ZigString.init(this.msg.metadata.resolve.specifier.slice(this.msg.data.text)).toValue(VirtualMachine.vm.global).asRef();
}
pub fn getImportKind(
this: *BuildError,
this: *ResolveError,
ctx: js.JSContextRef,
thisObject: js.JSObjectRef,
prop: js.JSStringRef,
exception: js.ExceptionRef,
) js.JSValueRef {
return ZigString.init(@tagName(this.msg.metadata.Resolve.import_kind)).toValue(VirtualMachine.vm.global);
return ZigString.init(@tagName(this.msg.metadata.resolve.import_kind)).toValue(VirtualMachine.vm.global).asRef();
}
pub fn getReferrer(
this: *BuildError,
this: *ResolveError,
ctx: js.JSContextRef,
thisObject: js.JSObjectRef,
prop: js.JSStringRef,
exception: js.ExceptionRef,
) js.JSValueRef {
if (this.referrer) |referrer| {
return ZigString.init(referrer.text).toValue(VirtualMachine.vm.global);
return ZigString.init(referrer.text).toValue(VirtualMachine.vm.global).asRef();
} else {
return js.JSValueMakeNull(ctx);
}
@@ -816,13 +1050,13 @@ pub const ResolveError = struct {
const BuildErrorName = "ResolveError";
pub fn getName(
this: *BuildError,
this: *ResolveError,
ctx: js.JSContextRef,
thisObject: js.JSObjectRef,
prop: js.JSStringRef,
exception: js.ExceptionRef,
) js.JSValueRef {
return ZigString.init(BuildErrorName).toValue(VirtualMachine.vm.global);
return ZigString.init(BuildErrorName).toValue(VirtualMachine.vm.global).asRef();
}
};
@@ -857,17 +1091,19 @@ pub const BuildError = struct {
pub fn create(
allocator: *std.mem.Allocator,
msg: *const logger.Msg,
msg: logger.Msg,
// resolve_result: *const resolver.Result,
) js.JSObjectRef {
var build_error = allocator.create(BuildError) catch unreachable;
build_error.* = BuildError{
.msg = msg.*,
.msg = msg,
// .resolve_result = resolve_result.*,
.allocator = allocator,
};
return Class.make(VirtualMachine.vm.global, build_error);
var ref = Class.make(VirtualMachine.vm.global.ref(), build_error);
js.JSValueProtect(VirtualMachine.vm.global.ref(), ref);
return ref;
}
pub fn getPosition(
@@ -939,16 +1175,65 @@ pub const BuildError = struct {
}
};
pub fn generatePositionObject(msg: logger.Msg, ctx: js.JSContextRef, exception: ExceptionValueRef) js.JSValue {
pub fn generatePositionObject(msg: logger.Msg, ctx: js.JSContextRef, exception: ExceptionValueRef) js.JSValueRef {
if (msg.data.location) |location| {
const ref = js.JSObjectMake(ctx, null, null);
js.JSObjectSetProperty(ctx, ref, PositionProperties.lineText(), ZigString.init(location.line_text orelse "").toJSStringRef(), 0, exception);
js.JSObjectSetProperty(ctx, ref, PositionProperties.file(), ZigString.init(location.file).toJSStringRef(), 0, exception);
js.JSObjectSetProperty(ctx, ref, PositionProperties.namespace(), ZigString.init(location.namespace).toJSStringRef(), 0, exception);
js.JSObjectSetProperty(ctx, ref, PositionProperties.line(), js.JSValueMakeNumber(ctx, location.line), 0, exception);
js.JSObjectSetProperty(ctx, ref, PositionProperties.column(), js.JSValueMakeNumber(ctx, location.column), 0, exception);
js.JSObjectSetProperty(ctx, ref, PositionProperties.length(), js.JSValueMakeNumber(ctx, location.length), 0, exception);
js.JSObjectSetProperty(ctx, ref, PositionProperties.offset(), js.JSValueMakeNumber(ctx, location.offset), 0, exception);
js.JSObjectSetProperty(
ctx,
ref,
PositionProperties.lineText(),
ZigString.init(location.line_text orelse "").toJSStringRef(),
0,
exception,
);
js.JSObjectSetProperty(
ctx,
ref,
PositionProperties.file(),
ZigString.init(location.file).toJSStringRef(),
0,
exception,
);
js.JSObjectSetProperty(
ctx,
ref,
PositionProperties.namespace(),
ZigString.init(location.namespace).toJSStringRef(),
0,
exception,
);
js.JSObjectSetProperty(
ctx,
ref,
PositionProperties.line(),
js.JSValueMakeNumber(ctx, @intToFloat(f64, location.line)),
0,
exception,
);
js.JSObjectSetProperty(
ctx,
ref,
PositionProperties.column(),
js.JSValueMakeNumber(ctx, @intToFloat(f64, location.column)),
0,
exception,
);
js.JSObjectSetProperty(
ctx,
ref,
PositionProperties.length(),
js.JSValueMakeNumber(ctx, @intToFloat(f64, location.length)),
0,
exception,
);
js.JSObjectSetProperty(
ctx,
ref,
PositionProperties.offset(),
js.JSValueMakeNumber(ctx, @intToFloat(f64, location.offset)),
0,
exception,
);
return ref;
}
@@ -962,7 +1247,7 @@ pub const BuildError = struct {
prop: js.JSStringRef,
exception: js.ExceptionRef,
) js.JSValueRef {
return ZigString.init(this.msg.data.text).toValue(VirtualMachine.vm.global);
return ZigString.init(this.msg.data.text).toValue(VirtualMachine.vm.global).asRef();
}
const BuildErrorName = "BuildError";
@@ -973,7 +1258,7 @@ pub const BuildError = struct {
prop: js.JSStringRef,
exception: js.ExceptionRef,
) js.JSValueRef {
return ZigString.init(BuildErrorName).toValue(VirtualMachine.vm.global);
return ZigString.init(BuildErrorName).toValue(VirtualMachine.vm.global).asRef();
}
};

View File

@@ -55,7 +55,6 @@ pub const Response = struct {
pub fn finalize(
this: *Response,
ctx: js.JSObjectRef,
) void {
this.body.deinit(this.allocator);
this.allocator.destroy(this);
@@ -121,16 +120,15 @@ pub const Response = struct {
// return null;
// }
var tup = Repsonse.Class.makeObject(
ctx,
getAllocator(ctx),
);
tup.ptr.* = Response{
var response = getAllocator(ctx).create(Response) catch unreachable;
response.* = Response{
.body = body,
.allocator = getAllocator(ctx),
};
return tup.ref;
return Response.Class.make(
ctx,
response,
);
}
};
@@ -298,7 +296,6 @@ pub const Headers = struct {
pub fn finalize(
this: *Headers,
ctx: js.JSObjectRef,
) void {
this.deinit();
}

View File

@@ -133,21 +133,28 @@ pub const Lexer = struct {
}
pub fn syntaxError(self: *LexerType) !void {
@setCold(true);
self.addError(self.start, "Syntax Error!!", .{}, true);
return Error.SyntaxError;
}
pub fn addDefaultError(self: *LexerType, msg: []const u8) !void {
@setCold(true);
self.addError(self.start, "{s}", .{msg}, true);
return Error.SyntaxError;
}
pub fn addSyntaxError(self: *LexerType, _loc: logger.Loc, comptime fmt: []const u8, args: anytype) !void {
pub fn addSyntaxError(self: *LexerType, _loc: usize, comptime fmt: []const u8, args: anytype) !void {
@setCold(true);
self.addError(_loc, fmt, args, false);
return Error.SyntaxError;
}
pub fn addError(self: *LexerType, _loc: usize, comptime format: []const u8, args: anytype, panic: bool) void {
@setCold(true);
if (self.is_log_disabled) return;
var __loc = logger.usize2Loc(_loc);
if (__loc.eql(self.prev_error_loc)) {
@@ -159,6 +166,8 @@ pub const Lexer = struct {
}
pub fn addRangeError(self: *LexerType, r: logger.Range, comptime format: []const u8, args: anytype, panic: bool) !void {
@setCold(true);
if (self.is_log_disabled) return;
if (self.prev_error_loc.eql(r.loc)) {
return;
@@ -173,14 +182,6 @@ pub const Lexer = struct {
// }
}
fn doPanic(self: *LexerType, content: []const u8) void {
if (@import("builtin").is_test) {
self.did_panic = true;
} else {
Global.panic("{s}", .{content});
}
}
pub fn codePointEql(self: *LexerType, a: u8) bool {
return @intCast(CodePoint, a) == self.code_point;
}

View File

@@ -173,8 +173,8 @@ pub const BabyString = packed struct {
};
}
pub fn slice(container: string) string {
return container[offset..][0..len];
pub fn slice(this: BabyString, container: string) string {
return container[this.offset..][0..this.len];
}
};
@@ -260,6 +260,30 @@ pub const Msg = struct {
});
}
pub fn formatWriter(
msg: *const Msg,
comptime Writer: type,
writer: Writer,
comptime allow_colors: bool,
) !void {
if (msg.data.location) |location| {
try writer.print("{s}: {s}\n{s}\n{s}:{}:{} ({d})", .{
msg.kind.string(),
msg.data.text,
location.line_text,
location.file,
location.line,
location.column,
location.offset,
});
} else {
try writer.print("{s}: {s}", .{
msg.kind.string(),
msg.data.text,
});
}
}
pub fn formatNoWriter(msg: *const Msg, comptime formatterFunc: @TypeOf(Global.panic)) void {
formatterFunc("\n\n{s}: {s}\n{s}\n{s}:{}:{} ({d})", .{
msg.kind.string(),

View File

@@ -48,7 +48,7 @@ pub fn TaggedPointerUnion(comptime Types: anytype) type {
inline for (Types) |field, i| {
enumFields[i] = .{
.name = @typeName(field),
.value = std.math.maxInt(TagSize) - 1 - i,
.value = 1024 - i,
};
}