diff options
Diffstat (limited to 'src/js')
| -rw-r--r-- | src/js/console.nim | 4 | ||||
| -rw-r--r-- | src/js/domexception.nim | 2 | ||||
| -rw-r--r-- | src/js/fromjs.nim | 112 | ||||
| -rw-r--r-- | src/js/javascript.nim | 94 | ||||
| -rw-r--r-- | src/js/jsutils.nim | 9 | ||||
| -rw-r--r-- | src/js/opaque.nim | 91 | ||||
| -rw-r--r-- | src/js/tojs.nim | 39 |
7 files changed, 188 insertions, 163 deletions
diff --git a/src/js/console.nim b/src/js/console.nim index 305dfa9b..3b28df5e 100644 --- a/src/js/console.nim +++ b/src/js/console.nim @@ -19,8 +19,8 @@ proc newConsole*(err: DynStream; clearFun: proc() = nil; showFun: proc() = nil; ) proc log*(console: Console; ss: varargs[string]) {.jsfunc.} = - for i in 0..<ss.len: - console.err.write(ss[i]) + for i, s in ss: + console.err.write(s) if i != ss.high: console.err.write(' ') console.err.write('\n') diff --git a/src/js/domexception.nim b/src/js/domexception.nim index 3d4a4a1e..f916fb59 100644 --- a/src/js/domexception.nim +++ b/src/js/domexception.nim @@ -37,7 +37,7 @@ type jsDestructor(DOMException) -proc newDOMException*(message = "", name = "Error"): DOMException {.jsctor.} = +proc newDOMException*(message = ""; name = "Error"): DOMException {.jsctor.} = return DOMException( e: JS_DOM_EXCEPTION, name: name, diff --git a/src/js/fromjs.nim b/src/js/fromjs.nim index 527b6221..c5c80da1 100644 --- a/src/js/fromjs.nim +++ b/src/js/fromjs.nim @@ -7,6 +7,7 @@ import bindings/quickjs import io/promise import js/error import js/jstypes +import js/jsutils import js/opaque import types/opt import utils/twtstr @@ -84,11 +85,6 @@ func fromJSInt[T: SomeInteger](ctx: JSContext; val: JSValue): if JS_ToInt32(ctx, addr ret, val) < 0: return err() return ok(int(ret)) - elif T is uint: - var ret: uint32 - if JS_ToUint32(ctx, addr ret, val) < 0: - return err() - return ok(uint(ret)) elif T is int32: var ret: int32 if JS_ToInt32(ctx, addr ret, val) < 0: @@ -123,11 +119,11 @@ macro fromJSTupleBody(a: tuple) = var `done`: bool) for i in 0..<len: result.add(quote do: - let next = JS_Call(ctx, next_method, it, 0, nil) + let next = JS_Call(ctx, nextMethod, it, 0, nil) if JS_IsException(next): return err() defer: JS_FreeValue(ctx, next) - let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().str_refs[DONE]) + let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().strRefs[jstDone]) if JS_IsException(doneVal): return err() defer: JS_FreeValue(ctx, doneVal) @@ -135,7 +131,7 @@ macro fromJSTupleBody(a: tuple) = if `done`: return errTypeError("Too few arguments in sequence (got " & $`i` & ", expected " & $`len` & ")") - let valueVal = JS_GetProperty(ctx, next, ctx.getOpaque().str_refs[VALUE]) + let valueVal = JS_GetProperty(ctx, next, ctx.getOpaque().strRefs[jstValue]) if JS_IsException(valueVal): return err() defer: JS_FreeValue(ctx, valueVal) @@ -143,23 +139,23 @@ macro fromJSTupleBody(a: tuple) = ) if i == len - 1: result.add(quote do: - let next = JS_Call(ctx, next_method, it, 0, nil) + let next = JS_Call(ctx, nextMethod, it, 0, nil) if JS_IsException(next): return err() defer: JS_FreeValue(ctx, next) - let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().str_refs[DONE]) + let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().strRefs[jstDone]) `done` = ?fromJS[bool](ctx, doneVal) var i = `i` # we're emulating a sequence, so we must query all remaining parameters # too: while not `done`: inc i - let next = JS_Call(ctx, next_method, it, 0, nil) + let next = JS_Call(ctx, nextMethod, it, 0, nil) if JS_IsException(next): return err() defer: JS_FreeValue(ctx, next) let doneVal = JS_GetProperty(ctx, next, - ctx.getOpaque().str_refs[DONE]) + ctx.getOpaque().strRefs[jstDone]) if JS_IsException(doneVal): return err() defer: JS_FreeValue(ctx, doneVal) @@ -169,11 +165,11 @@ macro fromJSTupleBody(a: tuple) = ", expected " & $`len` & ")" return err(newTypeError(msg)) JS_FreeValue(ctx, JS_GetProperty(ctx, next, - ctx.getOpaque().str_refs[VALUE])) + ctx.getOpaque().strRefs[jstValue])) ) proc fromJSTuple[T: tuple](ctx: JSContext; val: JSValue): JSResult[T] = - let itprop = JS_GetProperty(ctx, val, ctx.getOpaque().sym_refs[ITERATOR]) + let itprop = JS_GetProperty(ctx, val, ctx.getOpaque().symRefs[jsyIterator]) if JS_IsException(itprop): return err() defer: JS_FreeValue(ctx, itprop) @@ -181,16 +177,16 @@ proc fromJSTuple[T: tuple](ctx: JSContext; val: JSValue): JSResult[T] = if JS_IsException(it): return err() defer: JS_FreeValue(ctx, it) - let next_method = JS_GetProperty(ctx, it, ctx.getOpaque().str_refs[NEXT]) - if JS_IsException(next_method): + let nextMethod = JS_GetProperty(ctx, it, ctx.getOpaque().strRefs[jstNext]) + if JS_IsException(nextMethod): return err() - defer: JS_FreeValue(ctx, next_method) + defer: JS_FreeValue(ctx, nextMethod) var x: T fromJSTupleBody(x) return ok(x) proc fromJSSeq[T](ctx: JSContext; val: JSValue): JSResult[seq[T]] = - let itprop = JS_GetProperty(ctx, val, ctx.getOpaque().sym_refs[ITERATOR]) + let itprop = JS_GetProperty(ctx, val, ctx.getOpaque().symRefs[jsyIterator]) if JS_IsException(itprop): return err() defer: JS_FreeValue(ctx, itprop) @@ -198,24 +194,24 @@ proc fromJSSeq[T](ctx: JSContext; val: JSValue): JSResult[seq[T]] = if JS_IsException(it): return err() defer: JS_FreeValue(ctx, it) - let next_method = JS_GetProperty(ctx, it, ctx.getOpaque().str_refs[NEXT]) - if JS_IsException(next_method): + let nextMethod = JS_GetProperty(ctx, it, ctx.getOpaque().strRefs[jstNext]) + if JS_IsException(nextMethod): return err() - defer: JS_FreeValue(ctx, next_method) + defer: JS_FreeValue(ctx, nextMethod) var s = newSeq[T]() while true: - let next = JS_Call(ctx, next_method, it, 0, nil) + let next = JS_Call(ctx, nextMethod, it, 0, nil) if JS_IsException(next): return err() defer: JS_FreeValue(ctx, next) - let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().str_refs[DONE]) + let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().strRefs[jstDone]) if JS_IsException(doneVal): return err() defer: JS_FreeValue(ctx, doneVal) let done = ?fromJS[bool](ctx, doneVal) if done: break - let valueVal = JS_GetProperty(ctx, next, ctx.getOpaque().str_refs[VALUE]) + let valueVal = JS_GetProperty(ctx, next, ctx.getOpaque().strRefs[jstValue]) if JS_IsException(valueVal): return err() defer: JS_FreeValue(ctx, valueVal) @@ -224,7 +220,7 @@ proc fromJSSeq[T](ctx: JSContext; val: JSValue): JSResult[seq[T]] = return ok(s) proc fromJSSet[T](ctx: JSContext; val: JSValue): JSResult[set[T]] = - let itprop = JS_GetProperty(ctx, val, ctx.getOpaque().sym_refs[ITERATOR]) + let itprop = JS_GetProperty(ctx, val, ctx.getOpaque().symRefs[jsyIterator]) if JS_IsException(itprop): return err() defer: JS_FreeValue(ctx, itprop) @@ -232,28 +228,28 @@ proc fromJSSet[T](ctx: JSContext; val: JSValue): JSResult[set[T]] = if JS_IsException(it): return err() defer: JS_FreeValue(ctx, it) - let next_method = JS_GetProperty(ctx, it, ctx.getOpaque().str_refs[NEXT]) - if JS_IsException(next_method): + let nextMethod = JS_GetProperty(ctx, it, ctx.getOpaque().strRefs[jstNext]) + if JS_IsException(nextMethod): return err() - defer: JS_FreeValue(ctx, next_method) + defer: JS_FreeValue(ctx, nextMethod) var s: set[T] while true: - let next = JS_Call(ctx, next_method, it, 0, nil) + let next = JS_Call(ctx, nextMethod, it, 0, nil) if JS_IsException(next): return err() defer: JS_FreeValue(ctx, next) - let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().str_refs[DONE]) + let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().strRefs[jstDone]) if JS_IsException(doneVal): return err() defer: JS_FreeValue(ctx, doneVal) let done = ?fromJS[bool](ctx, doneVal) if done: break - let valueVal = JS_GetProperty(ctx, next, ctx.getOpaque().str_refs[VALUE]) + let valueVal = JS_GetProperty(ctx, next, ctx.getOpaque().strRefs[jstValue]) if JS_IsException(valueVal): return err() defer: JS_FreeValue(ctx, valueVal) - let genericRes = ?fromJS[typeof(s.items)](ctx, valueVal) + let genericRes = ?fromJS[T](ctx, valueVal) s.incl(genericRes) return ok(s) @@ -341,12 +337,14 @@ proc fromJSDict[T: JSDict](ctx: JSContext; val: JSValue): JSResult[T] = if not JS_IsUndefined(val) and not JS_IsNull(val) and not JS_IsObject(val): return err(newTypeError("Dictionary is not an object")) #TODO throw on missing required values - var d: T + var d = T() if JS_IsObject(val): for k, v in d.fieldPairs: let esm = JS_GetPropertyStr(ctx, val, k) if not JS_IsUndefined(esm): v = ?fromJS[typeof(v)](ctx, esm) + when v isnot JSValue: + JS_FreeValue(ctx, esm) return ok(d) proc fromJSArrayBuffer(ctx: JSContext; val: JSValue): JSResult[JSArrayBuffer] = @@ -377,25 +375,34 @@ proc fromJSArrayBufferView(ctx: JSContext; val: JSValue): return ok(view) proc promiseThenCallback(ctx: JSContext; this_val: JSValue; argc: cint; - argv: ptr JSValue; magic: cint; func_data: ptr JSValue): JSValue {.cdecl.} = - let op = JS_GetOpaque(func_data[], JS_GetClassID(func_data[])) - let p = cast[EmptyPromise](op) - p.resolve() - GC_unref(p) + argv: ptr UncheckedArray[JSValue]; magic: cint; + func_data: ptr UncheckedArray[JSValue]): JSValue {.cdecl.} = + let fun = func_data[0] + let op = JS_GetOpaque(fun, JS_GetClassID(fun)) + if op != nil: + let p = cast[EmptyPromise](op) + p.resolve() + GC_unref(p) + JS_SetOpaque(fun, nil) return JS_UNDEFINED proc fromJSEmptyPromise(ctx: JSContext; val: JSValue): JSResult[EmptyPromise] = if not JS_IsObject(val): return err(newTypeError("Value is not an object")) - #TODO I have a feeling this leaks memory in some cases :( var p = EmptyPromise() GC_ref(p) - var tmp = JS_NewObject(ctx) + let tmp = JS_NewObject(ctx) JS_SetOpaque(tmp, cast[pointer](p)) - var fun = JS_NewCFunctionData(ctx, promiseThenCallback, 0, 0, 1, addr tmp) - let res = JS_Invoke(ctx, val, ctx.getOpaque().str_refs[THEN], 1, addr fun) + let fun = JS_NewCFunctionData(ctx, promiseThenCallback, 0, 0, 1, + tmp.toJSValueArray()) + JS_FreeValue(ctx, tmp) + let res = JS_Invoke(ctx, val, ctx.getOpaque().strRefs[jstThen], 1, + fun.toJSValueArray()) + JS_FreeValue(ctx, fun) if JS_IsException(res): + JS_FreeValue(ctx, res) return err() + JS_FreeValue(ctx, res) return ok(p) type FromJSAllowedT = (object and not (Result|Option|Table|JSValue|JSDict| @@ -445,18 +452,25 @@ proc fromJS*[T](ctx: JSContext; val: JSValue): JSResult[T] = else: return fromJS2(ctx, val, $T) -const JS_ATOM_TAG_INT = cuint(1u32 shl 31) +const JS_ATOM_TAG_INT = 1u32 shl 31 func JS_IsNumber*(v: JSAtom): JS_BOOL = - return (cast[cuint](v) and JS_ATOM_TAG_INT) != 0 + return (uint32(v) and JS_ATOM_TAG_INT) != 0 -func fromJS*[T: string|uint32](ctx: JSContext; atom: JSAtom): Opt[T] = - when T is SomeNumber: +func fromJS*[T: string|uint32|JSAtom](ctx: JSContext; atom: JSAtom): Opt[T] = + when T is JSAtom: + return ok(atom) + elif T is SomeNumber: if JS_IsNumber(atom): - return ok(T(cast[uint32](atom) and (not JS_ATOM_TAG_INT))) + return ok(uint32(atom) and (not JS_ATOM_TAG_INT)) + return err() else: - let val = JS_AtomToValue(ctx, atom) - return toString(ctx, val) + let cs = JS_AtomToCString(ctx, atom) + if cs == nil: + return err() + let s = $cs + JS_FreeCString(ctx, cs) + return ok(s) proc fromJSPObj[T](ctx: JSContext; val: JSValue): JSResult[ptr T] = return cast[JSResult[ptr T]](fromJSPObj0(ctx, val, $T)) diff --git a/src/js/javascript.nim b/src/js/javascript.nim index 8a1a0794..2266a3c7 100644 --- a/src/js/javascript.nim +++ b/src/js/javascript.nim @@ -30,8 +30,8 @@ # can only be used on object fields. (I initially wanted to use the same # keyword, unfortunately that didn't work out.) # {.jsgetprop.} for property getters. Called when GetOwnProperty would return -# nothing. The key must be either a string or an integer (preferably uint32), -# since it is converted from a JSAtom. +# nothing. The key must be either a JSAtom, uint32 or string. (Note that the +# string option copies.) # {.jssetprop.} for property setters. Called on SetProperty - in fact this # is the set() method of Proxy, except it always returns true. Same rules as # jsgetprop for keys. @@ -77,11 +77,11 @@ export JS_EVAL_FLAG_STRIP, JS_EVAL_FLAG_COMPILE_ONLY -export JSRuntime, JSContext, JSValue, JSClassID +export JSRuntime, JSContext, JSValue, JSClassID, JSAtom export JS_GetGlobalObject, JS_FreeValue, JS_IsException, JS_GetPropertyStr, - JS_IsFunction, JS_NewCFunctionData, JS_Call, JS_DupValue + JS_IsFunction, JS_NewCFunctionData, JS_Call, JS_DupValue, JS_IsUndefined when sizeof(int) < sizeof(int64): export quickjs.`==` @@ -159,40 +159,41 @@ func newJSCFunction*(ctx: JSContext; name: string; fun: JSCFunction; return JS_NewCFunction2(ctx, fun, cstring(name), cint(argc), proto, cint(magic)) -proc free*(ctx: var JSContext) = +proc free*(ctx: JSContext) = var opaque = ctx.getOpaque() if opaque != nil: - for a in opaque.sym_refs: + for a in opaque.symRefs: JS_FreeAtom(ctx, a) - for a in opaque.str_refs: + for a in opaque.strRefs: JS_FreeAtom(ctx, a) + for v in opaque.valRefs: + JS_FreeValue(ctx, v) for classid, v in opaque.ctors: JS_FreeValue(ctx, v) - JS_FreeValue(ctx, opaque.Array_prototype_values) - JS_FreeValue(ctx, opaque.Object_prototype_valueOf) - JS_FreeValue(ctx, opaque.Uint8Array_ctor) - JS_FreeValue(ctx, opaque.Set_ctor) - JS_FreeValue(ctx, opaque.Function_ctor) - for v in opaque.err_ctors: + for v in opaque.errCtorRefs: JS_FreeValue(ctx, v) + if opaque.globalUnref != nil: + opaque.globalUnref() GC_unref(opaque) JS_FreeContext(ctx) - ctx = nil -proc free*(rt: var JSRuntime) = +proc free*(rt: JSRuntime) = let opaque = rt.getOpaque() GC_unref(opaque) JS_FreeRuntime(rt) runtimes.del(runtimes.find(rt)) - rt = nil -proc setGlobal*[T](ctx: JSContext; global: JSValue; obj: T) = +proc setGlobal*[T](ctx: JSContext; obj: T) = # Add JSValue reference. - let p = JS_VALUE_GET_PTR(global) - let header = cast[ptr JSRefCountHeader](p) - inc header.ref_count - ctx.setOpaque(global, cast[pointer](obj)) + let global = JS_GetGlobalObject(ctx) + let opaque = cast[pointer](obj) + ctx.setOpaque(global, opaque) GC_ref(obj) + let rtOpaque = JS_GetRuntime(ctx).getOpaque() + ctx.getOpaque().globalUnref = proc() = + GC_unref(obj) + rtOpaque.plist.del(opaque) + JS_FreeValue(ctx, global) proc setInterruptHandler*(rt: JSRuntime; cb: JSInterruptHandler; opaque: pointer = nil) = @@ -266,13 +267,13 @@ func newJSClass*(ctx: JSContext; cdef: JSClassDefConst; tname: string; ctxOpaque.htmldda = result if finalizer != nil: rtOpaque.fins[result] = finalizer - var proto: JSValue - if parent != 0: + let proto = if parent != 0: let parentProto = JS_GetClassProto(ctx, parent) - proto = JS_NewObjectProtoClass(ctx, parentProto, parent) + let x = JS_NewObjectProtoClass(ctx, parentProto, parent) JS_FreeValue(ctx, parentProto) + x else: - proto = JS_NewObject(ctx) + JS_NewObject(ctx) if funcs.len > 0: # We avoid funcs being GC'ed by putting the list in rtOpaque. # (QuickJS uses the pointer later.) @@ -282,11 +283,12 @@ func newJSClass*(ctx: JSContext; cdef: JSClassDefConst; tname: string; cint(funcs.len)) #TODO check if this is an indexed property getter if cdef.exotic != nil and cdef.exotic.get_own_property != nil: - let val = JS_DupValue(ctx, ctxOpaque.Array_prototype_values) - doAssert JS_SetProperty(ctx, proto, ctxOpaque.sym_refs[ITERATOR], val) == 1 + let val = JS_DupValue(ctx, ctxOpaque.valRefs[jsvArrayPrototypeValues]) + let itSym = ctxOpaque.symRefs[jsyIterator] + doAssert JS_SetProperty(ctx, proto, itSym, val) == 1 let news = JS_NewAtomString(ctx, cdef.class_name) doAssert not JS_IsException(news) - ctx.definePropertyC(proto, ctxOpaque.sym_refs[TO_STRING_TAG], + ctx.definePropertyC(proto, ctxOpaque.symRefs[jsyToStringTag], JS_DupValue(ctx, news)) JS_SetClassProto(ctx, result, proto) ctx.addClassUnforgeable(proto, result, parent, unforgeable) @@ -295,7 +297,7 @@ func newJSClass*(ctx: JSContext; cdef: JSClassDefConst; tname: string; assert ctxOpaque.gclaz == "" ctxOpaque.gclaz = tname ctxOpaque.gparent = parent - ctx.definePropertyC(global, ctxOpaque.sym_refs[TO_STRING_TAG], + ctx.definePropertyC(global, ctxOpaque.symRefs[jsyToStringTag], JS_DupValue(ctx, news)) if JS_SetPrototype(ctx, global, proto) != 1: raise newException(Defect, "Failed to set global prototype: " & @@ -313,7 +315,7 @@ func newJSClass*(ctx: JSContext; cdef: JSClassDefConst; tname: string; cint(staticfuns.len)) JS_SetConstructor(ctx, jctor, proto) if errid.isSome: - ctx.getOpaque().err_ctors[errid.get] = JS_DupValue(ctx, jctor) + ctx.getOpaque().errCtorRefs[errid.get] = JS_DupValue(ctx, jctor) ctxOpaque.ctors[result] = JS_DupValue(ctx, jctor) if not nointerface: if JS_IsNull(namespace): @@ -322,6 +324,8 @@ func newJSClass*(ctx: JSContext; cdef: JSClassDefConst; tname: string; JS_FreeValue(ctx, global) else: ctx.definePropertyCW(namespace, $cdef.class_name, jctor) + else: + JS_FreeValue(ctx, jctor) type FuncParam = tuple name: string @@ -596,7 +600,7 @@ proc addUnionParamBranch(gen: var JSFuncGenerator; query, newBranch: NimNode; func isSequence*(ctx: JSContext; o: JSValue): bool = if not JS_IsObject(o): return false - let prop = JS_GetProperty(ctx, o, ctx.getOpaque().sym_refs[ITERATOR]) + let prop = JS_GetProperty(ctx, o, ctx.getOpaque().symRefs[jsyIterator]) # prop can't be exception (throws_ref_error is 0 and tag is object) result = not JS_IsUndefined(prop) JS_FreeValue(ctx, prop) @@ -1358,10 +1362,9 @@ func jsname(info: RegistryInfo): string = return info.tname proc newRegistryInfo(t: NimNode; name: string): RegistryInfo = - let info = RegistryInfo( + return RegistryInfo( t: t, name: name, - dfin: ident("js_" & t.strVal & "ClassCheckDestroy"), classDef: ident("classDef"), tabList: newNimNode(nnkBracket), tabUnforgeable: newNimNode(nnkBracket), @@ -1374,9 +1377,6 @@ proc newRegistryInfo(t: NimNode; name: string): RegistryInfo = propHasFun: newNilLit(), propNamesFun: newNilLit() ) - if info.tname notin jsDtors: - warning("No destructor has been defined for type " & info.tname) - return info proc bindConstructor(stmts: NimNode; info: var RegistryInfo): NimNode = if info.ctorFun != nil: @@ -1604,14 +1604,21 @@ proc bindEndStmts(endstmts: NimNode; info: RegistryInfo) = ) let `classDef` = JSClassDefConst(addr cd)) -macro registerType*(ctx: typed; t: typed; parent: JSClassID = 0, - asglobal = false, nointerface = false, name: static string = "", - has_extra_getset: static bool = false, - extra_getset: static openArray[TabGetSet] = [], - namespace: JSValue = JS_NULL, errid = opt(JSErrorEnum), - ishtmldda = false): JSClassID = +macro registerType*(ctx: typed; t: typed; parent: JSClassID = 0; + asglobal: static bool = false; nointerface = false; name: static string = ""; + has_extra_getset: static bool = false; + extra_getset: static openArray[TabGetSet] = []; namespace = JS_NULL; + errid = opt(JSErrorEnum); ishtmldda = false): JSClassID = var stmts = newStmtList() var info = newRegistryInfo(t, name) + if not asglobal: + info.dfin = ident("js_" & t.strVal & "ClassCheckDestroy") + if info.tname notin jsDtors: + warning("No destructor has been defined for type " & info.tname) + else: + info.dfin = newNilLit() + if info.tname in jsDtors: + error("Global object " & info.tname & " must not have a destructor!") let pragmas = findPragmas(t) stmts.registerGetters(info, pragmas.jsget) stmts.registerSetters(info, pragmas.jsset) @@ -1623,7 +1630,8 @@ macro registerType*(ctx: typed; t: typed; parent: JSClassID = 0, # been passed to it at all. stmts.bindExtraGetSet(info, extra_getset) let sctr = stmts.bindConstructor(info) - stmts.bindCheckDestroy(info) + if not asglobal: + stmts.bindCheckDestroy(info) let endstmts = newStmtList() endstmts.bindEndStmts(info) let tabList = info.tabList diff --git a/src/js/jsutils.nim b/src/js/jsutils.nim new file mode 100644 index 00000000..b8a8398e --- /dev/null +++ b/src/js/jsutils.nim @@ -0,0 +1,9 @@ +import bindings/quickjs + +template toJSValueArray*(a: openArray[JSValue]): ptr UncheckedArray[JSValue] = + cast[ptr UncheckedArray[JSValue]](unsafeAddr a[0]) + +# Warning: this must be a template, because we're taking the address of +# the passed value, and Nim is pass-by-value. +template toJSValueArray*(a: JSValue): ptr UncheckedArray[JSValue] = + cast[ptr UncheckedArray[JSValue]](unsafeAddr a) diff --git a/src/js/opaque.nim b/src/js/opaque.nim index 490747bc..93900502 100644 --- a/src/js/opaque.nim +++ b/src/js/opaque.nim @@ -5,17 +5,24 @@ import js/error import types/opt type - JSSymbolRefs* = enum - ITERATOR = "iterator" - ASYNC_ITERATOR = "asyncIterator" - TO_STRING_TAG = "toStringTag" - - JSStrRefs* = enum - DONE = "done" - VALUE = "value" - NEXT = "next" - PROTOTYPE = "prototype" - THEN = "then" + JSSymbolRef* = enum + jsyIterator = "iterator" + jsyAsyncIterator = "asyncIterator" + jsyToStringTag = "toStringTag" + + JSStrRef* = enum + jstDone = "done" + jstValue = "value" + jstNext = "next" + jstPrototype = "prototype" + jstThen = "then" + + JSValueRef* = enum + jsvArrayPrototypeValues = "Array.prototype.values" + jsvUint8Array = "Uint8Array" + jsvObjectPrototypeValueOf = "Object.prototype.valueOf" + jsvSet = "Set" + jsvFunction = "Function" JSContextOpaque* = ref object creg*: Table[string, JSClassID] @@ -28,15 +35,12 @@ type unforgeable*: Table[JSClassID, seq[JSCFunctionListEntry]] gclaz*: string gparent*: JSClassID - sym_refs*: array[JSSymbolRefs, JSAtom] - str_refs*: array[JSStrRefs, JSAtom] - Array_prototype_values*: JSValue - Object_prototype_valueOf*: JSValue - Uint8Array_ctor*: JSValue - Set_ctor*: JSValue - Function_ctor*: JSValue - err_ctors*: array[JSErrorEnum, JSValue] + symRefs*: array[JSSymbolRef, JSAtom] + strRefs*: array[JSStrRef, JSAtom] + valRefs*: array[JSValueRef, JSValue] + errCtorRefs*: array[JSErrorEnum, JSValue] htmldda*: JSClassID # only one of these exists: document.all. + globalUnref*: proc() {.closure.} JSFinalizerFunction* = proc(rt: JSRuntime; val: JSValue) {.nimcall.} @@ -51,41 +55,26 @@ func newJSContextOpaque*(ctx: JSContext): JSContextOpaque = let opaque = JSContextOpaque() block: # get well-known symbols and other functions let global = JS_GetGlobalObject(ctx) - block: - let sym = JS_GetPropertyStr(ctx, global, "Symbol") - for s in JSSymbolRefs: - let name = $s - let val = JS_GetPropertyStr(ctx, sym, cstring(name)) - assert JS_IsSymbol(val) - opaque.sym_refs[s] = JS_ValueToAtom(ctx, val) - JS_FreeValue(ctx, val) - JS_FreeValue(ctx, sym) - for s in JSStrRefs: - let ss = $s - opaque.str_refs[s] = JS_NewAtomLen(ctx, cstring(ss), csize_t(ss.len)) - block: - let arrproto = JS_GetClassProto(ctx, JS_CLASS_ARRAY) - opaque.Array_prototype_values = JS_GetPropertyStr(ctx, arrproto, - "values") - JS_FreeValue(ctx, arrproto) - block: - let objproto = JS_GetClassProto(ctx, JS_CLASS_OBJECT) - opaque.Object_prototype_valueOf = JS_GetPropertyStr(ctx, objproto, - "valueOf") - JS_FreeValue(ctx, objproto) - block: - opaque.Uint8Array_ctor = JS_GetPropertyStr(ctx, global, "Uint8Array") - assert not JS_IsException(opaque.Uint8Array_ctor) - block: - opaque.Set_ctor = JS_GetPropertyStr(ctx, global, "Set") - assert not JS_IsException(opaque.Set_ctor) - block: - opaque.Function_ctor = JS_GetPropertyStr(ctx, global, "Function") - assert not JS_IsException(opaque.Function_ctor) + let sym = JS_GetPropertyStr(ctx, global, "Symbol") + for s in JSSymbolRef: + let name = $s + let val = JS_GetPropertyStr(ctx, sym, cstring(name)) + assert JS_IsSymbol(val) + opaque.symRefs[s] = JS_ValueToAtom(ctx, val) + JS_FreeValue(ctx, val) + JS_FreeValue(ctx, sym) + for s in JSStrRef: + let ss = $s + opaque.strRefs[s] = JS_NewAtomLen(ctx, cstring(ss), csize_t(ss.len)) + for s in JSValueRef: + let ss = $s + let ret = JS_Eval(ctx, cstring(ss), csize_t(ss.len), "<init>", 0) + assert JS_IsFunction(ctx, ret) + opaque.valRefs[s] = ret for e in JSErrorEnum: let s = $e let err = JS_GetPropertyStr(ctx, global, cstring(s)) - opaque.err_ctors[e] = err + opaque.errCtorRefs[e] = err JS_FreeValue(ctx, global) return opaque diff --git a/src/js/tojs.nim b/src/js/tojs.nim index 2ee8fd47..7831a6a9 100644 --- a/src/js/tojs.nim +++ b/src/js/tojs.nim @@ -44,6 +44,7 @@ import bindings/quickjs import io/promise import js/error import js/jstypes +import js/jsutils import js/opaque import js/typeptr import types/opt @@ -148,8 +149,8 @@ proc newFunction*(ctx: JSContext; args: openArray[string]; body: string): for arg in args: paramList.add(toJS(ctx, arg)) paramList.add(toJS(ctx, body)) - let fun = JS_CallConstructor(ctx, ctx.getOpaque().Function_ctor, - cint(paramList.len), addr paramList[0]) + let fun = JS_CallConstructor(ctx, ctx.getOpaque().valRefs[jsvFunction], + cint(paramList.len), paramList.toJSValueArray()) for param in paramList: JS_FreeValue(ctx, param) return fun @@ -234,7 +235,8 @@ proc toJS*[T](ctx: JSContext; s: set[T]): JSValue = var a = toJS(ctx, x) if JS_IsException(a): return a - let ret = JS_CallConstructor(ctx, ctx.getOpaque().Set_ctor, 1, addr a) + let ret = JS_CallConstructor(ctx, ctx.getOpaque().valRefs[jsvSet], 1, + a.toJSValueArray()) JS_FreeValue(ctx, a) return ret @@ -319,12 +321,12 @@ proc toJS(ctx: JSContext; j: JSValue): JSValue = proc toJS(ctx: JSContext; promise: EmptyPromise): JSValue = var resolving_funcs: array[2, JSValue] - let jsPromise = JS_NewPromiseCapability(ctx, addr resolving_funcs[0]) + let jsPromise = JS_NewPromiseCapability(ctx, resolving_funcs.toJSValueArray()) if JS_IsException(jsPromise): return JS_EXCEPTION promise.then(proc() = - var x = JS_UNDEFINED - let res = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED, 1, addr x) + let res = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED, 1, + JS_UNDEFINED.toJSValueArray()) JS_FreeValue(ctx, res) JS_FreeValue(ctx, resolving_funcs[0]) JS_FreeValue(ctx, resolving_funcs[1])) @@ -332,12 +334,13 @@ proc toJS(ctx: JSContext; promise: EmptyPromise): JSValue = proc toJS[T](ctx: JSContext; promise: Promise[T]): JSValue = var resolving_funcs: array[2, JSValue] - let jsPromise = JS_NewPromiseCapability(ctx, addr resolving_funcs[0]) + let jsPromise = JS_NewPromiseCapability(ctx, resolving_funcs.toJSValueArray()) if JS_IsException(jsPromise): return JS_EXCEPTION promise.then(proc(x: T) = - var x = toJS(ctx, x) - let res = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED, 1, addr x) + let x = toJS(ctx, x) + let res = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED, 1, + x.toJSValueArray()) JS_FreeValue(ctx, res) JS_FreeValue(ctx, x) JS_FreeValue(ctx, resolving_funcs[0]) @@ -346,7 +349,7 @@ proc toJS[T](ctx: JSContext; promise: Promise[T]): JSValue = proc toJS[T, E](ctx: JSContext; promise: Promise[Result[T, E]]): JSValue = var resolving_funcs: array[2, JSValue] - let jsPromise = JS_NewPromiseCapability(ctx, addr resolving_funcs[0]) + let jsPromise = JS_NewPromiseCapability(ctx, resolving_funcs.toJSValueArray()) if JS_IsException(jsPromise): return JS_EXCEPTION promise.then(proc(x: Result[T, E]) = @@ -355,7 +358,8 @@ proc toJS[T, E](ctx: JSContext; promise: Promise[Result[T, E]]): JSValue = JS_UNDEFINED else: toJS(ctx, x.get) - let res = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED, 1, unsafeAddr x) + let res = JS_Call(ctx, resolving_funcs[0], JS_UNDEFINED, 1, + x.toJSValueArray()) JS_FreeValue(ctx, res) JS_FreeValue(ctx, x) else: # err @@ -363,7 +367,8 @@ proc toJS[T, E](ctx: JSContext; promise: Promise[Result[T, E]]): JSValue = JS_UNDEFINED else: toJS(ctx, x.error) - let res = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1, unsafeAddr x) + let res = JS_Call(ctx, resolving_funcs[1], JS_UNDEFINED, 1, + x.toJSValueArray()) JS_FreeValue(ctx, res) JS_FreeValue(ctx, x) JS_FreeValue(ctx, resolving_funcs[0]) @@ -376,8 +381,8 @@ proc toJS*(ctx: JSContext; err: JSError): JSValue = var msg = toJS(ctx, err.message) if JS_IsException(msg): return msg - let ctor = ctx.getOpaque().err_ctors[err.e] - let ret = JS_CallConstructor(ctx, ctor, 1, addr msg) + let ctor = ctx.getOpaque().errCtorRefs[err.e] + let ret = JS_CallConstructor(ctx, ctor, 1, msg.toJSValueArray()) JS_FreeValue(ctx, msg) return ret @@ -385,9 +390,9 @@ proc toJS*(ctx: JSContext; abuf: JSArrayBuffer): JSValue = return JS_NewArrayBuffer(ctx, abuf.p, abuf.len, abuf.dealloc, nil, false) proc toJS*(ctx: JSContext; u8a: JSUint8Array): JSValue = - var jsabuf = toJS(ctx, u8a.abuf) - let ctor = ctx.getOpaque().Uint8Array_ctor - let ret = JS_CallConstructor(ctx, ctor, 1, addr jsabuf) + let jsabuf = toJS(ctx, u8a.abuf) + let ctor = ctx.getOpaque().valRefs[jsvUint8Array] + let ret = JS_CallConstructor(ctx, ctor, 1, jsabuf.toJSValueArray()) JS_FreeValue(ctx, jsabuf) return ret |