diff options
| author | bptato <nincsnevem662@gmail.com> | 2022-09-12 00:30:21 +0200 |
|---|---|---|
| committer | bptato <nincsnevem662@gmail.com> | 2022-09-12 00:30:21 +0200 |
| commit | 51ea622d58bfca19212fac1800cfb033bb85ec39 (patch) | |
| tree | b75891690f67b190c60584751f2a30c96f342fdc /src | |
| parent | e38402dfa1bbc33db6b9d9736517eb45533d595c (diff) | |
| download | chawan-51ea622d58bfca19212fac1800cfb033bb85ec39.tar.gz | |
Add JS binding generation
Diffstat (limited to 'src')
| -rw-r--r-- | src/bindings/quickjs.nim | 296 | ||||
| -rw-r--r-- | src/config/config.nim | 32 | ||||
| -rw-r--r-- | src/display/client.nim (renamed from src/client.nim) | 365 | ||||
| -rw-r--r-- | src/io/buffer.nim | 47 | ||||
| -rw-r--r-- | src/io/lineedit.nim | 6 | ||||
| -rw-r--r-- | src/io/loader.nim | 83 | ||||
| -rw-r--r-- | src/io/process.nim | 22 | ||||
| -rw-r--r-- | src/io/socketstream.nim | 35 | ||||
| -rw-r--r-- | src/io/term.nim | 30 | ||||
| -rw-r--r-- | src/js/javascript.nim | 1224 | ||||
| -rw-r--r-- | src/main.nim | 4 | ||||
| -rw-r--r-- | src/types/url.nim | 204 |
12 files changed, 1993 insertions, 355 deletions
diff --git a/src/bindings/quickjs.nim b/src/bindings/quickjs.nim index edda5c39..bdd156e2 100644 --- a/src/bindings/quickjs.nim +++ b/src/bindings/quickjs.nim @@ -26,22 +26,54 @@ when hlib != "": when sizeof(int) < sizeof(int64): {.passC: "-DJS_NAN_BOXING".} type - JSValue* {.importc: "JSValue", header: qjsheader.} = uint64 + JSValue* {.importc, header: qjsheader.} = uint64 # uh this won't compile you're on your own else: type - JSValueUnion {.union.} = object - int32: int32 - float64: float64 - `ptr`: pointer - JSValue* {.importc: "JSValue", header: qjsheader.} = object - u: JSValueUnion - tag: int64 + JSValueUnion* {.importc, header: qjsheader, union.} = object + int32*: int32 + float64*: float64 + `ptr`*: pointer + JSValue* {.importc, header: qjsheader.} = object + u*: JSValueUnion + tag*: int64 type JSRuntime* = ptr object JSContext* = ptr object JSCFunction* = proc (ctx: JSContext, this_val: JSValue, argc: int, argv: ptr JSValue): JSValue {.cdecl.} + JSGetterFunction* = proc(ctx: JSContext, this_val: JSValue): JSValue {.cdecl.} + JSSetterFunction* = proc(ctx: JSContext, this_val: JSValue, val: JSValue): JSValue {.cdecl.} + JSInterruptHandler* = proc (rt: JSRuntime, opaque: pointer): int {.cdecl.} + JSClassID* = uint32 + JSAtom* = uint32 + JSClassFinalizer* = proc (rt: JSRuntime, val: JSValue) {.cdecl.} + JSClassGCMark* = proc (rt: JSRuntime, val: JSValue, mark_func: JS_MarkFunc) {.cdecl.} + JS_MarkFunc* = proc (rt: JSRuntime, gp: ptr JSGCObjectHeader) {.cdecl.} + JSGCObjectHeader* {.importc, header: qjsheader.} = object + JSClassDef* {.importc, header: qjsheader.} = object + class_name*: cstring + finalizer*: JSClassFinalizer + gc_mark*: JSClassGCMark + call*: pointer + exotic*: pointer + JSMemoryUsage* = object + malloc_size*, malloc_limit*, memory_used_size*: int64 + malloc_count*: int64 + memory_used_count*: int64 + atom_count*, atom_size*: int64 + str_count*, str_size*: int64 + obj_count*, obj_size*: int64 + prop_count*, prop_size*: int64 + shape_count*, shape_size*: int64 + js_func_count*, js_func_size*, js_func_code_size*: int64 + js_func_pc2line_count*, js_func_pc2line_size*: int64 + c_func_count*, array_count*: int64 + fast_array_count*, fast_array_elements*: int64 + binary_object_count*, binary_object_size*: int64 + + JSClassDefConst* {.importc: "const JSClassDef *", header: qjsheader.} = ptr JSClassDef + JSCFunctionEnum* {.size: sizeof(cint).} = enum JS_CFUNC_generic, JS_CFUNC_generic_magic, JS_CFUNC_constructor, JS_CFUNC_constructor_magic, JS_CFUNC_constructor_or_func, @@ -49,6 +81,61 @@ type JS_CFUNC_getter, JS_CFUNC_setter, JS_CFUNC_getter_magic, JS_CFUNC_setter_magic, JS_CFUNC_iterator_next +type + JSCFunctionType* {.importc, union.} = object + generic*: JSCFunction + getter*: JSGetterFunction + setter*: JSSetterFunction + + JSCFunctionListEntryFunc = object + length*: uint8 + cproto*: JSCFunctionEnum + cfunc*: JSCFunctionType + + JSCFunctionListEntryGetset = object + get*: JSCFunctionType + set*: JSCFunctionType + + JSCFunctionListEntryAlias = object + name: cstring + base: cint + + JSCFunctionListEntryPropList = object + tab: ptr JSCfunctionListEntry + len: cint + + JSCFunctionListEntryU* {.union.} = object + `func`* {.importc: "func".}: JSCFunctionListEntryFunc + getset: JSCFunctionListEntryGetset + alias: JSCFunctionListEntryAlias + prop_list: JSCFunctionListEntryPropList + str: cstring + i32: int32 + i64: int64 + f64: cdouble + + JSCFunctionListEntry* {.importc.} = object + name*: cstring + prop_flags*: uint8 + def_type*: uint8 + magic*: int16 + u* {.importc.}: JSCFunctionListEntryU + + JSRefCountHeader* {.importc.} = object + ref_count* {.importc.}: cint + + JS_BOOL* = distinct cint + + JSPropertyEnum* {.importc.} = object + is_enumerable*: JS_BOOL + atom*: JSAtom + +converter toBool*(js: JS_BOOl): bool {.inline.} = + cast[cint](js) != 0 + +converter toJSBool*(b: bool): JS_BOOL {.inline.} = + cast[JS_BOOL](cint(b)) + const ## all tags with a reference count are negative JS_TAG_FIRST* = -10 ## first negative tag JS_TAG_BIG_INT* = -10 @@ -73,6 +160,15 @@ const ## all tags with a reference count are negative template JS_MKVAL*(t, val: untyped): JSValue = JSValue(u: JSValueUnion(`int32`: val), tag: t) +template JS_MKPTR*(t, p: untyped): JSValue = + JSValue(u: JSValueUnion(`ptr`: p), tag: t) + +template JS_VALUE_GET_TAG*(v: untyped): int = + cast[int32](v.tag) + +template JS_VALUE_GET_PTR*(v: untyped): pointer = + cast[pointer](v.u) + const JS_NULL* = JS_MKVAL(JS_TAG_NULL, 0) JS_UNDEFINED* = JS_MKVAL(JS_TAG_UNDEFINED, 0) @@ -92,44 +188,176 @@ const JS_EVAL_FLAG_STRIP* = (1 shl 4) ## force 'strip' mode JS_EVAL_FLAG_COMPILE_ONLY* = (1 shl 5) ## internal use -{.push header: qjsheader, cdecl.} +const + JS_DEF_CFUNC* = 0 + JS_DEF_CGETSET* = 1 + JS_DEF_CGETSET_MAGIC* = 2 + JS_DEF_PROP_STRING* = 3 + JS_DEF_PROP_INT32* = 4 + JS_DEF_PROP_INT64* = 5 + JS_DEF_PROP_DOUBLE* = 6 + JS_DEF_PROP_UNDEFINED* = 7 + JS_DEF_OBJECT* = 8 + JS_DEF_ALIAS* = 9 -proc JS_NewRuntime*(): JSRuntime {.importc: "JS_NewRuntime".} -proc JS_FreeRuntime*(rt: JSRuntime) {.importc: "JS_FreeRuntime".} +const + JS_PROP_CONFIGURABLE* = (1 shl 0) + JS_PROP_WRITABLE* = (1 shl 1) + JS_PROP_ENUMERABLE* = (1 shl 2) + JS_PROP_C_W_E* = (JS_PROP_CONFIGURABLE or JS_PROP_WRITABLE or JS_PROP_ENUMERABLE) + JS_PROP_LENGTH* = (1 shl 3) # used internally in Arrays + JS_PROP_TMASK* = (3 shl 4) # mask for NORMAL, GETSET, VARREF, AUTOINIT + JS_PROP_NORMAL* = (0 shl 4) + JS_PROP_GETSET* = (1 shl 4) + JS_PROP_VARREF* = (2 shl 4) # used internally + JS_PROP_AUTOINIT* = (3 shl 4) # used internally + +const + JS_GPN_STRING_MASK* = (1 shl 0) + JS_GPN_SYMBOL_MASK* = (1 shl 1) + JS_GPN_PRIVATE_MASK* = (1 shl 2) + JS_GPN_ENUM_ONLY* = (1 shl 3) + JS_GPN_SET_ENUM* = (1 shl 4) + + +template JS_CFUNC_DEF*(n: string, len: uint8, func1: JSCFunction): JSCFunctionListEntry = + JSCFunctionListEntry(name: cstring(n), + prop_flags: JS_PROP_WRITABLE or JS_PROP_CONFIGURABLE, + def_type: JS_DEF_CFUNC, + u: JSCFunctionListEntryU( + `func`: JSCFunctionListEntryFunc(length: len, + cproto: JS_CFUNC_generic, + cfunc: JSCFunctionType(generic: func1)))) + +template JS_CGETSET_DEF*(n: string, fgetter, fsetter: untyped): JSCFunctionListEntry = + JSCFunctionListEntry(name: cstring(n), + prop_flags: JS_PROP_CONFIGURABLE, + def_type: JS_DEF_CGETSET, + u: JSCFunctionListEntryU( + getset: JSCFunctionListEntryGetSet(get: JSCFunctionType(getter: fgetter), + set: JSCFunctionType(setter: fsetter)))) + +{.push header: qjsheader, importc, cdecl.} + +proc JS_NewRuntime*(): JSRuntime +proc JS_FreeRuntime*(rt: JSRuntime) +proc JS_GetRuntime*(ctx: JSContext): JSRuntime + +proc JS_ComputeMemoryUsage*(rt: JSRuntime, s: ptr JSMemoryUsage) -proc JS_NewContext*(rt: JSRuntime): JSContext {.importc: "JS_NewContext".} -proc JS_NewContextRaw*(rt: JSRuntime): JSContext {.importc: "JS_NewContextRaw".} -proc JS_FreeContext*(ctx: JSContext) {.importc: "JS_FreeContext".} +proc JS_NewContext*(rt: JSRuntime): JSContext +proc JS_NewContextRaw*(rt: JSRuntime): JSContext +proc JS_FreeContext*(ctx: JSContext) -proc JS_GetGlobalObject*(ctx: JSContext): JSValue {.importc: "JS_GetGlobalObject".} +proc JS_GetGlobalObject*(ctx: JSContext): JSValue +proc JS_IsInstanceOf*(ctx: JSContext, val: JSValue, obj: JSValue): cint -proc JS_NewObject*(ctx: JSContext): JSValue {.importc: "JS_NewObject".} +proc JS_NewObject*(ctx: JSContext): JSValue +proc JS_NewObjectClass*(ctx: JSContext, class_id: JSClassID): JSValue +proc JS_NewObjectProto*(ctx: JSContext, proto: JSValue): JSValue +proc JS_SetOpaque*(obj: JSValue, opaque: pointer) +proc JS_GetOpaque*(obj: JSValue, class_id: JSClassID): pointer +proc JS_GetOpaque2*(ctx: JSContext, obj: JSValue, class_id: JSClassID): pointer -proc JS_NewCFunction2*(ctx: JSContext, cfunc: JSCFunction, name: cstring, length: int, proto: JSCFunctionEnum, magic: int): JSValue {.importc: "JS_NewCFunction2".} -proc JS_NewCFunction*(ctx: JSContext, cfunc: JSCFunction, name: cstring, length: int): JSValue {.importc: "JS_NewCFunction".} +proc JS_NewClassID*(pclass_id: ptr JSClassID): JSClassID +proc JS_NewClass*(rt: JSRuntime, class_id: JSClassID, class_def: ptr JSClassDef): cint +proc JS_IsRegisteredClass*(rt: JSRuntime, class_id: JSClassID): cint +proc JS_SetClassProto*(ctx: JSContext, class_id: JSClassID, obj: JSValue) +proc JS_GetClassProto*(ctx: JSContext, class_id: JSClassID): JSValue +proc JS_SetConstructor*(ctx: JSContext, func_obj: JSValue, proto: JSValue) +proc JS_SetPrototype*(ctx: JSContext, obj: JSValue, proto_val: JSValue): cint -proc JS_SetPropertyStr*(ctx: JSContext, this_obj: JSValue, prop: cstring, val: JSValue): int - {.importc: "JS_SetPropertyStr".} +proc JS_NewBool*(ctx: JSContext, val: JS_BOOL): JSValue +proc JS_NewInt32*(ctx: JSContext, val: int32): JSValue +proc JS_NewCatchOffset*(ctx: JSContext, val: int32): JSValue +proc JS_NewInt64*(ctx: JSContext, val: int64): JSValue +proc JS_NewUint32*(ctx: JSContext, val: uint32): JSValue +proc JS_NewUint64*(ctx: JSContext, val: uint64): JSValue +proc JS_NewBigInt64*(ctx: JSContext, val: int64): JSValue +proc JS_NewBigUInt64*(ctx: JSContext, val: uint64): JSValue +proc JS_NewFloat64*(ctx: JSContext, val: uint64): JSValue + +proc JS_NewAtomLen*(ctx: JSContext, str: cstring, len: csize_t): JSAtom +proc JS_ValueToAtom*(ctx: JSContext, val: JSValue): JSAtom +proc JS_AtomToValue*(ctx: JSContext, atom: JSAtom): JSValue +proc JS_FreeAtom*(ctx: JSContext, atom: JSAtom) +proc JS_FreeAtomRT*(rt: JSRuntime, atom: JSAtom) + +proc JS_NewCFunction2*(ctx: JSContext, cfunc: JSCFunction, name: cstring, length: cint, proto: JSCFunctionEnum, magic: cint): JSValue +proc JS_NewCFunction*(ctx: JSContext, cfunc: JSCFunction, name: cstring, length: cint): JSValue + +proc JS_NewString*(ctx: JSContext, str: cstring): JSValue + +proc JS_SetPropertyStr*(ctx: JSContext, this_obj: JSValue, prop: cstring, val: JSValue): cint +proc JS_SetPropertyFunctionList*(ctx: JSContext, obj: JSValue, tab: ptr JSCFunctionListEntry, len: cint) +proc JS_GetProperty*(ctx: JSContext, this_obj: JSValue, prop: JSAtom): JSValue proc JS_GetPropertyStr*(ctx: JSContext, this_obj: JSValue, prop: cstring): JSValue - {.importc: "JS_GetPropertyStr".} +proc JS_GetPropertyUint32*(ctx: JSContext, this_obj: JSValue, idx: uint32): JSValue +proc JS_GetOwnPropertyNames*(ctx: JSContext, ptab: ptr ptr JSPropertyEnum, plen: ptr uint32, obj: JSValue, flags: cint): int + +proc JS_Call*(ctx: JSContext, func_obj, this_obj: JSValue, argc: cint, argv: ptr JSValue): JSValue + +proc JS_DefineProperty*(ctx: JSContext, this_obj: JSValue, prop: JSAtom, val: JSValue, getter: JSValue, setter: JSValue, flags: cint): cint +proc JS_DefinePropertyValue*(ctx: JSContext, this_obj: JSValue, prop: JSAtom, val: JSValue, flags: cint): cint +proc JS_DefinePropertyValueUint32*(ctx: JSContext, this_obj: JSValue, idx: uint32, val: JSValue, flags: cint): cint +proc JS_DefinePropertyValueStr*(ctx: JSContext, this_obj: JSValue, prop: cstring, val: JSValue, flags: cint): cint +proc JS_DefinePropertyValueGetSet*(ctx: JSContext, this_obj: JSValue, prop: JSAtom, getter: JSValue, setter: JSValue, flags: cint): cint + +proc JS_FreeValue*(ctx: JSContext, v: JSValue) +proc JS_FreeValueRT*(rt: JSRuntime, v: JSValue) +proc JS_DupValue*(ctx: JSContext, v: JSValue): JSValue + +proc JS_ToBool*(ctx: JSContext, val: JSValue): cint # return -1 for JS_EXCEPTION +proc JS_ToInt32*(ctx: JSContext, pres: ptr int32, val: JSValue): cint +proc JS_ToUint32*(ctx: JSContext, pres: ptr uint32, val: JSValue): cint +proc JS_ToInt64*(ctx: JSContext, pres: ptr int64, val: JSValue): cint +proc JS_ToIndex*(ctx: JSContext, plen: ptr uint64, val: JSValue): cint +proc JS_ToFloat64*(ctx: JSContext, pres: ptr float64, val: JSValue): cint +# return an exception if 'val' is a Number +proc JS_ToBigInt64*(ctx: JSContext, pres: ptr int64, val: JSValue): cint +# same as JS_ToInt64 but allow BigInt +proc JS_ToInt64Ext*(ctx: JSContext, pres: ptr int64, val: JSValue): cint + +proc JS_ToCStringLen*(ctx: JSContext, plen: ptr csize_t, val1: JSValue): cstring +proc JS_ToCString*(ctx: JSContext, val1: JSValue): cstring +proc JS_FreeCString*(ctx: JSContext, `ptr`: cstring) -proc JS_FreeValue*(ctx: JSContext, v: JSValue) {.importc: "JS_FreeValue".} +proc JS_Eval*(ctx: JSContext, input: cstring, input_len: cint, filename: cstring, eval_flags: cint): JSValue +proc JS_SetInterruptHandler*(rt: JSRuntime, cb: JSInterruptHandler, opaque: pointer) +proc JS_SetCanBlock*(rt: JSRuntime, can_block: JS_BOOL) -# use toString if possible -proc JS_ToCStringLen*(ctx: JSContext, plen: ptr int, val1: JSValue): cstring {.importc: "JS_ToCStringLen".} -proc JS_ToCString*(ctx: JSContext, val1: JSValue): cstring {.importc: "JS_ToCString".} -proc JS_FreeCString*(ctx: JSContext, `ptr`: cstring) {.importc: "JS_FreeCString".} +#TODO these should be remapped +proc JS_IsNumber*(v: JSValue): JS_BOOL +proc JS_IsBigInt*(v: JSValue): JS_BOOL +proc JS_IsBigFloat*(v: JSValue): JS_BOOL +proc JS_IsBigDecimal*(v: JSValue): JS_BOOL +proc JS_IsBool*(v: JSValue): JS_BOOL +proc JS_IsNull*(v: JSValue): JS_BOOL +proc JS_IsUndefined*(v: JSValue): JS_BOOL +proc JS_IsException*(v: JSValue): JS_BOOL +proc JS_IsUninitialized*(v: JSValue): JS_BOOL +proc JS_IsString*(v: JSValue): JS_BOOL +proc JS_IsSymbol*(v: JSValue): JS_BOOL +proc JS_IsObject*(v: JSValue): JS_BOOL -proc JS_Eval*(ctx: JSContext, input: cstring, input_len: int, filename: cstring, eval_flags: int): JSValue {.importc: "JS_Eval".} +proc JS_IsFunction*(ctx: JSContext, val: JSValue): JS_BOOL +proc JS_IsArray*(ctx: JSContext, v: JSValue): cint -proc JS_IsException*(v: JSValue): bool {.importc: "JS_IsException".} -proc JS_IsError*(v: JSValue): bool {.importc: "JS_IsError".} -proc JS_IsUndefined*(v: JSValue): bool {.importc: "JS_IsUndefined".} +proc JS_Throw*(ctx: JSContext, obj: JSValue): JSValue +proc JS_GetException*(ctx: JSContext): JSValue +proc JS_IsError*(ctx: JSContext, v: JSValue): JS_BOOL +proc JS_ThrowSyntaxError*(ctx: JSContext, fmt: cstring): JSValue {.varargs, discardable.} +proc JS_ThrowTypeError*(ctx: JSContext, fmt: cstring): JSValue {.varargs, discardable.} +proc JS_ThrowReferenceError*(ctx: JSContext, fmt: cstring): JSValue {.varargs, discardable.} +proc JS_ThrowRangeError*(ctx: JSContext, fmt: cstring): JSValue {.varargs, discardable.} +proc JS_ThrowInternalError*(ctx: JSContext, fmt: cstring): JSValue {.varargs, discardable.} -proc JS_GetException*(ctx: JSContext): JSValue {.importc: "JS_GetException".} +proc JS_GetRuntimeOpaque*(rt: JSRuntime): pointer +proc JS_SetRuntimeOpaque*(rt: JSRuntime, p: pointer) -proc JS_SetContextOpaque*(ctx: JSContext, opaque: pointer) {.importc: "JS_SetContextOpaque".} -proc JS_GetContextOpaque*(ctx: JSContext): pointer {.importc: "JS_GetContextOpaque".} +proc JS_SetContextOpaque*(ctx: JSContext, opaque: pointer) +proc JS_GetContextOpaque*(ctx: JSContext): pointer -proc js_free_rt*(rt: JSRuntime, p: pointer) {.importc: "js_free_rt".} +proc js_free_rt*(rt: JSRuntime, p: pointer) +proc js_free*(ctx: JSContext, p: pointer) {.pop.} diff --git a/src/config/config.nim b/src/config/config.nim index 9151628f..ddbbaa95 100644 --- a/src/config/config.nim +++ b/src/config/config.nim @@ -40,8 +40,8 @@ type ACTION_LINED_ESC ActionMap = Table[string, TwtAction] - Config = object - nmap*: ActionMap + Config* = object + nmap*: Table[string, string] lemap*: ActionMap stylesheet*: string ambiguous_double*: bool @@ -107,10 +107,23 @@ func constructActionTable*(origTable: ActionMap): ActionMap = newTable[realk] = v return newTable -func getAction(s: string): TwtAction = - if s == "NULL": - return NO_ACTION - return parseEnum[TwtAction]("ACTION_" & s) +func constructActionTable2*(origTable: Table[string, string]): Table[string, string] = + var strs: seq[string] + for k in origTable.keys: + let realk = getRealKey(k) + var teststr = "" + for c in realk: + teststr &= c + strs.add(teststr) + + for k, v in origTable: + let realk = getRealKey(k) + var teststr = "" + for c in realk: + teststr &= c + if strs.contains(teststr): + result[teststr] = "client.feedNext()" + result[realk] = v func getLineAction(s: string): TwtAction = if s == "NULL": @@ -138,7 +151,8 @@ proc parseConfig(config: var Config, dir: string, t: TomlValue) = config.ambiguous_double = general["double-width-ambiguous"].b if "page" in t: for k, v in t["page"].pairs: - config.nmap[getRealKey(k)] = getAction(v.s) + #config.nmap[getRealKey(k)] = getAction(v.s) + config.nmap[getRealKey(k)] = v.s if "line" in t: for k, v in t["line"].pairs: config.lemap[getRealKey(k)] = getLineAction(v.s) @@ -186,10 +200,10 @@ proc readConfig(dir: string) = if fs != nil: gconfig.parseConfig(dir, fs) -proc getNormalAction*(s: string): TwtAction = +proc getNormalAction*(s: string): string = if gconfig.nmap.hasKey(s): return gconfig.nmap[s] - return NO_ACTION + return "" proc getLinedAction*(s: string): TwtAction = if gconfig.lemap.hasKey(s): diff --git a/src/client.nim b/src/display/client.nim index eb48a30a..6e3c8c45 100644 --- a/src/client.nim +++ b/src/display/client.nim @@ -19,41 +19,37 @@ import utils/twtstr type Client* = ref ClientObj - ClientObj = object - buffer: Buffer + ClientObj* = object + buffer*: Buffer feednext: bool s: string iserror: bool errormessage: string userstyle: CSSStylesheet loader: FileLoader + console: Console jsrt: JSRuntime jsctx: JSContext regex: Option[Regex] revsearch: bool needsauth: bool redirecturl: Option[Url] + cmdmode: bool - ActionError = object of IOError - LoadError = object of ActionError - InterruptError = object of LoadError + Console* = ref object + err*: Stream + lastbuf*: Buffer + ibuf: string -proc statusMode(client: Client) = - print(HVP(client.buffer.height + 1, 1)) - print(EL()) + ActionError* = object of IOError + LoadError* = object of ActionError + InterruptError* = object of LoadError -proc js_console_log(ctx: JSContext, this: JSValue, argc: int, argv: ptr JSValue): JSValue {.cdecl.} = - let opaque = ctx.getOpaque() - for i in 0..<argc: - let arg = getJSObject(ctx, argv, i) - if i != 0: - opaque.err &= ' ' - let str = arg.toString() - if str.isnone: - return JS_EXCEPTION - opaque.err &= str.get - opaque.err &= '\n' - return JS_UNDEFINED +proc readChar(console: Console): char = + if console.ibuf == "": + return stdin.readChar() + result = console.ibuf[0] + console.ibuf = console.ibuf.substr(1) proc `=destroy`(client: var ClientObj) = if client.jsctx != nil: @@ -61,18 +57,9 @@ proc `=destroy`(client: var ClientObj) = if client.jsrt != nil: free(client.jsrt) -proc newClient*(): Client = - new(result) - result.loader = newFileLoader() - let rt = newJSRuntime() - let ctx = rt.newJSContext() - result.jsrt = rt - result.jsctx = ctx - var global = ctx.getGlobalObject() - let console = newJSObject(result.jsctx) - console.setFunctionProperty("log", js_console_log) - global.setProperty("console", console) - free(global) +proc statusMode(client: Client) = + print(HVP(client.buffer.height + 1, 1)) + print(EL()) proc loadError(s: string) = raise newException(LoadError, s) @@ -80,9 +67,6 @@ proc loadError(s: string) = proc actionError(s: string) = raise newException(ActionError, s) -proc interruptError() = - raise newException(InterruptError, "Interrupted") - proc addBuffer(client: Client) = if client.buffer == nil: client.buffer = newBuffer() @@ -98,43 +82,39 @@ proc addBuffer(client: Client) = client.buffer.userstyle = client.userstyle client.buffer.markcolor = gconfig.markcolor -proc prevBuffer(client: Client) = +proc prevBuffer(client: Client) {.jsfunc.} = if client.buffer.prev != nil: client.buffer = client.buffer.prev client.buffer.redraw = true -proc nextBuffer(client: Client) = +proc nextBuffer(client: Client) {.jsfunc.} = if client.buffer.next != nil: client.buffer = client.buffer.next client.buffer.redraw = true proc discardBuffer(buffer: Buffer) = + if buffer.next == nil and buffer.prev == nil: + actionError("Cannot discard last buffer!") + if buffer.sourcepair != nil: + buffer.sourcepair.sourcepair = nil if buffer.next != nil: - if buffer.sourcepair != nil: - buffer.sourcepair.sourcepair = nil buffer.next.prev = buffer.prev - buffer.redraw = true - elif buffer.prev != nil: - if buffer.sourcepair != nil: - buffer.sourcepair.sourcepair = nil + if buffer.prev != nil: buffer.prev.next = buffer.next - buffer.redraw = true - -proc discardBuffer(client: Client) = - if client.buffer.next != nil: - if client.buffer.sourcepair != nil: - client.buffer.sourcepair.sourcepair = nil - client.buffer.next.prev = client.buffer.prev - client.buffer = client.buffer.next - client.buffer.redraw = true - elif client.buffer.prev != nil: - if client.buffer.sourcepair != nil: - client.buffer.sourcepair.sourcepair = nil - client.buffer.prev.next = client.buffer.next - client.buffer = client.buffer.prev - client.buffer.redraw = true + buffer.sourcepair = nil + buffer.next = nil + buffer.prev = nil + +proc discardBuffer(client: Client) {.jsfunc.} = + let old = client.buffer + if old.next != nil: + client.buffer = old.next + elif old.prev != nil: + client.buffer = old.prev else: - actionError("Can't discard last buffer!") + actionError("Cannot discard last buffer!") + discardBuffer(old) + client.buffer.redraw = true proc setupBuffer(client: Client) = let buffer = client.buffer @@ -143,7 +123,7 @@ proc setupBuffer(client: Client) = buffer.gotoAnchor() buffer.redraw = true -proc dupeBuffer(client: Client, location = none(Url)) = +proc dupeBuffer(client: Client, location = none(URL)) {.jsfunc.} = let prev = client.buffer client.addBuffer() client.buffer.contenttype = prev.contenttype @@ -161,8 +141,7 @@ proc readPipe(client: Client, ctype: string) = client.buffer.contenttype = if ctype != "": ctype else: "text/plain" client.buffer.ispipe = true client.buffer.istream = newFileStream(stdin) - const url = parseUrl("file://-").get - client.buffer.location = url + client.buffer.location = newURL("file://-") client.buffer.load() #TODO is this portable at all? if reopen(stdin, "/dev/tty", fmReadWrite): @@ -172,9 +151,7 @@ proc readPipe(client: Client, ctype: string) = # Load request in a new buffer. var g_client: Client -proc gotoUrl(client: Client, request: Request, prevurl = none(Url), force = false, ctype = "") = - setControlCHook(proc() {.noconv.} = - raise newException(InterruptError, "Interrupted")) +proc gotoUrl(client: Client, request: Request, prevurl = none(URL), force = false, ctype = "") = if force or prevurl.isnone or not prevurl.get.equals(request.url, true) or prevurl.get.equals(request.url) or request.httpmethod != HTTP_GET: let page = client.loader.doRequest(request) @@ -183,10 +160,6 @@ proc gotoUrl(client: Client, request: Request, prevurl = none(Url), force = fals if page.body != nil: client.addBuffer() g_client = client - setControlCHook(proc() {.noconv.} = - if g_client.buffer.prev != nil or g_client.buffer.next != nil: - g_client.discardBuffer() - interruptError()) client.buffer.contenttype = if ctype != "": ctype else: page.contenttype client.buffer.istream = page.body client.buffer.location = request.url @@ -200,7 +173,7 @@ proc gotoUrl(client: Client, request: Request, prevurl = none(Url), force = fals loadError("Couldn't find anchor " & request.url.anchor) # Relative gotoUrl: either to prevurl, or if that's none, client.buffer.url. -proc gotoUrl(client: Client, url: string, prevurl = none(Url), force = false, ctype = "") = +proc gotoUrl(client: Client, url: string, prevurl = none(URL), force = false, ctype = "") = var prevurl = prevurl if prevurl.isnone and client.buffer != nil: prevurl = client.buffer.location.some @@ -233,13 +206,13 @@ proc loadUrl(client: Client, url: string, ctype = "") = client.gotoUrl("https://" & url, none(Url), true, ctype) # Reload the page in a new buffer, then kill the previous buffer. -proc reloadPage(client: Client) = +proc reloadPage(client: Client) {.jsfunc.} = let buf = client.buffer - client.gotoUrl(newRequest(client.buffer.location), none(Url), true, client.buffer.contenttype) + client.gotoUrl(newRequest(client.buffer.location), none(URL), true, client.buffer.contenttype) discardBuffer(buf) # Open a URL prompt and visit the specified URL. -proc changeLocation(client: Client) = +proc changeLocation(client: Client) {.jsfunc.} = let buffer = client.buffer var url = buffer.location.serialize(true) client.statusMode() @@ -247,12 +220,12 @@ proc changeLocation(client: Client) = if status: client.loadUrl(url) -proc click(client: Client) = +proc click(client: Client) {.jsfunc.} = let req = client.buffer.click() if req.issome: client.gotoUrl(req.get, client.buffer.location.some) -proc toggleSource*(client: Client) = +proc toggleSource*(client: Client) {.jsfunc.} = let buffer = client.buffer if buffer.sourcepair != nil: client.buffer = buffer.sourcepair @@ -272,55 +245,84 @@ proc toggleSource*(client: Client) = client.buffer.contenttype = "text/html" client.setupBuffer() -proc command(client: Client) = - var iput: string - client.statusMode() - let status = readLine("COMMAND: ", iput, client.buffer.width) - if status and iput.len > 0: - let ret = client.jsctx.eval(iput, "<stdin>", JS_EVAL_TYPE_GLOBAL) - let opaque = client.jsctx.getOpaque() - if ret.isException(): - let ex = client.jsctx.getException() - let str = ex.toString() - if str.issome: - opaque.err &= str.get & '\n' - var stack = ex.getProperty("stack") - if not stack.isUndefined(): - let str = stack.toString() - if str.issome: - opaque.err &= str.get & '\n' - free(stack) - free(ex) +proc interruptHandler(rt: JSRuntime, opaque: pointer): int {.cdecl.} = + let client = cast[Client](opaque) + try: + let c = stdin.readChar() + if c == char(3): #C-c + client.console.ibuf = "" + return 1 else: - let str = ret.toString() + client.console.ibuf &= c + except IOError: + discard + return 0 + +proc evalJS(client: Client, src, filename: string): JSObject = + unblockStdin() + return client.jsctx.eval(src, filename, JS_EVAL_TYPE_GLOBAL) + +proc command(client: Client, src: string) = + restoreStdin() + let previ = client.console.err.getPosition() + let ret = client.evalJS(src, "<command>") + if ret.isException(): + let ex = client.jsctx.getException() + let str = ex.toString() + if str.issome: + client.console.err.write(str.get & '\n') + var stack = ex.getProperty("stack") + if not stack.isUndefined(): + let str = stack.toString() if str.issome: - opaque.err &= str.get & '\n' - free(ret) + client.console.err.write(str.get) + free(stack) + free(ex) + else: + let str = ret.toString() + if str.issome: + client.console.err.write(str.get & '\n') + free(ret) + g_client = client + client.console.err.setPosition(previ) + if client.console.lastbuf == nil or client.console.lastbuf != client.buffer: client.addBuffer() - g_client = client - setControlCHook(proc() {.noconv.} = - if g_client.buffer.prev != nil or g_client.buffer.next != nil: - g_client.discardBuffer() - interruptError()) - client.buffer.istream = newStringStream(opaque.err) + client.buffer.istream = newStringStream(client.console.err.readAll()) #TODO client.buffer.contenttype = "text/plain" - client.setupBuffer() + client.buffer.location = parseUrl("javascript:void(0);").get + client.console.lastbuf = client.buffer + else: + client.buffer.istream = newStringStream(client.buffer.source & client.console.err.readAll()) + client.buffer.streamclosed = false + client.setupBuffer() + client.buffer.cursorLastLine() -proc searchNext(client: Client) = +proc command(client: Client): bool {.jsfunc.} = + var iput: string + client.statusMode() + let status = readLine("COMMAND: ", iput, client.buffer.width) + if status: + client.command(iput) + return status + +proc commandMode(client: Client) {.jsfunc.} = + client.cmdmode = client.command() + +proc searchNext(client: Client) {.jsfunc.} = if client.regex.issome: if not client.revsearch: discard client.buffer.cursorNextMatch(client.regex.get) else: discard client.buffer.cursorPrevMatch(client.regex.get) -proc searchPrev(client: Client) = +proc searchPrev(client: Client) {.jsfunc.} = if client.regex.issome: if not client.revsearch: discard client.buffer.cursorPrevMatch(client.regex.get) else: discard client.buffer.cursorNextMatch(client.regex.get) -proc search(client: Client) = +proc search(client: Client) {.jsfunc.} = client.statusMode() var iput: string let status = readLine("/", iput, client.buffer.width) @@ -330,7 +332,7 @@ proc search(client: Client) = client.revsearch = false client.searchNext() -proc searchBack(client: Client) = +proc searchBack(client: Client) {.jsfunc.} = client.statusMode() var iput: string let status = readLine("?", iput, client.buffer.width) @@ -340,7 +342,7 @@ proc searchBack(client: Client) = client.revsearch = true client.searchNext() -proc isearch(client: Client) = +proc isearch(client: Client) {.jsfunc.} = client.statusMode() var iput: string let cpos = client.buffer.cpos @@ -379,7 +381,7 @@ proc isearch(client: Client) = else: client.buffer.cpos = cpos -proc isearchBack(client: Client) = +proc isearchBack(client: Client) {.jsfunc.} = client.statusMode() var iput: string let cpos = client.buffer.cpos @@ -415,71 +417,62 @@ proc isearchBack(client: Client) = else: client.buffer.cpos = cpos -proc quit(client: Client) = +proc quit(client: Client) {.jsfunc.} = eraseScreen() print(HVP(0, 0)) quit(0) +proc feedNext(client: Client) {.jsfunc.} = + client.feednext = true + +#TODO move this to a pager module or something +proc cursorLeft(client: Client) {.jsfunc.} = client.buffer.cursorLeft() +proc cursorDown(client: Client) {.jsfunc.} = client.buffer.cursorDown() +proc cursorUp(client: Client) {.jsfunc.} = client.buffer.cursorUp() +proc cursorRight(client: Client) {.jsfunc.} = client.buffer.cursorRight() +proc cursorLineBegin(client: Client) {.jsfunc.} = client.buffer.cursorLineBegin() +proc cursorLineEnd(client: Client) {.jsfunc.} = client.buffer.cursorLineEnd() +proc cursorNextWord(client: Client) {.jsfunc.} = client.buffer.cursorNextWord() +proc cursorPrevWord(client: Client) {.jsfunc.} = client.buffer.cursorPrevWord() +proc cursorNextLink(client: Client) {.jsfunc.} = client.buffer.cursorNextLink() +proc cursorPrevLink(client: Client) {.jsfunc.} = client.buffer.cursorPrevLink() +proc pageDown(client: Client) {.jsfunc.} = client.buffer.pageDown() +proc pageUp(client: Client) {.jsfunc.} = client.buffer.pageUp() +proc pageRight(client: Client) {.jsfunc.} = client.buffer.pageRight() +proc pageLeft(client: Client) {.jsfunc.} = client.buffer.pageLeft() +proc halfPageDown(client: Client) {.jsfunc.} = client.buffer.halfPageDown() +proc halfPageUp(client: Client) {.jsfunc.} = client.buffer.halfPageUp() +proc cursorFirstLine(client: Client) {.jsfunc.} = client.buffer.cursorFirstLine() +proc cursorLastLine(client: Client) {.jsfunc.} = client.buffer.cursorLastLine() +proc cursorTop(client: Client) {.jsfunc.} = client.buffer.cursorTop() +proc cursorMiddle(client: Client) {.jsfunc.} = client.buffer.cursorMiddle() +proc cursorBottom(client: Client) {.jsfunc.} = client.buffer.cursorBottom() +proc cursorLeftEdge(client: Client) {.jsfunc.} = client.buffer.cursorLeftEdge() +proc cursorVertMiddle(client: Client) {.jsfunc.} = client.buffer.cursorVertMiddle() +proc cursorRightEdge(client: Client) {.jsfunc.} = client.buffer.cursorRightEdge() +proc centerLine(client: Client) {.jsfunc.} = client.buffer.centerLine() +proc scrollDown(client: Client) {.jsfunc.} = client.buffer.scrollDown() +proc scrollUp(client: Client) {.jsfunc.} = client.buffer.scrollUp() +proc scrollLeft(client: Client) {.jsfunc.} = client.buffer.scrollLeft() +proc scrollRight(client: Client) {.jsfunc.} = client.buffer.scrollRight() +proc lineInfo(client: Client) {.jsfunc.} = client.buffer.lineInfo() +proc reshape(client: Client) {.jsfunc.} = client.buffer.reshape = true +proc redraw(client: Client) {.jsfunc.} = client.buffer.redraw = true + proc input(client: Client) = - let buffer = client.buffer + if client.cmdmode: + client.commandMode() + return if not client.feednext: client.s = "" else: client.feednext = false - let c = getch() + restoreStdin() + let c = client.console.readChar() client.s &= c + let action = getNormalAction(client.s) - case action - of ACTION_QUIT: client.quit() - of ACTION_CURSOR_LEFT: buffer.cursorLeft() - of ACTION_CURSOR_DOWN: buffer.cursorDown() - of ACTION_CURSOR_UP: buffer.cursorUp() - of ACTION_CURSOR_RIGHT: buffer.cursorRight() - of ACTION_CURSOR_LINEBEGIN: buffer.cursorLineBegin() - of ACTION_CURSOR_LINEEND: buffer.cursorLineEnd() - of ACTION_CURSOR_NEXT_WORD: buffer.cursorNextWord() - of ACTION_CURSOR_PREV_WORD: buffer.cursorPrevWord() - of ACTION_CURSOR_NEXT_LINK: buffer.cursorNextLink() - of ACTION_CURSOR_PREV_LINK: buffer.cursorPrevLink() - of ACTION_PAGE_DOWN: buffer.pageDown() - of ACTION_PAGE_UP: buffer.pageUp() - of ACTION_PAGE_RIGHT: buffer.pageRight() - of ACTION_PAGE_LEFT: buffer.pageLeft() - of ACTION_HALF_PAGE_DOWN: buffer.halfPageDown() - of ACTION_HALF_PAGE_UP: buffer.halfPageUp() - of ACTION_CURSOR_FIRST_LINE: buffer.cursorFirstLine() - of ACTION_CURSOR_LAST_LINE: buffer.cursorLastLine() - of ACTION_CURSOR_TOP: buffer.cursorTop() - of ACTION_CURSOR_MIDDLE: buffer.cursorMiddle() - of ACTION_CURSOR_BOTTOM: buffer.cursorBottom() - of ACTION_CURSOR_LEFT_EDGE: buffer.cursorLeftEdge() - of ACTION_CURSOR_VERT_MIDDLE: buffer.cursorVertMiddle() - of ACTION_CURSOR_RIGHT_EDGE: buffer.cursorRightEdge() - of ACTION_CENTER_LINE: buffer.centerLine() - of ACTION_SCROLL_DOWN: buffer.scrollDown() - of ACTION_SCROLL_UP: buffer.scrollUp() - of ACTION_SCROLL_LEFT: buffer.scrollLeft() - of ACTION_SCROLL_RIGHT: buffer.scrollRight() - of ACTION_CLICK: client.click() - of ACTION_CHANGE_LOCATION: client.changeLocation() - of ACTION_DUPE_BUFFER: client.dupeBuffer() - of ACTION_LINE_INFO: buffer.lineInfo() - of ACTION_FEED_NEXT: client.feednext = true - of ACTION_RELOAD: client.reloadPage() - of ACTION_RESHAPE: buffer.reshape = true - of ACTION_REDRAW: buffer.redraw = true - of ACTION_TOGGLE_SOURCE: client.toggleSource() - of ACTION_PREV_BUFFER: client.prevBuffer() - of ACTION_NEXT_BUFFER: client.nextBuffer() - of ACTION_DISCARD_BUFFER: client.discardBuffer() - of ACTION_COMMAND: client.command() - of ACTION_SEARCH: client.search() - of ACTION_SEARCH_BACK: client.searchBack() - of ACTION_ISEARCH: client.isearch() - of ACTION_ISEARCH_BACK: client.isearchBack() - of ACTION_SEARCH_NEXT: client.searchNext() - of ACTION_SEARCH_PREV: client.searchPrev() - else: discard + discard client.evalJS(action, "<command>") proc followRedirect(client: Client) @@ -523,11 +516,7 @@ proc followRedirect(client: Client) = proc inputLoop(client: Client) = while true: g_client = client - setControlCHook(proc() {.noconv.} = - g_client.buffer.setStatusMessage("Interrupted rendering procedure") - g_client.buffer.redraw = true - g_client.buffer.reshape = false - g_client.inputLoop()) + restoreStdin() client.followRedirect() client.checkAuth() client.buffer.refreshBuffer() @@ -562,3 +551,41 @@ proc launchClient*(client: Client, pages: seq[string], ctype: string, dump: bool while buffer.prev != nil: buffer = buffer.prev buffer.drawBuffer() + +proc nimGCStats(client: Client): string {.jsfunc.} = + return GC_getStatistics() + +proc jsGCStats(client: Client): string {.jsfunc.} = + return client.jsrt.getMemoryUsage() + +func newConsole(): Console = + new(result) + result.err = newStringStream() + +proc log(console: Console, ss: varargs[string]) {.jsfunc.} = + for i in 0..<ss.len: + console.err.write(ss[i]) + if i != ss.high: + console.err.write(' ') + console.err.write('\n') + +proc newClient*(): Client = + new(result) + result.loader = newFileLoader() + result.console = newConsole() + let rt = newJSRuntime() + rt.setInterruptHandler(interruptHandler, cast[pointer](result)) + let ctx = rt.newJSContext() + result.jsrt = rt + result.jsctx = ctx + var global = ctx.getGlobalObject() + discard ctx.registerType(Client, asglobal = true, addto = some(global)) + global.setOpaque(result) + global.setProperty("client", global) + + let consoleClassId = ctx.registerType(Console) + let jsConsole = ctx.newJSObject(consoleClassId) + jsConsole.setOpaque(result.console) + global.setProperty("console", jsConsole) + + ctx.addUrlModule() diff --git a/src/io/buffer.nim b/src/io/buffer.nim index 52a55819..8b1268ef 100644 --- a/src/io/buffer.nim +++ b/src/io/buffer.nim @@ -931,12 +931,12 @@ proc displayStatusMessage*(buffer: Buffer) = print(SGR()) # https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set -proc constructEntryList(form: HTMLFormElement, submitter: Element = nil, encoding: string = ""): Table[string, string] = +proc constructEntryList(form: HTMLFormElement, submitter: Element = nil, encoding: string = ""): seq[tuple[name, value: string]] = if form.constructingentrylist: return form.constructingentrylist = true - var entrylist: Table[string, string] + var entrylist: seq[tuple[name, value: string]] for field in form.controls: if field.findAncestor({TAG_DATALIST}) != nil or field.attrb("disabled") or @@ -950,8 +950,8 @@ proc constructEntryList(form: HTMLFormElement, submitter: Element = nil, encodin field.attr("name") & '.' else: "" - entrylist[name & 'x'] = $field.xcoord - entrylist[name & 'y'] = $field.ycoord + entrylist.add((name & 'x', $field.xcoord)) + entrylist.add((name & 'y', $field.ycoord)) continue #TODO custom elements @@ -965,13 +965,13 @@ proc constructEntryList(form: HTMLFormElement, submitter: Element = nil, encodin let field = HTMLSelectElement(field) for option in field.options: if option.selected or option.disabled: - entrylist[name] = option.value + entrylist.add((name, option.value)) elif field.tagType == TAG_INPUT and HTMLInputElement(field).inputType in {INPUT_CHECKBOX, INPUT_RADIO}: let value = if field.attr("value") != "": field.attr("value") else: "on" - entrylist[name] = value + entrylist.add((name, value)) elif field.tagType == TAG_INPUT and HTMLInputElement(field).inputType == INPUT_FILE: #TODO file discard @@ -980,10 +980,10 @@ proc constructEntryList(form: HTMLFormElement, submitter: Element = nil, encodin encoding else: "UTF-8" - entrylist[name] = charset + entrylist.add((name, charset)) else: if field.tagType == TAG_INPUT: - entrylist[name] = HTMLInputElement(field).value + entrylist.add((name, HTMLInputElement(field).value)) else: assert false if field.tagType == TAG_TEXTAREA or @@ -991,20 +991,11 @@ proc constructEntryList(form: HTMLFormElement, submitter: Element = nil, encodin if field.attr("dirname") != "": let dirname = field.attr("dirname") let dir = "ltr" #TODO bidi - entrylist[dirname] = dir + entrylist.add((dirname, dir)) form.constructingentrylist = false return entrylist -#https://url.spec.whatwg.org/#concept-urlencoded-serializer -proc serializeApplicationXWWFormUrlEncoded(kvs: Table[string, string]): string = - for name, value in kvs: - if result != "": - result &= '&' - result.percentEncode(name, ApplicationXWWWFormUrlEncodedSet, true) - result &= '=' - result.percentEncode(value, ApplicationXWWWFormUrlEncodedSet, true) - #https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart/form-data-encoding-algorithm proc makeCRLF(s: string): string = result = newStringOfCap(s.len) @@ -1022,19 +1013,19 @@ proc makeCRLF(s: string): string = result &= s[i] inc i -proc serializeMultipartFormData(kvs: Table[string, string]): MimeData = - for name, value in kvs: - let name = makeCRLF(name) - let value = makeCRLF(value) +proc serializeMultipartFormData(kvs: seq[(string, string)]): MimeData = + for it in kvs: + let name = makeCRLF(it[0]) + let value = makeCRLF(it[1]) result[name] = value -proc serializePlainTextFormData(kvs: Table[string, string]): string = - for name, value in kvs: +proc serializePlainTextFormData(kvs: seq[(string, string)]): string = + for it in kvs: + let (name, value) = it result &= name result &= '=' result &= value - result &= '\r' - result &= '\n' + result &= "\r\n" proc submitForm(form: HTMLFormElement, submitter: Element): Option[Request] = let entrylist = form.constructEntryList(submitter) @@ -1068,7 +1059,7 @@ proc submitForm(form: HTMLFormElement, submitter: Element): Option[Request] = #let noopener = true #TODO template mutateActionUrl() = - let query = serializeApplicationXWWFormUrlEncoded(entrylist) + let query = serializeApplicationXWWWFormUrlEncoded(entrylist) parsedaction.query = query.some return newRequest(parsedaction, httpmethod).some @@ -1078,7 +1069,7 @@ proc submitForm(form: HTMLFormElement, submitter: Element): Option[Request] = var multipart = none(MimeData) case enctype of FORM_ENCODING_TYPE_URLENCODED: - body = serializeApplicationXWWFormUrlEncoded(entrylist).some + body = serializeApplicationXWWWFormUrlEncoded(entrylist).some mimeType = $enctype of FORM_ENCODING_TYPE_MULTIPART: multipart = serializeMultipartFormData(entrylist).some diff --git a/src/io/lineedit.nim b/src/io/lineedit.nim index 5c756625..def2feb2 100644 --- a/src/io/lineedit.nim +++ b/src/io/lineedit.nim @@ -4,8 +4,9 @@ import strutils import sequtils import sugar -import utils/twtstr import config/config +import io/term +import utils/twtstr type LineState* = object news*: seq[Rune] @@ -143,7 +144,8 @@ proc readLine(state: var LineState): bool = else: state.feedNext = false - let c = getch() + restoreStdin() + let c = stdin.readChar() state.s &= c var action = getLinedAction(state.s) diff --git a/src/io/loader.nim b/src/io/loader.nim index 31b51930..7c68258e 100644 --- a/src/io/loader.nim +++ b/src/io/loader.nim @@ -15,15 +15,16 @@ import options import streams import tables import net -import os when defined(posix): import posix import bindings/curl import io/http +import io/process import io/request import io/serialize import io/socketstream +import types/mime import types/url import utils/twtstr @@ -75,88 +76,80 @@ proc loadResource(loader: FileLoader, request: Request, ostream: Stream) = ostream.swrite(-1) # error ostream.flush() -const SocketDirectory = "/tmp/cha/" -const SocketPathPrefix = SocketDirectory & "cha_sock_" -func getSocketPath(pid: Pid): string = - SocketPathPrefix & $pid - -proc runFileLoader(loader: FileLoader) = +proc runFileLoader(loader: FileLoader, loadcb: proc()) = if curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK: raise newException(Defect, "Failed to initialize libcurl.") - let path = getSocketPath(getpid()) - discard unlink(cstring(path)) - createDir(SocketDirectory) - let sock = newSocket(Domain.AF_UNIX, SockType.SOCK_STREAM, Protocol.IPPROTO_IP) - bindUnix(sock, path) - listen(sock) - stdout.write(char(0u8)) - stdout.flushFile() + let ssock = initServerSocket(getpid()) + # The server has been initialized, so the main process can resume execution. + loadcb() while true: - var sock2: Socket - sock.accept(sock2) - let istream = newSocketStream(sock2, nil) - let ostream = newSocketStream(nil, sock2) + let stream = ssock.acceptSocketStream() try: - let request = istream.readRequest() + let request = stream.readRequest() for k, v in loader.defaultHeaders.table: if k notin request.headers.table: request.headers.table[k] = v - loader.loadResource(request, ostream) + loader.loadResource(request, stream) except IOError: # End-of-file, quit. # TODO this should be EOFError break - close(sock2) + stream.close() curl_global_cleanup() - close(sock) - discard unlink(cstring(path)) + ssock.close() quit(0) proc doRequest*(loader: FileLoader, request: Request): Response = - let sock = newSocket(Domain.AF_UNIX, SockType.SOCK_STREAM, Protocol.IPPROTO_IP) - let path = getSocketPath(loader.process) - connectUnix(sock, path) - let istream = newSocketStream(nil, sock) - let ostream = newSocketStream(sock, nil) - istream.swrite(request) - istream.flush() - ostream.sread(result.res) + let stream = connectSocketStream(loader.process) + stream.swrite(request) + stream.flush() + stream.sread(result.res) if result.res == 0: - ostream.sread(result.status) - ostream.sread(result.headers) + stream.sread(result.status) + stream.sread(result.headers) if "Content-Type" in result.headers.table: result.contenttype = result.headers.table["Content-Type"][0].until(';') + else: + result.contenttype = guessContentType($request.url) if "Location" in result.headers.table: let location = result.headers.table["Location"][0] result.redirect = parseUrl(location, some(request.url)) # Only a stream of the response body may arrive after this point. - result.body = ostream + result.body = stream proc newFileLoader*(defaultHeaders: HeaderList): FileLoader = new(result) result.defaultHeaders = defaultHeaders when defined(posix): - var pipefd_b: array[0..1, cint] - if pipe(pipefd_b) == -1: + var pipefd: array[0..1, cint] + if pipe(pipefd) == -1: raise newException(Defect, "Failed to open pipe.") let pid = fork() if pid == -1: raise newException(Defect, "Failed to fork network process") elif pid == 0: # child process - let writefd = pipefd_b[1] # get write b - discard close(pipefd_b[0]) # close read b - discard dup2(writefd, stdout.getFileHandle()) - result.runFileLoader() + discard close(pipefd[0]) # close read + var writef: File + if not open(writef, FileHandle(pipefd[1]), fmWrite): + raise newException(Defect, "Failed to open input handle.") + result.runFileLoader((proc() = + writef.write(char(0u8)) + writef.flushFile() + close(writef) + discard close(pipefd[1]) + )) else: result.process = pid - let readfd = pipefd_b[0] # get read b - discard close(pipefd_b[1]) # close write b + let readfd = pipefd[0] # get read + discard close(pipefd[1]) # close write var readf: File if not open(readf, FileHandle(readfd), fmRead): raise newException(Defect, "Failed to open output handle.") - var n: uint8 - assert newFileStream(readf).readUint8() == 0u8 + assert readf.readChar() == char(0u8) + close(readf) + discard close(pipefd[0]) + proc newFileLoader*(): FileLoader = newFileLoader(DefaultHeaders) diff --git a/src/io/process.nim b/src/io/process.nim index e081ecc6..ffdf5d91 100644 --- a/src/io/process.nim +++ b/src/io/process.nim @@ -1,6 +1,12 @@ +import net +import os when defined(posix): import posix +type ServerSocket* = object + sock*: Socket + path*: string + proc doFork*(): Pid = result = fork() if result == -1: @@ -14,3 +20,19 @@ proc doFork*(): Pid = quit(0) return 0 +const SocketDirectory = "/tmp/cha/" +const SocketPathPrefix = SocketDirectory & "cha_sock_" +func getSocketPath*(pid: Pid): string = + SocketPathPrefix & $pid + +proc initServerSocket*(pid: Pid): ServerSocket = + createDir(SocketDirectory) + result.sock = newSocket(Domain.AF_UNIX, SockType.SOCK_STREAM, Protocol.IPPROTO_IP) + result.path = getSocketPath(getpid()) + discard unlink(cstring(result.path)) + bindUnix(result.sock, result.path) + listen(result.sock) + +proc close*(ssock: ServerSocket) = + close(ssock.sock) + discard unlink(cstring(ssock.path)) diff --git a/src/io/socketstream.nim b/src/io/socketstream.nim index 73a00aa2..d7f43625 100644 --- a/src/io/socketstream.nim +++ b/src/io/socketstream.nim @@ -1,37 +1,50 @@ import net import streams +when defined(posix): + import posix + +import io/process type SocketStream* = ref object of Stream - isource: Socket - osource: Socket + source: Socket isend: bool proc sockReadData(s: Stream, buffer: pointer, len: int): int = let s = SocketStream(s) - result = s.isource.recv(buffer, len) + result = s.source.recv(buffer, len) if result < 0: raise newException(Defect, "Failed to read data") elif result < len: s.isend = true proc sockWriteData(s: Stream, buffer: pointer, len: int) = - discard SocketStream(s).osource.send(buffer, len) + discard SocketStream(s).source.send(buffer, len) proc sockAtEnd(s: Stream): bool = SocketStream(s).isend proc sockClose(s: Stream) = {.cast(tags: []).}: #...sigh let s = SocketStream(s) - if s.isource != nil: - s.isource.close() - if s.osource != nil and s.isource != s.osource: - s.osource.close() + s.source.close() -func newSocketStream*(isource, osource: Socket): SocketStream = +func newSocketStream*(): SocketStream = new(result) - result.isource = isource - result.osource = osource result.readDataImpl = sockReadData result.writeDataImpl = sockWriteData result.atEndImpl = sockAtEnd result.closeImpl = sockClose + +proc connectSocketStream*(path: string): SocketStream = + result = newSocketStream() + let sock = newSocket(Domain.AF_UNIX, SockType.SOCK_STREAM, Protocol.IPPROTO_IP) + connectUnix(sock, path) + result.source = sock + +proc connectSocketStream*(pid: Pid): SocketStream = + connectSocketStream(getSocketPath(pid)) + +proc acceptSocketStream*(ssock: ServerSocket): SocketStream = + result = newSocketStream() + var sock: Socket + ssock.sock.accept(sock) + result.source = sock diff --git a/src/io/term.nim b/src/io/term.nim index 914b5398..d9609715 100644 --- a/src/io/term.nim +++ b/src/io/term.nim @@ -1,7 +1,6 @@ import terminal + import std/exitprocs -when defined(posix): - import termios type TermAttributes* = object @@ -14,6 +13,9 @@ type height_px*: int when defined(posix): + import posix + import termios + # see https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html let stdin_fileno = stdin.getFileHandle() var orig_termios: Termios @@ -27,12 +29,28 @@ when defined(posix): raw.c_iflag = raw.c_iflag and not (BRKINT or ICRNL or INPCK or ISTRIP or IXON) raw.c_oflag = raw.c_oflag and not (OPOST) raw.c_cflag = raw.c_cflag or CS8 - # we do not currently set ISIG, so that ctrl+c can be used to - # immediately return to the input loop. - #TODO set it once we have separated i/o from layout - raw.c_lflag = raw.c_lflag and not (ECHO or ICANON or IEXTEN) + raw.c_lflag = raw.c_lflag and not (ECHO or ICANON or ISIG or IEXTEN) discard tcSetAttr(stdin_fileno, TCSAFLUSH, addr raw) + var orig_flags: cint + var stdin_unblocked = false + proc unblockStdin*() = + orig_flags = fcntl(getFileHandle(stdin), F_GETFL, 0) + let flags = orig_flags or O_NONBLOCK + discard fcntl(getFileHandle(stdin), F_SETFL, flags) + stdin_unblocked = true + + proc restoreStdin*() = + if stdin_unblocked: + discard fcntl(getFileHandle(stdin), F_SETFL, orig_flags) + stdin_unblocked = false +else: + proc unblockStdin*(): cint = + discard + + proc restoreStdin*(flags: cint) = + discard + proc getTermAttributes*(): TermAttributes = if stdin.isatty(): when defined(posix): diff --git a/src/js/javascript.nim b/src/js/javascript.nim index c728283a..11253875 100644 --- a/src/js/javascript.nim +++ b/src/js/javascript.nim @@ -1,4 +1,9 @@ +import macros import options +import sequtils +import strformat +import strutils +import tables import bindings/quickjs @@ -23,17 +28,69 @@ type ctx*: JSContext val*: JSValue - JSContextOpaque* = object - err*: string + JSContextOpaque* = ref object + creg: Table[string, JSClassID] + gclaz: string + sym_iterator: JSAtom + sym_asyncIterator: JSAtom + done: JSAtom + next: JSAtom + value: JSAtom -func newJSRuntime*(): JSRuntime = + JSRuntimeOpaque* = ref object + plist: Table[pointer, pointer] + flist: seq[seq[JSCFunctionListEntry]] + + JSFunctionList* = openArray[JSCFunctionListEntry] + +func getOpaque*(ctx: JSContext): JSContextOpaque = + return cast[JSContextOpaque](JS_GetContextOpaque(ctx)) + +func getOpaque*(rt: JSRuntime): JSRuntimeOpaque = + return cast[JSRuntimeOpaque](JS_GetRuntimeOpaque(rt)) + +var runtimes {.threadVar.}: seq[JSRuntime] + +proc newJSRuntime*(): JSRuntime = result = JS_NewRuntime() + runtimes.add(result) + var opaque = new(JSRuntimeOpaque) + GC_ref(opaque) + JS_SetRuntimeOpaque(result, cast[pointer](opaque)) proc newJSContext*(rt: JSRuntime): JSContext = - result = JS_NewContext(rt) - let opaque = cast[ptr JSContextOpaque](alloc0(sizeof(JSContextOpaque))) - opaque.err = "" - JS_SetContextOpaque(result, opaque) + let ctx = JS_NewContext(rt) + var opaque = new(JSContextOpaque) + GC_ref(opaque) + + block: + let global = JS_GetGlobalObject(ctx) + block: + let sym = JS_GetPropertyStr(ctx, global, "Symbol") + block: + let it = JS_GetPropertyStr(ctx, sym, "iterator") + assert JS_IsSymbol(it) + opaque.sym_iterator = JS_ValueToAtom(ctx, it) + JS_FreeValue(ctx, it) + block: + let ait = JS_GetPropertyStr(ctx, sym, "asyncIterator") + assert JS_IsSymbol(ait) + opaque.sym_asyncIterator = JS_ValueToAtom(ctx, ait) + JS_FreeValue(ctx, ait) + block: + let s = "done" + opaque.done = JS_NewAtomLen(ctx, cstring(s), csize_t(s.len)) + block: + let s = "value" + opaque.value = JS_NewAtomLen(ctx, cstring(s), csize_t(s.len)) + block: + let s = "next" + opaque.next = JS_NewAtomLen(ctx, cstring(s), csize_t(s.len)) + JS_FreeValue(ctx, sym) + JS_FreeValue(ctx, global) + + JS_SetContextOpaque(ctx, cast[pointer](opaque)) + return ctx proc newJSContextRaw*(rt: JSRuntime): JSContext = result = JS_NewContextRaw(rt) @@ -42,16 +99,41 @@ func getJSObject*(ctx: JSContext, v: JSValue): JSObject = result.ctx = ctx result.val = v -func getJSObject*(ctx: JSContext, argv: ptr JSValue, i: int): JSObject = - getJSObject(ctx, cast[ptr JSValue](cast[int](argv) + i * sizeof(JSValue))[]) +func getJSValue*(ctx: JSContext, argv: ptr JSValue, i: int): JSValue = + cast[ptr JSValue](cast[int](argv) + i * sizeof(JSValue))[] func newJSObject*(ctx: JSContext): JSObject = result.ctx = ctx result.val = JS_NewObject(ctx) -func newJSCFunction*(ctx: JSContext, name: string, fun: JSCFunction, argc: int): JSObject = +func newJSObject*(ctx: JSContext, cid: JSClassID): JSObject = + result.ctx = ctx + result.val = JS_NewObjectClass(ctx, cid) + +func newJSObject*(ctx: JSContext, proto: JSObject): JSObject = + result.ctx = ctx + result.val = JS_NewObjectProto(ctx, proto.val) + +func getClass*(ctx: JSContext, class: string): JSClassID = + # This function *should* never fail. + ctx.getOpaque().creg[class] + +func getClassProto*(ctx: JSContext, cid: JSClassID): JSObject = + return JSObject(ctx: ctx, val: JS_GetClassProto(ctx, cid)) + +func findClass*(ctx: JSContext, class: string): Option[JSClassID] = + let opaque = ctx.getOpaque() + if class in opaque.creg: + return some(opaque.creg[class]) + return none(JSClassID) + +func newJSObject*(ctx: JSContext, class: string): JSObject = result.ctx = ctx - result.val = JS_NewCFunction(ctx, fun, cstring(name), argc) + result.val = JS_NewObjectClass(ctx, ctx.getClass(class)) + +func newJSCFunction*(ctx: JSContext, name: string, fun: JSCFunction, argc: int = 0, proto = JS_CFUNC_generic, magic = 0): JSObject = + result.ctx = ctx + result.val = JS_NewCFunction2(ctx, fun, cstring(name), cint(argc), proto, cint(magic)) func getGlobalObject*(ctx: JSContext): JSObject = result.ctx = ctx @@ -65,53 +147,1113 @@ func getProperty*(obj: JSObject, s: string): JSObject = result.ctx = obj.ctx result.val = JS_GetPropertyStr(obj.ctx, obj.val, cstring(s)); -func getOpaque*(ctx: JSContext): ptr JSContextOpaque = - return cast[ptr JSContextOpaque](JS_GetContextOpaque(ctx)) +proc free*(ctx: var JSContext) = + var opaque = ctx.getOpaque() + if opaque != nil: + JS_FreeAtom(ctx, opaque.sym_iterator) + JS_FreeAtom(ctx, opaque.sym_asyncIterator) + JS_FreeAtom(ctx, opaque.done) + JS_FreeAtom(ctx, opaque.next) + GC_unref(opaque) + JS_FreeContext(ctx) + ctx = nil + +proc free*(rt: var JSRuntime) = + let opaque = rt.getOpaque() + GC_unref(opaque) + JS_FreeRuntime(rt) + runtimes.del(runtimes.find(rt)) + rt = nil + +proc free*(obj: JSObject) = + JS_FreeValue(obj.ctx, obj.val) + #TODO maybe? obj.val = JS_NULL -func toString*(obj: JSObject): Option[string] = - var plen: int - let outp = JS_ToCStringLen(obj.ctx, addr plen, obj.val) # cstring +proc setOpaque*[T](obj: JSObject, opaque: T) = + let rt = JS_GetRuntime(obj.ctx) + let rtOpaque = rt.getOpaque() + let p = JS_VALUE_GET_PTR(obj.val) + let header = cast[ptr JSRefCountHeader](p) + inc header.ref_count # add jsvalue reference + rtOpaque.plist[cast[pointer](opaque)] = p + JS_SetOpaque(obj.val, cast[pointer](opaque)) + +func isGlobal*(ctx: JSContext, class: string): bool = + assert class != "" + return ctx.getOpaque().gclaz == class + +# A hack to retrieve a given val's class id. +# Used when we can't query ctx's hash table. +func getClassID*(val: JSValue): JSClassID = + const index = sizeof(cint) + # gc_ref_count + sizeof(uint8) + # gc_mark + sizeof(uint8) # bit field + return cast[ptr uint16](cast[int](JS_VALUE_GET_PTR(val)) + index)[] + +func getOpaque*(ctx: JSContext, val: JSValue, class: string): pointer = + # Unfortunately, we can't change the global object's class. + #TODO: or maybe we can, but I'm afraid of breaking something. + # This needs further investigation. + if ctx.isGlobal(class): + let global = ctx.getGlobalObject() + let opaque = JS_GetOpaque(global.val, 1) # JS_CLASS_OBJECT + free(global) + return opaque + return JS_GetOpaque(val, ctx.getClass(class)) + +func getOpaque*(obj: JSObject, class: string): pointer = getOpaque(obj.ctx, obj.val, class) + +proc setInterruptHandler*(rt: JSRuntime, cb: JSInterruptHandler, opaque: pointer = nil) = + JS_SetInterruptHandler(rt, cb, opaque) + +func toString*(ctx: JSContext, val: JSValue): Option[string] = + var plen: csize_t + let outp = JS_ToCStringLen(ctx, addr plen, val) # cstring if outp != nil: var ret = newString(plen) for i in 0..<plen: ret[i] = outp[i] result = some(ret) - JS_FreeCString(obj.ctx, outp) # refc + JS_FreeCString(ctx, outp) + +func toString*(obj: JSObject): Option[string] = toString(obj.ctx, obj.val) func `$`*(obj: JSObject): string = return obj.toString().get("") func isUndefined*(obj: JSObject): bool = JS_IsUndefined(obj.val) +func isNull*(obj: JSObject): bool = JS_IsNull(obj.val) func isException*(obj: JSObject): bool = JS_IsException(obj.val) +func isError*(obj: JSObject): bool = JS_IsError(obj.ctx, obj.val) + +func isGlobal*(obj: JSObject): bool = + let global = obj.ctx.getGlobalObject() + result = JS_VALUE_GET_PTR(global.val) == JS_VALUE_GET_PTR(obj.val) + +func isInstanceOf*(obj: JSObject, class: string): bool = + return obj.getOpaque(class) != nil proc setProperty*(obj: JSObject, name: string, prop: JSObject) = - discard JS_SetPropertyStr(obj.ctx, obj.val, cstring(name), prop.val) - -proc setFunctionProperty*(obj: JSObject, name: string, fun: JSCFunction) = - obj.setProperty(name, obj.ctx.newJSCFunction(name, fun, 1)) - # (proc(ctx: JSContext, obj: JSValue, argc: int, argv: ptr JSValue): JSValue {.cdecl.} = - # var invoc: seq[JSValue] - # for i in 0..<argc: - # let arg = cast[ptr JSValue](cast[int](argv) + i * sizeof(JSValue))[] - # invoc.add(arg) - # return fun(JSObject(ctx: ctx, qjs: obj), invoc) - #), cstring(name), 1)) + if JS_SetPropertyStr(obj.ctx, obj.val, cstring(name), prop.val) <= 0: + raise newException(Defect, "Failed to set property string: " & name) -proc free*(ctx: var JSContext) = - let opaque = ctx.getOpaque() - if opaque != nil: - dealloc(opaque) - JS_FreeContext(ctx) - ctx = nil +proc setProperty*(obj: JSObject, name: string, fun: JSCFunction, argc: int = 0) = + obj.setProperty(name, obj.ctx.newJSCFunction(name, fun, argc)) -proc free*(rt: var JSRuntime) = - JS_FreeRuntime(rt) - rt = nil +func newJSClass*(ctx: JSContext, cdef: JSClassDefConst, cctor: JSCFunction, funcs: JSFunctionList, parent: JSClassID = 0, asglobal = false, addto = none(JSObject)): JSClassID = + let rt = JS_GetRuntime(ctx) + discard JS_NewClassID(addr result) + var ctxOpaque = ctx.getOpaque() + var rtOpaque = rt.getOpaque() + ctxOpaque.creg[$cdef.class_name] = result + if JS_NewClass(rt, result, cdef) != 0: + raise newException(Defect, "Failed to allocate JS class: " & $cdef.class_name) + var proto: JSObject + if parent != 0: + let parentProto = ctx.getClassProto(parent) + proto = ctx.newJSObject(parentProto) + free(parentProto) + else: + proto = ctx.newJSObject() + if funcs.len > 0: + rtOpaque.flist.add(funcs.toSeq()) + JS_SetPropertyFunctionList(ctx, proto.val, addr rtOpaque.flist[^1][0], cint(funcs.len)) + JS_SetClassProto(ctx, result, proto.val) + if asglobal: + let global = ctx.getGlobalObject() + assert ctxOpaque.gclaz == "" + ctxOpaque.gclaz = $cdef.class_name + if JS_SetPrototype(ctx, global.val, proto.val) != 1: + raise newException(Defect, "Failed to set global prototype: " & $cdef.class_name) + free(global) + if addto.issome: + let jctor = ctx.newJSCFunction($cdef.class_name, cctor, 0, JS_CFUNC_constructor) + JS_SetConstructor(ctx, jctor.val, proto.val) + addto.get.setProperty($cdef.class_name, jctor) -proc free*(obj: JSObject) = - JS_FreeValue(obj.ctx, obj.val) - #TODO maybe? obj.val = JS_NULL +type FuncParam = tuple[name: string, t: NimNode, val: Option[NimNode], generic: Option[NimNode]] + +func getMinArgs(params: seq[FuncParam]): int = + for i in 0..<params.len: + let it = params[i] + if it[2].issome: + return i + let t = it.t + if t.kind == nnkBracketExpr: + if t.typeKind == varargs.getType().typeKind: + assert i == params.high, "Not even nim can properly handle this..." + return i + return params.len + +func fromJSInt[T: SomeInteger](ctx: JSContext, val: JSValue): Option[T] = + when T is int: + when sizeof(int) <= sizeof(int32): + var ret: int32 + if JS_ToInt32(ctx, addr ret, val) < 0: + return none(T) + return some(ret) + else: + var ret: int64 + if JS_ToInt64(ctx, addr ret, val) < 0: + return none(T) + return some(ret) + elif T is uint: + when sizeof(int) <= sizeof(int32): + var ret: uint32 + if JS_ToUint32(ctx, addr ret, val) < 0: + return none(T) + return some(ret) + else: + var ret: uint32 + if JS_ToUint32(ctx, addr ret, val) < 0: + return none(T) + return some(cast[uint](ret)) + elif T is int32: + var ret: int32 + if JS_ToInt32(ctx, addr ret, val) < 0: + return none(T) + return some(ret) + elif T is int64: + var ret: int64 + if JS_ToInt64(ctx, addr ret, val) < 0: + return none(T) + return some(ret) + elif T is uint32: + var ret: uint32 + if JS_ToUint32(ctx, addr ret, val) < 0: + return none(T) + return some(ret) + elif T is uint64: + var ret: uint32 + if JS_ToUint32(ctx, addr ret, val) < 0: + return none(T) + return some(cast[uint64](ret)) + +proc fromJS[T](ctx: JSContext, val: JSValue): Option[T] + +macro len(t: type tuple): int = + let i = t.getType()[1].len - 1 # - tuple + newLit(i) + +macro fromJSTupleBody(a: tuple) = + let len = a.getType().len - 1 + let done = ident("done") + result = newStmtList(quote do: + var `done`: Option[bool]) + for i in 0..<len: + result.add(quote do: + let next = JS_Call(ctx, next_method, it, 0, nil) + if JS_IsException(next): + return none(T) + defer: JS_FreeValue(ctx, next) + let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().done) + if JS_IsException(doneVal): + return none(T) + defer: JS_FreeValue(ctx, doneVal) + `done` = fromJS[bool](ctx, doneVal) + if `done`.isnone: # exception + return none(T) + if `done`.get: + JS_ThrowTypeError(ctx, "Too few arguments in sequence (got %d, expected %d)", `i`, `len`) + return none(T) + let valueVal = JS_GetProperty(ctx, next, ctx.getOpaque().value) + if JS_IsException(valueVal): + return none(T) + defer: JS_FreeValue(ctx, valueVal) + let genericRes = fromJS[typeof(result.get[`i`])](ctx, valueVal) + if genericRes.isnone: # exception + return none(T) + `a`[`i`] = genericRes.get + ) + if i == len - 1: + result.add(quote do: + var i = `i` + # we're simulating a sequence, so we must query all remaining parameters too: + while not `done`.get: + inc i + let next = JS_Call(ctx, next_method, it, 0, nil) + if JS_IsException(next): + return none(T) + defer: JS_FreeValue(ctx, next) + let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().done) + if JS_IsException(doneVal): + return none(T) + defer: JS_FreeValue(ctx, doneVal) + `done` = fromJS[bool](ctx, doneVal) + if `done`.isnone: # exception + return none(T) + if `done`.get: + JS_ThrowTypeError(ctx, "Too many arguments in sequence (got %d, expected %d)", i, `len`) + return none(T) + JS_FreeValue(ctx, JS_GetProperty(ctx, next, ctx.getOpaque().value)) + ) + +proc fromJSTuple[T: tuple](ctx: JSContext, val: JSValue): Option[T] = + let itprop = JS_GetProperty(ctx, val, ctx.getOpaque().sym_iterator) + if JS_IsException(itprop): + return none(T) + defer: JS_FreeValue(ctx, itprop) + let it = JS_Call(ctx, itprop, val, 0, nil) + if JS_IsException(it): + return none(T) + defer: JS_FreeValue(ctx, it) + let next_method = JS_GetProperty(ctx, it, ctx.getOpaque().next) + if JS_IsException(next_method): + return none(T) + defer: JS_FreeValue(ctx, next_method) + var x: T + result = some(x) + fromJSTupleBody(result.get) + +proc fromJSSeq[T](ctx: JSContext, val: JSValue): Option[seq[T]] = + let itprop = JS_GetProperty(ctx, val, ctx.getOpaque().sym_iterator) + if JS_IsException(itprop): + return none(seq[T]) + defer: JS_FreeValue(ctx, itprop) + let it = JS_Call(ctx, itprop, val, 0, nil) + if JS_IsException(it): + return none(seq[T]) + defer: JS_FreeValue(ctx, it) + let next_method = JS_GetProperty(ctx, it, ctx.getOpaque().next) + if JS_IsException(next_method): + return none(seq[T]) + defer: JS_FreeValue(ctx, next_method) + result = some(newSeq[T]()) + while true: + let next = JS_Call(ctx, next_method, it, 0, nil) + if JS_IsException(next): + return none(seq[T]) + defer: JS_FreeValue(ctx, next) + let doneVal = JS_GetProperty(ctx, next, ctx.getOpaque().done) + if JS_IsException(doneVal): + return none(seq[T]) + defer: JS_FreeValue(ctx, doneVal) + let done = fromJS[bool](ctx, doneVal) + if done.isnone: # exception + return none(seq[T]) + if done.get: + break + let valueVal = JS_GetProperty(ctx, next, ctx.getOpaque().value) + if JS_IsException(valueVal): + return none(seq[T]) + defer: JS_FreeValue(ctx, valueVal) + let genericRes = fromJS[typeof(result.get[0])](ctx, valueVal) + if genericRes.isnone: # exception + return none(seq[T]) + result.get.add(genericRes.get) + +proc fromJSTable[A, B](ctx: JSContext, val: JSValue): Option[Table[A, B]] = + var ptab: ptr JSPropertyEnum + #TODO free ptab + var plen: uint32 + let flags = cint(JS_GPN_STRING_MASK) + if JS_GetOwnPropertyNames(ctx, addr ptab, addr plen, val, flags) < -1: + # exception + return none(Table[A, B]) + defer: + for i in 0..<plen: + let prop = cast[ptr JSPropertyEnum](cast[int](ptab) + sizeof(ptab[]) * int(i)) + JS_FreeAtom(ctx, prop.atom) + js_free(ctx, ptab) + result = some(Table[A, B]()) + for i in 0..<plen: + let prop = cast[ptr JSPropertyEnum](cast[int](ptab) + sizeof(ptab[]) * int(i)) + let atom = prop.atom + let k = JS_AtomToValue(ctx, atom) + defer: JS_FreeValue(ctx, k) + let kn = fromJS[A](ctx, k) + if kn.isnone: # exception + return none(Table[A, B]) + let v = JS_GetProperty(ctx, val, atom) + defer: JS_FreeValue(ctx, v) + let vn = fromJS[B](ctx, v) + if vn.isnone: # exception + return none(Table[A, B]) + result.get[kn.get] = vn.get + +#TODO handle exceptions in all cases +proc fromJS[T](ctx: JSContext, val: JSValue): Option[T] = + when T is string: + return toString(ctx, val) + elif typeof(result.get) is Option: # unwrap + return fromJS[typeof(result.get)](ctx, val) + elif T is seq: + return fromJSSeq[typeof(result.get[0])](ctx, val) + elif T is tuple: + return fromJSTuple[T](ctx, val) + elif T is bool: + let ret = JS_ToBool(ctx, val) + if ret == -1: # exception + return none(T) + if ret == 0: + return some(false) + return some(true) + elif typeof(result.get) is Table: + return fromJSTable[typeof(result.get.keys), typeof(result.get.values)](ctx, val) + elif T is SomeInteger: + return fromJSInt[T](obj.ctx, obj.val) + elif T is SomeFloat: + let f64: float64 + if JS_ToFloat64(ctx, addr f64, val) < 0: + return none(T) + return some(cast[T](f64)) + else: + let op = cast[T](getOpaque(ctx, val, $T)) + if op == nil: + JS_ThrowTypeError(ctx, "Value is not an instance of %s", $T) + return none(T) + return some(op) + +func toJSString(ctx: JSContext, str: string): JSValue = + return JS_NewString(ctx, cstring(str)) + +func toJSInt(ctx: JSContext, n: SomeInteger): JSValue = + when n is int: + when sizeof(int) <= sizeof(int32): + return JS_NewInt32(ctx, n) + else: + return JS_NewInt64(ctx, n) + elif n is uint: + when sizeof(uint) <= sizeof(uint32): + return JS_NewUint32(ctx, n) + else: + return JS_NewUint64(ctx, n) + elif n is int32: + return JS_NewInt32(ctx, n) + elif n is int64: + return JS_NewInt64(ctx, n) + elif n is uint32: + return JS_NewUint32(ctx, n) + elif n is uint64: + return JS_NewUint64(ctx, n) + +func toJSNumber(ctx: JSContext, n: SomeNumber): JSValue = + when n is SomeInteger: + return toJSInt(n) + else: + return JS_NewFloat64(n) + +func toJSBool(ctx: JSContext, b: bool): JSValue = + return JS_NewBool(ctx, b) + +func toJSObject[T](ctx: JSContext, obj: T, class: string): JSValue = + let claz = ctx.findClass(class) + assert claz.issome + let op = JS_GetRuntime(ctx).getOpaque() + let p = cast[pointer](obj) + if p in op.plist: + # a JSValue already points to this object. + return JS_DupValue(ctx, JS_MKPTR(JS_TAG_OBJECT, op.plist[p])) + let jsObj = ctx.newJSObject(claz.get) + jsObj.setOpaque(obj) + return jsObj.val + +proc toJS*[T](ctx: JSContext, obj: T, class = ""): JSValue = + when T is string: + ctx.toJSString(obj) + elif T is SomeNumber: + ctx.toJSNumber(obj) + elif T is bool: + ctx.toJSBool(obj) + else: + ctx.toJSObject(obj, class) + +type + JS_Error = object of CatchableError + + JS_SyntaxError* = object of JS_Error + JS_TypeError* = object of JS_Error + JS_ReferenceError* = object of JS_Error + JS_RangeError* = object of JS_Error + JS_InternalError* = object of JS_Error + + JSFuncGenerator = object + original: NimNode + copied: NimNode + hasthis: bool + funcName: string + generics: Table[string, seq[NimNode]] + funcParams: seq[FuncParam] + thisType: string + returnType: Option[NimNode] + newName: string + newBranchList: seq[NimNode] + jsFunCallLists: seq[NimNode] + jsFunCallList: NimNode + jsFunCall: NimNode + jsCallAndRet: NimNode + minArgs: int + i: int # nim parameters accounted for + j: int # js parameters accounted for (not including fix ones, e.g. `this') + res: NimNode + +var RegisteredFunctions {.compileTime.}: Table[string, seq[(NimNode, NimNode)]] + +proc getGenerics(fun: NimNode): Table[string, seq[NimNode]] = + var node = fun.findChild(it.kind == nnkBracket) + if node.kind == nnkNilLit: + return # no bracket + node = node.findChild(it.kind == nnkGenericParams) + if node.kind == nnkNilLit: + return # no generics + node = node.findChild(it.kind == nnkIdentDefs) + var stack: seq[NimNode] + for i in countdown(node.len - 1, 0): stack.add(node[i]) + var gen_name: NimNode + var gen_types: seq[NimNode] + template add_gen = + if gen_name != nil: + assert gen_types.len != 0 + result[gen_name.strVal] = gen_types + gen_types.setLen(0) + + while stack.len > 0: + let node = stack.pop() + case node.kind + of nnkIdent: + add_gen + gen_name = node + of nnkSym: + assert gen_name != nil + gen_types.add(node) + of nnkInfix: + assert node[0].eqIdent(ident("|")) or node[0].eqIdent(ident("or")), "Only OR generics are supported." + for i in countdown(node.len - 1, 1): stack.add(node[i]) # except infix ident + of nnkBracketExpr: + gen_types.add(node) + else: + discard + add_gen + +proc getParams(fun: NimNode): seq[FuncParam] = + let formalParams = fun.findChild(it.kind == nnkFormalParams) + var funcParams: seq[FuncParam] + var returnType = none(NimNode) + if formalParams[0].kind != nnkEmpty: + returnType = some(formalParams[0]) + for i in 1..<fun.params.len: + let it = formalParams[i] + let name = $it[0] + let tt = it[1] + let t = if it[1].kind != nnkEmpty: + `tt` + else: + let x = it[2] + quote do: + typeof(`x`) + let val = if it[2].kind != nnkEmpty: + some(it[2]) + else: + none(NimNode) + var g = none(NimNode) + funcParams.add((name, t, val, g)) + funcParams + +proc getReturn(fun: NimNode): Option[NimNode] = + let formalParams = fun.findChild(it.kind == nnkFormalParams) + if formalParams[0].kind != nnkEmpty: + some(formalParams[0]) + else: + none(NimNode) + +template getJSParams(): untyped = + [ + (quote do: JSValue), + newIdentDefs(ident("ctx"), quote do: JSContext), + newIdentDefs(ident("this"), quote do: JSValue), + newIdentDefs(ident("argc"), quote do: int), + newIdentDefs(ident("argv"), quote do: ptr JSValue) + ] + +template getJSGetterParams(): untyped = + [ + (quote do: JSValue), + newIdentDefs(ident("ctx"), quote do: JSContext), + newIdentDefs(ident("this"), quote do: JSValue), + ] + +template getJSSetterParams(): untyped = + [ + (quote do: JSValue), + newIdentDefs(ident("ctx"), quote do: JSContext), + newIdentDefs(ident("this"), quote do: JSValue), + newIdentDefs(ident("val"), quote do: JSValue), + ] + +proc addParam2(gen: var JSFuncGenerator, s, t, val: NimNode, fallback: NimNode = nil) = + let stmt = quote do: + fromJS_or_return(`t`, ctx, `val`) + for i in 0..gen.jsFunCallLists.high: + if fallback == nil: + gen.jsFunCallLists[i].add(newLetStmt(s, stmt)) + else: + let j = gen.j + gen.jsFunCallLists[i].add(newLetStmt(s, quote do: + if `j` < argc: `stmt` else: `fallback`)) + +proc addValueParam(gen: var JSFuncGenerator, s, t: NimNode, fallback: NimNode = nil) = + let j = gen.j + gen.addParam2(s, t, quote do: getJSValue(ctx, argv, `j`), fallback) + +proc addFixParam(gen: var JSFuncGenerator, name: string) = + let s = ident("arg_" & $gen.i) + let t = gen.funcParams[gen.i][1] + let id = ident(name) + gen.addParam2(s, t, id) + if gen.jsFunCall != nil: + gen.jsFunCall.add(s) + inc gen.i + +proc addUnionParamBranch(gen: var JSFuncGenerator, query, newBranch: NimNode, fallback: NimNode = nil) = + let i = gen.i + let query = if fallback == nil: query else: + quote do: ( + if `i` >= argc: + false + else: + `query` + ) + let newBranch = newStmtList(newBranch) + for i in 0..gen.jsFunCallLists.high: + var ifstmt = newIfStmt((query, newBranch)) + let oldBranch = newStmtList() + ifstmt.add(newTree(nnkElse, oldBranch)) + gen.jsFunCallLists[i].add(ifstmt) + gen.jsFunCallLists[i] = oldBranch + gen.newBranchList.add(newBranch) + +proc addUnionParam(gen: var JSFuncGenerator, tt: NimNode, s: NimNode, fallback: NimNode = nil) = + # Union types. + #TODO lots of types missing + let j = gen.j + let flattened = gen.generics[tt.strVal] # flattened member types + var tableg = none(NimNode) + var seqg = none(NimNode) + var hasString = false + for g in flattened: + if g.len > 0 and g[0] == Table.getType(): + tableg = some(g) + elif g.typekind == ntySequence: + seqg = some(g) + elif g == string.getType(): + hasString = true + # 4. If V is null or undefined, then: + if tableg.issome: + let a = tableg.get[1] + let b = tableg.get[2] + gen.addUnionParamBranch(quote do: ( + let val = getJSValue(ctx, argv, `j`) + JS_IsNull(val) or JS_IsUndefined(val) + ), + quote do: + let `s` = Table[`a`, `b`](), #TODO is this correct? + fallback) + # 10. If Type(V) is Object, then: + if tableg.issome or seqg.issome: + # Sequence: + if seqg.issome: + let query = quote do: + ( + let o = getJSValue(ctx, argv, `j`) + JS_IsObject(o) and ( + let prop = JS_GetProperty(ctx, o, ctx.getOpaque().sym_iterator) + if JS_IsException(prop): + return JS_EXCEPTION + let ret = not JS_IsUndefined(prop) + JS_FreeValue(ctx, prop) + ret + ) + ) + let a = seqg.get[1] + gen.addUnionParamBranch(query, quote do: + let `s` = fromJS_or_return(seq[`a`], ctx, getJSValue(ctx, argv, `j`)), + fallback) + # Record: + if tableg.issome: + let a = tableg.get[1] + let b = tableg.get[2] + let query = quote do: + JS_IsObject(getJSValue(ctx, argv, `j`)) + gen.addUnionParamBranch(query, quote do: + let `s` = fromJS_or_return(Table[`a`, `b`], ctx, getJSValue(ctx, argv, `j`)), + fallback) + + # 14. If types includes a string type, then return the result of converting V + # to that type. + # TODO else typeerror + gen.addParam2(s, string.getType(), quote do: getJSValue(ctx, argv, `j`), fallback) + + for branch in gen.newBranchList: + gen.jsFunCallLists.add(branch) + gen.newBranchList.setLen(0) + +proc addRequiredParams(gen: var JSFuncGenerator) = + let minArgs = gen.funcParams.getMinArgs() + while gen.i < minArgs: + let s = ident("arg_" & $gen.i) + let tt = gen.funcParams[gen.i][1] + if tt.typeKind == ntyGenericParam: + gen.addUnionParam(tt, s) + else: + gen.addValueParam(s, tt) + if gen.jsFunCall != nil: + gen.jsFunCall.add(s) + inc gen.j + inc gen.i + +proc addOptionalParams(gen: var JSFuncGenerator) = + while gen.i < gen.funcParams.len: + let j = gen.j + let s = ident("arg_" & $gen.i) + let tt = gen.funcParams[gen.i][1] + if tt.typeKind == varargs.getType().typeKind: # pray it's not a generic... + let vt = tt[1].getType() + for i in 0..gen.jsFunCallLists.high: + gen.jsFunCallLists[i].add(newLetStmt(s, quote do: + ( + var valist: seq[`vt`] + for i in `j`..<argc: + let it = fromJS_or_return(`vt`, ctx, getJSValue(ctx, argv, i)) + valist.add(it) + valist + ) + )) + else: + let fallback = gen.funcParams[gen.i][2].get + if tt.typeKind == ntyGenericParam: + gen.addUnionParam(tt, s, fallback) + else: + gen.addValueParam(s, tt, fallback) + if gen.jsFunCall != nil: + gen.jsFunCall.add(s) + inc gen.j + inc gen.i + +proc finishFunCallList(gen: var JSFuncGenerator) = + for branch in gen.jsFunCallLists: + branch.add(gen.jsFunCall) + +var js_funcs {.compileTime.}: Table[string, JSFuncGenerator] + +proc registerFunction(gen: JSFuncGenerator) = + if gen.thisType notin RegisteredFunctions: + RegisteredFunctions[gen.thisType] = @[(newStrLitNode(gen.funcName), ident(gen.newName))] + else: + RegisteredFunctions[gen.thisType].add((newStrLitNode(gen.funcName), ident(gen.newName))) + js_funcs[gen.funcName] = gen + +var js_errors {.compileTime.}: Table[string, seq[string]] + +export JS_ThrowTypeError, JS_ThrowRangeError, JS_ThrowSyntaxError, + JS_ThrowInternalError, JS_ThrowReferenceError + +proc newJSProcBody(gen: var JSFuncGenerator, isva: bool): NimNode = + let tt = gen.thisType + let fn = gen.funcName + let ma = if gen.hasthis: gen.minArgs - 1 else: gen.minArgs + assert ma >= 0 + result = newStmtList() + if isva: + result.add(quote do: + if argc < `ma`: + return JS_ThrowTypeError(ctx, "At least %d arguments required, but only %d passed", `ma`, argc) + ) + if gen.hasthis: + result.add(quote do: + var this = JSObject(ctx: ctx, val: this) + if not (this.isUndefined() or ctx.isGlobal(`tt`)) and not this.isInstanceOf(`tt`): + # undefined -> global. + return JS_ThrowTypeError(ctx, "'%s' called on an object that is not an instance of %s", `fn`, `tt`) + ) + + if gen.funcName in js_errors: + var tryWrap = newNimNode(nnkTryStmt) + tryWrap.add(gen.jsCallAndRet) + for error in js_errors[gen.funcName]: + let ename = ident("JS_" & error) + var exceptBranch = newNimNode(nnkExceptBranch) + let eid = ident("e") + exceptBranch.add(newNimNode(nnkInfix).add(ident("as"), ename, eid)) + let throwName = ident("JS_Throw" & error) + exceptBranch.add(newCall(throwName, + ident("ctx"), + newLit("%s"), + newCall(ident("cstring"), + newDotExpr(eid, ident("msg"))))) + tryWrap.add(exceptBranch) + gen.jsCallAndRet = tryWrap + result.add(gen.jsCallAndRet) + +proc newJSProc(gen: var JSFuncGenerator, params: openArray[NimNode], isva = true): NimNode = + let jsBody = gen.newJSProcBody(isva) + let jsPragmas = newNimNode(nnkPragma).add(ident("cdecl")) + result = newProc(ident(gen.newName), params, jsBody, pragmas = jsPragmas) + gen.res = result + +# Note: this causes the entire nim function body to be inlined inside the JS +# interface function. +#TODO: implement actual inlining (so we can e.g. get rid of JS_Error, use format strings, etc.) +macro JS_THROW*(a: untyped, b: string) = + let es = ident("JS_" & a.strVal) + result = quote do: + block when_js: + raise newException(`es`, `b`) + +proc setupGenerator(fun: NimNode, hasthis = true, hasfuncall = true): JSFuncGenerator = + result.funcName = $fun[0] + if result.funcName == "$": + # stringifier + result.funcName = "toString" + result.generics = getGenerics(fun) + result.funcParams = getParams(fun) + result.returnType = getReturn(fun) + result.minArgs = result.funcParams.getMinArgs() + result.original = fun + result.hasthis = hasthis + result.jsFunCallList = newStmtList() + result.jsFunCallLists.add(result.jsFunCallList) + if hasfuncall: + result.jsFunCall = newCall(fun[0]) + +# this might be pretty slow... +#TODO ideally we wouldn't need separate functions at all. Not sure how that +# could be achieved, maybe using options? +proc rewriteExceptions(gen: var JSFuncGenerator, errors: var seq[string], node: NimNode) = + for i in countdown(node.len - 1, 0): + let c = node[i] + if c.kind == nnkCommand and c[0].eqIdent ident("JS_THROW"): + if gen.copied == nil: + gen.copied = copy(gen.original) + node[i] = newNimNode(nnkReturnStmt).add(newNilLit()) + if c[1].strVal notin errors: + errors.add(c[1].strVal) + elif c.len > 0: + gen.rewriteExceptions(errors, c) + +proc rewriteExceptions(gen: var JSFuncGenerator) = + let ostmts = gen.original.findChild(it.kind == nnkStmtList) + var errors: seq[string] + gen.rewriteExceptions(errors, ostmts) + assert gen.copied != nil + var name: string + if gen.copied[0].kind == nnkIdent: + name = gen.copied[0].strVal + elif gen.copied[0].kind == nnkPostfix: + name = gen.copied[0][1].strVal + else: + assert false, "No JS_THROW statement found in proc with jserr pragma." + name &= "_exceptions" + gen.copied[0] = ident(name) + js_errors[name] = errors + +macro jserr*(fun: untyped) = + var gen: JSFuncGenerator + gen.original = fun + gen.rewriteExceptions() + var pragma = gen.original.findChild(it.kind == nnkPragma) + for i in 0..<pragma.len: + if pragma[i] == ident("jsctor"): + pragma.del(i) + gen.copied.addPragma(quote do: inline) + + result = newStmtList(gen.original, gen.copied) + +macro jsctor*(fun: typed) = + var gen = setupGenerator(fun, hasthis = false) + if gen.funcName in js_funcs: + #TODO TODO TODO implement function overloading + error("Function overloading hasn't been implemented yet...") + result = newStmtList(fun) + else: + if gen.returnType.get.kind == nnkRefTy: + gen.thisType = gen.returnType.get[0].strVal + else: + gen.thisType = gen.returnType.get.strVal + gen.newName = "js_new_" & gen.thisType & '_' & gen.funcName + gen.addRequiredParams() + gen.addOptionalParams() + gen.finishFunCallList() + let jfcl = gen.jsFunCallList + let tt = gen.thisType + gen.jsCallAndRet = quote do: + return ctx.toJS((`jfcl`), `tt`) + discard gen.newJSProc(getJSParams()) + gen.registerFunction() + result = newStmtList(fun) + +macro jsget*(fun: typed) = + var gen = setupGenerator(fun) + gen.newName = "js_get_" & gen.funcParams[0][0] & '_' & gen.funcName + gen.thisType = $gen.funcParams[0][1] + if gen.minArgs != 1 or gen.funcParams.len != gen.minArgs: + error("jsget functions must accept one parameter") + if gen.returnType.isnone: + error("jsget functions must have a return type") + gen.addFixParam("this") + gen.finishFunCallList() + let jfcl = gen.jsFunCallList + let tt = gen.thisType + gen.jsCallAndRet = quote do: + return ctx.toJS(`jfcl`, `tt`) + let jsProc = gen.newJSProc(getJSGetterParams(), false) + gen.registerFunction() + result = newStmtList(fun, jsProc) + +macro jsset*(fun: typed) = + var gen = setupGenerator(fun) + gen.newName = "js_set_" & gen.funcParams[0][0] & '_' & gen.funcName + gen.thisType = $gen.funcParams[0][1] + if gen.minArgs != 2 or gen.funcParams.len != gen.minArgs: + error("jsset functions must accept two parameters") + if gen.returnType.issome: + error("jsset functions must not have a return type") + gen.addFixParam("this") + gen.addFixParam("val") + gen.finishFunCallList() + let jfcl = gen.jsFunCallList + # Ideally we could simulate JS setters using nim setters, but nim setters + # won't accept types that don't match their reflected field's type. + gen.jsCallAndRet = quote do: + `jfcl` + return JS_DupValue(ctx, val) + let jsProc = gen.newJSProc(getJSSetterParams(), false) + gen.registerFunction() + result = newStmtList(fun, jsProc) + +macro jsfunc*(fun: typed) = + var gen = setupGenerator(fun) + gen.newName = "js_" + if gen.funcParams.len > 0: + gen.newName &= gen.funcParams[0][0] & "_" + gen.newName &= gen.funcName + assert gen.minArgs > 0 #TODO support zero-param (=global, no parent object) + gen.thisType = $gen.funcParams[0][1] + gen.addFixParam("this") + gen.addRequiredParams() + gen.addOptionalParams() + gen.finishFunCallList() + let jfcl = gen.jsFunCallList + let tt = gen.thisType + gen.jsCallAndRet = if gen.returnType.issome: + quote do: + return ctx.toJS(`jfcl`, `tt`) + else: + quote do: + `jfcl` + return JS_UNDEFINED + let jsProc = gen.newJSProc(getJSParams()) + gen.registerFunction() + result = newStmtList(fun, jsProc) + +#WARNING footgun ahead: for some reason, these must be declared *after* their +# macro counterparts, or they override the macros. +template jsget*() {.pragma.} +template jsset*() {.pragma.} + +proc findPragmas(otab: var Table[string, seq[NimNode]], t: NimNode) = + let typ = t.getTypeInst()[1] # The type, as declared. + var impl = typ.getTypeImpl() # ref t + assert impl.kind == nnkRefTy, "Only ref nodes are supported..." + impl = impl[0].getImpl() + # stolen from std's macros.customPragmaNode + var identDefsStack = newSeq[NimNode](impl[2].len) + for i in 0..<identDefsStack.len: identDefsStack[i] = impl[2][i] + while identDefsStack.len > 0: + var identDefs = identDefsStack.pop() + + case identDefs.kind + of nnkRecList: + for child in identDefs.children: + identDefsStack.add(child) + of nnkRecCase: + # Add condition definition + identDefsStack.add(identDefs[0]) + # Add branches + for i in 1 ..< identDefs.len: + identDefsStack.add(identDefs[i].last) + else: + for i in 0 .. identDefs.len - 3: + let varNode = identDefs[i] + if varNode.kind == nnkPragmaExpr: + var varName = varNode[0] + if varName.kind == nnkPostfix: + # This is a public field. We are skipping the postfix * + varName = varName[1] + for pragma in varNode[1]: + let pragmaName = ($pragma).tolower() + if pragmaName in otab: #TODO this isn't style sensitive... + otab[pragmaName].add(varName) + +proc nim_finalize_for_js[T](obj: T) = + for rt in runtimes: + let rtOpaque = rt.getOpaque() + if tables.hasKey(rtOpaque.plist, cast[pointer](obj)): + let p = rtOpaque.plist[cast[pointer](obj)] + let val = JS_MKPTR(JS_TAG_OBJECT, p) + let header = cast[ptr JSRefCountHeader](p) + if header.ref_count > 1: + # References to this value still exist in JS, so we + # * copy the opaque's value + # * increase the new value's refcount by 1 + # * set the new value as the new opaque + # * add the new value to the pointer table + # Now it's on JS to decrement the new object's refcount. + # (Yeah, kind of an ugly hack. But it starts to look better when + # the alternative is writing a cycle collector...) + let newop = new(T) + newop[] = obj[] + GC_ref(newop) + let np = cast[pointer](newop) + JS_SetOpaque(val, np) + rtOpaque.plist[np] = p + else: + # This was the last reference to the JS value. + # Clear val's opaque so our refcount isn't decreased again. + JS_SetOpaque(val, nil) + tables.del(rtOpaque.plist, cast[pointer](obj)) + # Decrement jsvalue's refcount. This is needed in both cases to + # trigger the JS finalizer and free the JS value. + JS_FreeValueRT(rt, val) + +proc js_illegal_ctor*(ctx: JSContext, this: JSValue, argc: int, argv: ptr JSValue): JSValue {.cdecl.} = + return JS_ThrowTypeError(ctx, "Illegal constructor") + +template fromJS_or_return*(t, ctx, val: untyped): untyped = + ( + let x = fromJS[t](ctx, val) + if x.isnone: + return JS_EXCEPTION + x.get + ) + +macro registerType*(ctx: typed, t: typed, parent: JSClassID = 0, asglobal = false, addto = none(JSObject)): JSClassID = + let s = t.strVal + var sctr = ident("js_illegal_ctor") + var sfin = ident("js_" & s & "ClassFin") + var ctorFun: NimNode + var ctorImpl: NimNode + var setters, getters: Table[string, NimNode] + var pragmas: Table[string, seq[NimNode]] + pragmas["jsget"] = @[] + pragmas["jsset"] = @[] + pragmas.findPragmas(t) + result = newStmtList() + #TODO use magic functions instead + for node in pragmas["jsget"]: + let id = ident("js_get_" & s & "_" & $node) + let fn = $node + result.add(quote do: + proc `id`(ctx: JSContext, this: JSValue): JSValue = + if not (JS_IsUndefined(this) or ctx.isGlobal(`s`)) and not JSObject(ctx: ctx, val: this).isInstanceOf(`s`): + # undefined -> global. + return JS_ThrowTypeError(ctx, "'%s' called on an object that is not an instance of %s", `fn`, `s`) + let arg_0 = fromJS_or_return(`t`, ctx, this) + return toJS(ctx, arg_0.`node`, $typeof(arg_0.`node`)) + ) + RegisteredFunctions[s].add((node, id)) + for node in pragmas["jsset"]: + let id = ident("js_set_" & s & "_" & $node) + let fn = $node + result.add(quote do: + proc `id`(ctx: JSContext, this: JSValue, val: JSValue): JSValue = + var this = JSObject(ctx: ctx, val: this) + if not (this.isUndefined() or ctx.isGlobal(`s`)) and not this.isInstanceOf(`s`): + # undefined -> global. + return JS_ThrowTypeError(ctx, "'%s' called on an object that is not an instance of %s", `fn`, `s`) + let arg_0 = fromJS[`t`](this) + let arg_1 = JSObject(ctx: ctx, val: val) + arg_0.`node` = fromJS[typeof(arg_0.`node`)](arg_1) + return JS_DupValue(ctx, arg_1.val) + ) + RegisteredFunctions[s].add((node, id)) + let tabList = newNimNode(nnkBracket) + for fun in RegisteredFunctions[s]: + let f0 = fun[0] + let f1 = fun[1] + if f1.strVal.startsWith("js_new"): + ctorImpl = js_funcs[$f0].res + if ctorFun != nil: + error("Class " & $s & " has 2+ constructors.") + ctorFun = f1 + elif f1.strVal.startsWith("js_get"): + getters[$f0] = f1 + elif f1.strVal.startsWith("js_set"): + setters[$f0] = f1 + else: + tabList.add(quote do: + JS_CFUNC_DEF(`f0`, 0, cast[JSCFunction](`f1`))) + for k, v in getters: + if k in setters: + let s = setters[k] + tabList.add(newCall((quote do: JS_CGETSET_DEF), + newLit(k), + newNimNode(nnkCast).add(quote do: JSGetterFunction, + v), + newNimNode(nnkCast).add(quote do: JSSetterFunction, + s))) + else: + tabList.add(newCall((quote do: JS_CGETSET_DEF), + newLit(k), + newNimNode(nnkCast).add(quote do: JSGetterFunction, + v), + newNilLit())) + for k, v in setters: + if k notin getters: + tabList.add(newCall((quote do: JS_CGETSET_DEF), + newLit(k), + newNilLit(), + newNimNode(nnkCast).add(quote do: JSSetterFunction, + v))) + + if ctorFun != nil: + sctr = ctorFun + result.add(ctorImpl) + + result.add(quote do: + proc `sfin`(rt: JSRuntime, val: JSValue) {.cdecl.} = + let opaque = JS_GetOpaque(val, val.getClassID()) + if opaque != nil: + # This means the nim value is no longer referenced by anything but this + # JSValue. Meaning we can just unref and remove it from the pointer + # table. + GC_unref(cast[`t`](opaque)) + let rtOpaque = rt.getOpaque() + rtOpaque.plist.del(opaque) + ) + + result.add(quote do: + block: + # See the definition of `new': + # > **Note**: + # > The `finalizer` refers to the type `T`, not to the object! + # > This means that for each object of type `T` the finalizer will be + # > called! + # We exploit this by setting a finalizer here, which can then unregister + # any associated JS object from all relevant runtimes. + var x: `t` + new(x, nim_finalize_for_js) + const classDef = JSClassDef(class_name: `s`, finalizer: `sfin`) + `ctx`.newJSClass(JSClassDefConst(unsafeAddr classDef), `sctr`, `tabList`, `parent`, `asglobal`, `addto`) + ) + +proc getMemoryUsage*(rt: JSRuntime): string = + var m: JSMemoryUsage + JS_ComputeMemoryUsage(rt, addr m) + result = fmt""" +memory allocated: {m.malloc_count} {m.malloc_size} ({float(m.malloc_size)/float(m.malloc_count):.1f}/block) +memory used: {m.memory_used_count} {m.memory_used_size} ({float(m.malloc_size-m.memory_used_size)/float(m.memory_used_count):.1f} average slack) +atoms: {m.atom_count} {m.atom_size} ({float(m.atom_size)/float(m.atom_count):.1f}/atom) +strings: {m.str_count} {m.str_size} ({float(m.str_size)/float(m.str_count):.1f}/string) +objects: {m.obj_count} {m.obj_size} ({float(m.obj_size)/float(m.obj_count):.1f}/object) +properties: {m.prop_count} {m.prop_size} ({float(m.prop_size)/float(m.obj_count):.1f}/object) +shapes: {m.shape_count} {m.shape_size} ({float(m.shape_size)/float(m.shape_count):.1f}/shape) +js functions: {m.js_func_count} {m.js_func_size} ({float(m.js_func_size)/float(m.js_func_count):.1f}/function) +native functions: {m.c_func_count} +arrays: {m.array_count} +fast arrays: {m.fast_array_count} +fast array elements: {m.fast_array_elements} {m.fast_array_elements*sizeof(JSValue)} ({float(m.fast_array_elements)/float(m.fast_array_count):.1f}) +binary objects: {m.binary_object_count} {m.binary_object_size}""" proc eval*(ctx: JSContext, s: string, file: string, eval_flags: int): JSObject = result.ctx = ctx - result.val = JS_Eval(ctx, cstring(s), s.len, cstring(file), eval_flags) + result.val = JS_Eval(ctx, cstring(s), cint(s.len), cstring(file), cint(eval_flags)) diff --git a/src/main.nim b/src/main.nim index 926d1c37..51824798 100644 --- a/src/main.nim +++ b/src/main.nim @@ -4,8 +4,8 @@ import terminal when defined(profile): import nimprof -import client import config/config +import display/client import utils/twtstr readConfig() @@ -81,7 +81,7 @@ if pages.len == 0: if stdin.isatty: help(1) -gconfig.nmap = constructActionTable(gconfig.nmap) +gconfig.nmap = constructActionTable2(gconfig.nmap) gconfig.lemap = constructActionTable(gconfig.lemap) width_table = makewidthtable(gconfig.ambiguous_double) diff --git a/src/types/url.nim b/src/types/url.nim index f86bdc01..4e258b22 100644 --- a/src/types/url.nim +++ b/src/types/url.nim @@ -5,6 +5,7 @@ import options import unicode import math +import js/javascript import utils/twtstr type @@ -34,17 +35,23 @@ type ipv6: Option[array[8, uint16]] opaquehost: string - Url* = object + URLSearchParams* = ref object + list*: seq[tuple[name, value: string]] + url: Option[URL] + + URL* = ref URLObj + URLObj* = object encoding: int #TODO scheme*: string - username*: string - password*: string + username* {.jsget.}: string + password* {.jsget.}: string port: Option[uint16] host: Option[Host] path*: UrlPath query*: Option[string] fragment: Option[string] blob: Option[BlobUrlEntry] + searchParams* {.jsget.}: URLSearchParams const EmptyPath = UrlPath(opaque: true, s: "") const EmptyHost = Host(domain: "").some @@ -308,7 +315,7 @@ func parseHost(input: string, isnotspecial = false): Option[Host] = func isempty(host: Host): bool = return host.domain == "" and host.ipv4.isnone and host.ipv6.isnone and host.opaquehost == "" -proc shorten_path(url: var Url) {.inline.} = +proc shorten_path(url: Url) {.inline.} = assert not url.path.opaque if url.scheme == "file" and url.path.ss.len == 1 and url.path.ss[0][0] in Letters and url.path.ss[0][1] == ':': @@ -324,9 +331,11 @@ proc append(path: var UrlPath, s: string) = template includes_credentials(url: Url): bool = url.username != "" or url.password != "" template is_windows_drive_letter(s: string): bool = s.len == 2 and s[0] in Letters and (s[1] == ':' or s[1] == '|') +template canHaveUsernamePasswordPort(url: URL): bool = + url.host.issome and url.host.get.serialize() != "" and url.scheme != "file" #TODO encoding -proc basicParseUrl*(input: string, base = none(Url), url: var Url = Url(), override: bool = false): Option[Url] = +proc basicParseUrl*(input: string, base = none(Url), url: Url = Url(), stateOverride = none(UrlState)): Option[Url] = #TODO If input contains any leading or trailing C0 control or space, validation error. #TODO If input contains any ASCII tab or newline, validation error. let input = input.strip(true, false, {chr(0x00)..chr(0x1F), ' '}).strip(true, false, {'\t', '\n'}) @@ -335,7 +344,10 @@ proc basicParseUrl*(input: string, base = none(Url), url: var Url = Url(), overr var insidebrackets = false var passwordtokenseen = false var pointer = 0 + let override = stateOverride.issome var state = SCHEME_START_STATE + if override: + state = stateOverride.get template c(i = 0): char = input[pointer + i] template has(i = 0): bool = (pointer + i < input.len) @@ -712,7 +724,7 @@ func anchor*(url: Url): string = return url.fragment.get return "" -proc parseUrl*(input: string, base = none(Url), url: var Url, override: bool = false): Option[Url] = +proc parseUrl*(input: string, base = none(Url), url: var Url, override = none(UrlState)): Option[Url] = var url = basicParseUrl(input, base, url, override) if url.isnone: return url @@ -721,7 +733,7 @@ proc parseUrl*(input: string, base = none(Url), url: var Url, override: bool = f url.get.blob = BlobUrlEntry().some return url -proc parseUrl*(input: string, base = none(Url), override: bool = false): Option[Url] = +proc parseUrl*(input: string, base = none(Url), override = none(UrlState)): Option[Url] = var url = Url().some url = basicParseUrl(input, base, url.get, override) if url.isnone: @@ -843,6 +855,182 @@ func serialize*(url: Option[Url], excludefragment = false): string = func equals*(a, b: Url, excludefragment = false): bool = return a.serialize(excludefragment) == b.serialize(excludefragment) -func `$`*(url: Url): string {.inline.} = url.serialize() +func `$`*(url: Url): string {.jsfunc, inline.} = url.serialize() func `$`*(path: UrlPath): string {.inline.} = path.serialize() + +#https://url.spec.whatwg.org/#concept-urlencoded-serializer +proc parseApplicationXWWWFormUrlEncoded(input: string): seq[(string, string)] = + for s in input.split('&'): + if s == "": + continue + var name = "" + var value = "" + for i in 0..<s.len: + if s[i] == '=': + name = s.substr(0, i - 1) + value = s.substr(i + 1) + break + if name == "": + name = s + for i in 0..<name.len: + if name[i] == '+': + name[i] = ' ' + for i in 0..<value.len: + if value[i] == '+': + value[i] = ' ' + result.add((percentDecode(name), percentDecode(value))) + +#https://url.spec.whatwg.org/#concept-urlencoded-serializer +proc serializeApplicationXWWWFormUrlEncoded*(kvs: seq[(string, string)]): string = + for it in kvs: + let (name, value) = it + if result != "": + result &= '&' + result.percentEncode(name, ApplicationXWWWFormUrlEncodedSet, true) + result &= '=' + result.percentEncode(value, ApplicationXWWWFormUrlEncodedSet, true) + +proc initURLSearchParams(params: URLSearchParams, init: string) = + params.list = parseApplicationXWWWFormUrlEncoded(init) + +proc newURLSearchParams*[T: seq[(string, string)]|Table[string, string]|string](init: T = ""): URLSearchParams {.jsctor.} = + new(result) + when T is seq[(string, string)]: + result.list = init + elif T is Table[string, string]: + for k, v in init: + result.list.add((k, v)) + elif T is string: + let init = if init.len > 0 and init[0] == '?': + init.substr(1) + else: + init + result.initURLSearchParams(init) + +proc `$`*(params: URLSearchParams): string {.jsfunc.} = + return serializeApplicationXWWWFormUrlEncoded(params.list) + +#TODO add Option wrapper +proc newURL*(s: string, base: Option[string] = none(string)): URL {.jserr, jsctor.} = + if base.issome: + let baseUrl = parseUrl(base.get) + if baseUrl.isnone: + JS_THROW TypeError, base.get & " is not a valid URL" + let url = parseUrl(s, baseUrl) + if url.isnone: + JS_THROW TypeError, s & " is not a valid URL" + return url.get + let url = parseUrl(s) + if url.isnone: + JS_THROW TypeError, s & " is not a valid URL" + url.get.searchParams = newURLSearchParams() + url.get.searchParams.initURLSearchParams(url.get.query.get("")) + return url.get + +proc origin*(url: URL): string {.jsget.} = + case url.scheme + of "blob": + if url.blob.issome: + #TODO + discard + let pathURL = parseURL($url.path) + if pathURL.isnone: + return "null" + return pathURL.get.origin + of "ftp", "http", "https", "ws", "wss": + # return the tuple origin. + #TODO split this out + result = url.scheme + result &= "://" + result &= url.host.get.serialize() + if url.port.issome: + result &= ":" + result &= $url.port.get + of "file": + #??? + return "null" + else: + return "null" + +proc protocol*(url: URL): string {.jsget.} = + return url.scheme & ':' + +proc protocol*(url: URL, s: string) {.jsset.} = + discard basicParseUrl(s & ':', url = url, stateOverride = some(SCHEME_START_STATE)) + +proc username*(url: URL, username: string) {.jsset.} = + if not url.canHaveUsernamePasswordPort: + return + url.username = username.percentEncode(UserInfoPercentEncodeSet) + +proc password*(url: URL, password: string) {.jsset.} = + if not url.canHaveUsernamePasswordPort: + return + url.password = password.percentEncode(UserInfoPercentEncodeSet) + +proc host*(url: URL): string {.jsget.} = + if url.host.isnone: + return "" + if url.port.isnone: + return url.host.get.serialize() + return url.host.get.serialize() & ':' & $url.port.get + +proc host*(url: URL, s: string) {.jsset.} = + if url.path.opaque: + return + discard basicParseUrl(s, url = url, stateOverride = some(HOST_STATE)) + +proc port*(url: URL): string {.jsget.} = + if url.port.issome: + return $url.port.get + +proc port*(url: URL, s: string) {.jsset.} = + if not url.canHaveUsernamePasswordPort: + return + if s == "": + url.port = none(uint16) + else: + discard basicParseUrl(s, url = url, stateOverride = some(PORT_STATE)) + +proc pathname*(url: URL): string {.jsget.} = + return url.path.serialize() + +proc pathname*(url: URL, s: string) {.jsset.} = + if url.path.opaque: + return + url.path.ss.setLen(0) + discard basicParseUrl(s, url = url, stateOverride = some(PATH_START_STATE)) + +proc search*(url: URL): string {.jsget.} = + if url.query.get("") == "": + return "" + return "?" & url.query.get + +proc search*(url: URL, s: string) {.jsset.} = + if s == "": + url.query = none(string) + url.searchParams.list.setLen(0) + return + let s = if s[0] == '?': s.substr(1) else: s + url.query = some("") + discard basicParseUrl(s, url = url, stateOverride = some(QUERY_STATE)) + url.searchParams.list = parseApplicationXWWWFormUrlEncoded(s) + +proc hash*(url: URL): string {.jsget.} = + if url.fragment.get("") == "": + return "" + return '#' & url.fragment.get + +proc hash*(url: URL, s: string) {.jsset.} = + if s == "": + url.fragment = none(string) + return + let s = if s[0] == '#': s.substr(1) else: s + discard basicParseUrl(s, url = url, stateOverride = some(FRAGMENT_STATE)) + +proc addUrlModule*(ctx: JSContext) = + let global = ctx.getGlobalObject() + discard ctx.registerType(URL, addto = some(global)) + discard ctx.registerType(URLSearchParams, addto = some(global)) + free(global) |