aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2022-12-19 01:04:52 +0100
committerbptato <nincsnevem662@gmail.com>2022-12-19 01:04:52 +0100
commita04485f298d75ccbd8fc0b6fdd7be9ca63817cb0 (patch)
treef254ff77f3d8a497b19a1afe71efa481c7bdb3e6 /src
parentb1ad3a6950c76fc38593f46eb39d65a7dc1bfcec (diff)
downloadchawan-a04485f298d75ccbd8fc0b6fdd7be9ca63817cb0.tar.gz
More work on DOM (incl. bugfixes)
Diffstat (limited to 'src')
-rw-r--r--src/bindings/quickjs.nim1
-rw-r--r--src/html/dom.nim272
-rw-r--r--src/js/javascript.nim180
-rw-r--r--src/utils/twtstr.nim14
4 files changed, 251 insertions, 216 deletions
diff --git a/src/bindings/quickjs.nim b/src/bindings/quickjs.nim
index 59914e43..34f24cec 100644
--- a/src/bindings/quickjs.nim
+++ b/src/bindings/quickjs.nim
@@ -342,6 +342,7 @@ proc JS_NewCFunction2*(ctx: JSContext, cfunc: JSCFunction, name: cstring, length
proc JS_NewCFunction*(ctx: JSContext, cfunc: JSCFunction, name: cstring, length: cint): JSValue
proc JS_NewString*(ctx: JSContext, str: cstring): JSValue
+proc JS_NewStringLen*(ctx: JSContext, str: cstring, len1: csize_t): JSValue
proc JS_SetProperty*(ctx: JSContext, this_obj: JSValue, prop: JSAtom, val: JSValue): cint
proc JS_SetPropertyUint32*(ctx: JSContext, this_obj: JSValue, idx: uint32, val: JSValue): cint
diff --git a/src/html/dom.nim b/src/html/dom.nim
index c80c7201..4dfe5c3a 100644
--- a/src/html/dom.nim
+++ b/src/html/dom.nim
@@ -31,7 +31,7 @@ type
NO_QUIRKS, QUIRKS, LIMITED_QUIRKS
Namespace* = enum
- NO_NAMESPACE,
+ NO_NAMESPACE = "",
HTML = "http://www.w3.org/1999/xhtml",
MATHML = "http://www.w3.org/1998/Math/MathML",
SVG = "http://www.w3.org/2000/svg",
@@ -86,11 +86,9 @@ type
Console* = ref object
err: Stream
- NamedNodeMap* = ref object
+ NamedNodeMap = ref object
element: Element
- attrlist: seq[string]
- attrs: Table[string, Attr]
- nsattrs: Table[Namespace, Table[string, Attr]]
+ attrlist: seq[Attr]
EnvironmentSettings* = object
scripting*: bool
@@ -98,7 +96,7 @@ type
EventTarget* = ref object of RootObj
Node* = ref object of EventTarget
- nodeType*: NodeType
+ nodeType* {.jsget.}: NodeType
childNodes* {.jsget.}: seq[Node]
nextSibling*: Node
previousSibling*: Node
@@ -108,7 +106,7 @@ type
document*: Document
Attr* = ref object of Node
- namespaceURI* {.jsget.}: string
+ namespace: Namespace
prefix* {.jsget.}: string
localName* {.jsget.}: string
value* {.jsget.}: string
@@ -160,10 +158,8 @@ type
id*: string
classList*: seq[string]
- # attrs and nsattrs both store qualified names.
- attrs*: Table[string, string] # namespace = null
- nsattrs: Table[Namespace, Table[string, string]]
- attrsmap: NamedNodeMap
+ attrs*: Table[string, string]
+ attributes* {.jsget.}: NamedNodeMap
hover*: bool
invalid*: bool
@@ -261,6 +257,11 @@ type
cols*: int
value* {.jsget.}: string
+const NamespaceMap = (func(): Table[string, Namespace] =
+ for ns in Namespace:
+ result[$ns] = ns
+)()
+
proc tostr(ftype: enum): string =
return ($ftype).split('_')[1..^1].join("-").tolower()
@@ -401,29 +402,29 @@ iterator options*(select: HTMLSelectElement): HTMLOptionElement {.inline.} =
if opt.tagType == TAG_OPTION:
yield HTMLOptionElement(child)
-func newAttr(parent: Element, qualifiedName, value: string): Attr =
- new(result)
- result.document = parent.document
- result.nodeType = ATTRIBUTE_NODE
- result.ownerElement = parent
- if parent.namespace == Namespace.HTML:
- result.localName = qualifiedName
- else:
- #TODO ???
- let s = qualifiedName.until(':')
- if s.len == qualifiedName.len:
- result.localName = qualifiedName
- else:
- result.prefix = s
- result.localName = qualifiedName.substr(s.len)
- result.value = value
+iterator items(attributes: NamedNodeMap): Attr {.inline.} =
+ for attr in attributes.attrlist:
+ yield attr
+
+func newAttr(parent: Element, localName, value: string, prefix = "", namespace = NO_NAMESPACE): Attr =
+ return Attr(
+ nodeType: ATTRIBUTE_NODE,
+ document: parent.document,
+ namespace: namespace,
+ ownerElement: parent,
+ localName: localName,
+ prefix: prefix,
+ value: value
+ )
func name(attr: Attr): string {.jsfget.} =
if attr.prefix == "":
return attr.localName
- return attr.prefix & attr.localName
+ return attr.prefix & ':' & attr.localName
+
+func namespaceURI(attr: Attr): string {.jsfget.} =
+ return $attr.namespace
-#TODO TODO TODO all of this is dumb, we should just have an array of attrs, that's all
func hasAttribute(element: Element, qualifiedName: string): bool {.jsfunc.} =
let qualifiedName = if element.namespace == Namespace.HTML and not element.document.isxml:
qualifiedName.toLowerAscii2()
@@ -431,15 +432,15 @@ func hasAttribute(element: Element, qualifiedName: string): bool {.jsfunc.} =
qualifiedName
if qualifiedName in element.attrs:
return true
- for ns, t in element.nsattrs:
- if qualifiedName in t:
- return true
func hasAttributeNS(element: Element, namespace, localName: string): bool {.jsfunc.} =
if namespace == "":
return localName in element.attrs
- for ns, t in element.nsattrs:
- if $ns == namespace and localName in t:
+ if namespace notin NamespaceMap:
+ return false
+ let ns = NamespaceMap[namespace]
+ for attr in element.attributes:
+ if attr.namespace == ns and attr.localName == localName:
return true
func getAttribute(element: Element, qualifiedName: string): Option[string] {.jsfunc.} =
@@ -449,101 +450,51 @@ func getAttribute(element: Element, qualifiedName: string): Option[string] {.jsf
qualifiedName
element.attrs.withValue(qualifiedName, val):
return some(val[])
- for ns, t in element.nsattrs.mpairs:
- t.withValue(qualifiedName, val):
- return some(val[])
func getAttributeNS(element: Element, namespace, localName: string): Option[string] {.jsfunc.} =
if namespace == "":
return element.getAttribute(localName)
if namespace == $Namespace.HTML:
return element.getAttribute(localName)
- try:
- #TODO TODO TODO parseEnum is style insensitive
- let ns = parseEnum[Namespace](namespace)
- element.nsattrs.withValue(ns, t):
- t[].withValue(localName, val):
- # Not a qualified name...
- return some(val[])
- for k, v in t[]:
- let s = k.until(':')
- if s.len != k.len and localName == s:
- return some(v)
- except ValueError:
- discard
+ if namespace notin NamespaceMap:
+ return
+ let ns = NamespaceMap[namespace]
+ for attr in element.attributes:
+ if attr.namespace == ns and attr.localName == localName:
+ return some(attr.value)
+
+func findAttr(map: NamedNodeMap, name: string): int =
+ for i in 0 ..< map.attrlist.len:
+ if map.attrlist[i].name == name:
+ return i
+ return -1
-#TODO this is simply wrong
func getNamedItem(map: NamedNodeMap, qualifiedName: string): Option[Attr] {.jsfunc.} =
- let v = map.element.getAttribute(qualifiedName)
- if v.isSome:
- if qualifiedName notin map.attrs:
- map.attrs[qualifiedName] = map.element.newAttr(qualifiedName, v.get)
- return some(map.attrs[qualifiedName])
+ if map.element.hasAttribute(qualifiedName):
+ let i = map.findAttr(qualifiedName)
+ if i != -1:
+ return some(map.attrlist[i])
func getNamedItemNS(map: NamedNodeMap, namespace, localName: string): Option[Attr] {.jsfunc.} =
- if namespace == "":
- return map.getNamedItem(localName)
- if namespace == $Namespace.HTML:
- return map.getNamedItem(localName)
- try:
- #TODO TODO TODO parseEnum is style insensitive
- let ns = parseEnum[Namespace](namespace)
- var qn: string
- if ns notin map.nsattrs:
- map.nsattrs[ns] = Table[string, Attr]()
- map.element.nsattrs.withValue(ns, t):
- t[].withValue(localName, val):
- # Not a qualified name...
- if localName notin map.nsattrs[ns]:
- map.nsattrs[ns][localName] = map.element.newAttr(localName, val[])
- qn = localName
- for k, v in t[]:
- let s = k.until(':')
- if localName == s:
- if localName notin map.nsattrs[ns]:
- map.nsattrs[ns][localName] = map.element.newAttr(localName, v)
- qn = k
- if qn != "":
- return some(map.nsattrs[ns][qn])
- except ValueError:
- discard
-
-func attributes(element: Element): NamedNodeMap {.jsfget.} =
- if element.attrsmap == nil:
- element.attrsmap = NamedNodeMap(element: element)
- return element.attrsmap
+ if map.element.hasAttributeNS(namespace, localName):
+ if namespace in NamespaceMap:
+ let ns = NamespaceMap[namespace]
+ for attr in map:
+ if attr.namespace == ns and attr.localName == localName:
+ return some(attr)
func length(map: NamedNodeMap): int {.jsfget.} =
return map.element.attrs.len
-proc setNamedItem*(map: NamedNodeMap, attr: Attr): Option[Attr] {.jserr, jsfunc.} =
- if attr.ownerElement != nil and attr.ownerElement != map.element:
- #TODO should be DOMException
- JS_ERR JS_TypeError, "InUseAttributeError"
- if attr.name in map.element.attrs:
- return some(attr)
- let oldAttr = getNamedItem(map, attr.name)
- map.element.attrs[attr.name] = attr.value
- return oldAttr
-
-proc setNamedItemNS*(map: NamedNodeMap, attr: Attr): Option[Attr] {.jsfunc.} =
- map.setNamedItem(attr)
-
-#TODO TODO TODO this is extremely inefficient...
func item(map: NamedNodeMap, i: int): Option[Attr] {.jsfunc.} =
- var found: HashSet[string]
- for j in countdown(map.attrlist.high, 0):
- let k = map.attrlist[j]
- if k in map.element.attrs:
- found.incl(k)
- else:
- map.attrlist.delete(j)
- if map.attrlist.len < map.element.attrs.len:
- for k in map.element.attrs.keys:
- if k notin found:
- map.attrlist.add(k)
if i < map.attrlist.len:
- return map.getNamedItem(map.attrlist[i])
+ return some(map.attrlist[i])
+
+func hasprop[T: int|string](map: NamedNodeMap, i: T): bool {.jshasprop.} =
+ when T is int:
+ return i < map.attrlist.len
+ else:
+ return map.getNamedItem(i).isSome
func getter[T: int|string](map: NamedNodeMap, i: T): Option[Attr] {.jsgetprop.} =
when T is int:
@@ -596,24 +547,20 @@ func qualifiedName*(element: Element): string =
else: element.localName
func html*(document: Document): HTMLElement =
- for element in document.children:
- if element.tagType == TAG_HTML:
- return HTMLElement(element)
- return nil
+ for element in document.elements(TAG_HTML):
+ return HTMLElement(element)
func head*(document: Document): HTMLElement =
- if document.html != nil:
- for element in document.html.children:
- if element.tagType == TAG_HEAD:
- return HTMLElement(element)
- return nil
+ let html = document.html
+ if html != nil:
+ for element in html.elements(TAG_HEAD):
+ return HTMLElement(element)
func body*(document: Document): HTMLElement =
- if document.html != nil:
- for element in document.html.children:
- if element.tagType == TAG_BODY:
- return HTMLElement(element)
- return nil
+ let html = document.html
+ if html != nil:
+ for element in html.elements(TAG_BODY):
+ return HTMLElement(element)
func select*(option: HTMLOptionElement): HTMLSelectElement =
for anc in option.ancestors:
@@ -682,27 +629,28 @@ func contains*(a, b: Node): bool =
if node == b: return true
return false
-func firstChild*(node: Node): Node =
+func firstChild*(node: Node): Node {.jsfget.} =
if node.childNodes.len == 0:
return nil
return node.childNodes[0]
-func lastChild*(node: Node): Node =
+func lastChild*(node: Node): Node {.jsfget.} =
if node.childNodes.len == 0:
return nil
return node.childNodes[^1]
-func firstElementChild*(node: Node): Element =
+func firstElementChild*(node: Node): Element {.jsfget.} =
for child in node.children:
return child
return nil
-func lastElementChild*(node: Node): Element =
+func lastElementChild*(node: Node): Element {.jsfget.} =
for child in node.children:
return child
return nil
-func previousElementSibling*(elem: Element): Element =
+func previousElementSibling*(elem: Element): Element {.jsfget.} =
+ if elem.parentNode == nil: return nil
var i = elem.parentNode.childNodes.find(elem)
dec i
while i >= 0:
@@ -711,7 +659,8 @@ func previousElementSibling*(elem: Element): Element =
dec i
return nil
-func nextElementSibling*(elem: Element): Element =
+func nextElementSibling*(elem: Element): Element {.jsfget.} =
+ if elem.parentNode == nil: return nil
var i = elem.parentNode.childNodes.find(elem)
inc i
while i < elem.parentNode.childNodes.len:
@@ -720,6 +669,9 @@ func nextElementSibling*(elem: Element): Element =
inc i
return nil
+func documentElement(document: Document): Element {.jsfget.} =
+ document.firstElementChild()
+
func attr*(element: Element, s: string): string {.inline.} =
return element.attrs.getOrDefault(s, "")
@@ -973,6 +925,7 @@ func newHTMLElement*(document: Document, tagType: TagType, namespace = Namespace
result.namespace = namespace
result.namespacePrefix = prefix
result.document = document
+ result.attributes = NamedNodeMap(element: result)
func newHTMLElement*(document: Document, localName: string, namespace = Namespace.HTML, prefix = none[string](), tagType = tagType(localName)): Element =
result = document.newHTMLElement(tagType, namespace, prefix)
@@ -999,17 +952,20 @@ func getElementById*(node: Node, id: string): Element {.jsfunc.} =
if child.id == id:
return child
-func getElementById2*(node: Node, id: string): pointer =
- if id.len == 0:
- return nil
- for child in node.elements:
- if child.id == id:
- return cast[pointer](child)
-
-func getElementsByTag*(document: Document, tag: TagType): seq[Element] =
- for element in document.elements(tag):
+func getElementsByTag*(node: Node, tag: TagType): seq[Element] =
+ for element in node.elements(tag):
result.add(element)
+func getElementsByTagName(node: Node, tagName: string): seq[Element] {.jsfunc.} =
+ let tagName = tagType(tagName)
+ if tagName != TAG_UNKNOWN:
+ return node.getElementsByTag(tagName)
+
+func getElementsByClassName(node: Node, class: string): seq[Element] {.jsfunc.} =
+ for element in node.elements:
+ if class in element.classList:
+ result.add(element)
+
func inHTMLNamespace*(element: Element): bool = element.namespace == Namespace.HTML
func inMathMLNamespace*(element: Element): bool = element.namespace == Namespace.MATHML
func inSVGNamespace*(element: Element): bool = element.namespace == Namespace.SVG
@@ -1123,6 +1079,36 @@ func preInsertionValidity*(parent, node, before: Node): bool =
else: discard
return true # no exception reached
+proc delAttr(element: Element, name: string) =
+ let i = element.attributes.findAttr(name)
+ if i != -1:
+ element.attributes.attrlist.delete(i)
+
+proc attr(element: Element, name, value: string) =
+ if name in element.attrs:
+ element.delAttr(name)
+ element.attrs[name] = value
+ element.attributes.attrlist.add(element.newAttr(name, value))
+
+proc setAttribute(element: Element, qualifiedName, value: string) {.jsfunc.} =
+ element.attr(qualifiedName, value)
+
+proc setNamedItem*(map: NamedNodeMap, attr: Attr): Option[Attr] {.jserr, jsfunc.} =
+ if attr.ownerElement != nil and attr.ownerElement != map.element:
+ #TODO should be DOMException
+ JS_ERR JS_TypeError, "InUseAttributeError"
+ if attr.name in map.element.attrs:
+ return some(attr)
+ let i = map.findAttr(attr.name)
+ if i != -1:
+ result = some(map.attrlist[i])
+ map.attrlist.delete(i)
+ map.element.attrs[attr.name] = attr.value
+ map.attrlist.add(attr)
+
+proc setNamedItemNS*(map: NamedNodeMap, attr: Attr): Option[Attr] {.jsfunc.} =
+ map.setNamedItem(attr)
+
proc remove*(node: Node) =
let parent = node.parentNode
assert parent != nil
@@ -1305,7 +1291,7 @@ proc reset*(form: HTMLFormElement) =
proc appendAttributes*(element: Element, attrs: Table[string, string]) =
for k, v in attrs:
- element.attrs[k] = v
+ element.attr(k, v)
template reflect_str(element: Element, name: static string, val: untyped) =
element.attrs.withValue(name, val):
element.val = val[]
diff --git a/src/js/javascript.nim b/src/js/javascript.nim
index 0831f366..49d0b311 100644
--- a/src/js/javascript.nim
+++ b/src/js/javascript.nim
@@ -719,6 +719,8 @@ proc toJS*[T](ctx: JSContext, obj: T): JSValue =
if JS_DefinePropertyValueInt64(ctx, a, int64(i), j, JS_PROP_C_W_E or JS_PROP_THROW) < 0:
return JS_EXCEPTION
return a
+ elif T is enum:
+ return toJS(ctx, int(obj))
else:
if obj == nil:
return JS_NULL
@@ -767,7 +769,8 @@ type
CONSTRUCTOR = "js_ctor"
GETTER = "js_get"
SETTER = "js_set"
- PROPERTY_GETTER = "js_prop_get"
+ PROPERTY_GET = "js_prop_get"
+ PROPERTY_HAS = "js_prop_has"
var BoundFunctions {.compileTime.}: Table[string, seq[BoundFunction]]
@@ -825,7 +828,7 @@ proc getParams(fun: NimNode): seq[FuncParam] =
typeof(`x`)
else:
eprint treeRepr it
- assert false
+ error("??")
let val = if it[^1].kind != nnkEmpty:
let x = it[^1]
some(newPar(x))
@@ -860,7 +863,7 @@ template getJSGetterParams(): untyped =
newIdentDefs(ident("this"), quote do: JSValue),
]
-template getJSNamedPropertyParams(): untyped =
+template getJSGetPropParams(): untyped =
[
(quote do: cint),
newIdentDefs(ident("ctx"), quote do: JSContext),
@@ -869,6 +872,15 @@ template getJSNamedPropertyParams(): untyped =
newIdentDefs(ident("prop"), quote do: JSAtom),
]
+template getJSHasPropParams(): untyped =
+ [
+ (quote do: cint),
+ newIdentDefs(ident("ctx"), quote do: JSContext),
+ newIdentDefs(ident("obj"), quote do: JSValue),
+ newIdentDefs(ident("atom"), quote do: JSAtom),
+ ]
+
+
template getJSSetterParams(): untyped =
[
(quote do: JSValue),
@@ -887,21 +899,23 @@ template fromJS_or_return*(t, ctx, val: untyped): untyped =
x.get
)
+template fromJS_or_die*(t, ctx, val, ev, dl: untyped): untyped =
+ let valval = when typeof(val) is JSAtom:
+ JS_AtomToValue(ctx, val)
+ else:
+ val
+ if JS_IsException(valval):
+ return ev
+ let x = fromJS[t](ctx, valval)
+ if x.isnone:
+ break dl
+ x.get
+
proc addParam2(gen: var JSFuncGenerator, s, t, val: NimNode, fallback: NimNode = nil) =
let ev = gen.errval
let dl = gen.dielabel
- var stmt = newStmtList()
- stmt.add(quote do:
- let valval = when typeof(`val`) is JSAtom:
- JS_AtomToValue(ctx, `val`)
- else:
- `val`
- if JS_IsException(valval):
- return `ev`
- let x = fromJS[`t`](ctx, valval)
- if x.isnone:
- break `dl`
- x.get)
+ let stmt = quote do:
+ fromJS_or_die(`t`, ctx, `val`, `ev`, `dl`)
for i in 0..gen.jsFunCallLists.high:
if fallback == nil:
gen.jsFunCallLists[i].add(newLetStmt(s, stmt))
@@ -917,12 +931,7 @@ proc addValueParam(gen: var JSFuncGenerator, s, t: NimNode, fallback: NimNode =
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`
- )
+ quote do: (`i` < argc and `query`)
let newBranch = newStmtList(newBranch)
for i in 0..gen.jsFunCallLists.high:
var ifstmt = newIfStmt((query, newBranch))
@@ -932,35 +941,39 @@ proc addUnionParamBranch(gen: var JSFuncGenerator, query, newBranch: NimNode, fa
gen.jsFunCallLists[i] = oldBranch
gen.newBranchList.add(newBranch)
+const JS_ATOM_TAG_INT = cuint(1u32 shl 31)
+
+proc JS_IsNumber(v: JSAtom): JS_BOOL =
+ return (cast[cuint](v) and JS_ATOM_TAG_INT) != 0
+
proc addUnionParam0(gen: var JSFuncGenerator, tt: NimNode, s: NimNode, val: NimNode, fallback: NimNode = nil) =
# Union types.
- #TODO lots of types missing
+ #TODO quite a few types are still missing.
let flattened = gen.generics[tt.strVal] # flattened member types
var tableg = none(NimNode)
var seqg = none(NimNode)
+ var numg = none(NimNode)
var hasString = false
var hasJSObject = false
+ var hasBoolean = false
+ let ev = gen.errval
+ let dl = gen.dielabel
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():
+ elif g == string.getTypeInst():
hasString = true
elif g == JSValue.getTypeInst():
hasJSObject = true
- # 4. If V is null or undefined, then:
- #TODO this is wrong. map dictionary to object instead
- #if tableg.issome:
- # let a = tableg.get[1]
- # let b = tableg.get[2]
- # gen.addUnionParamBranch(quote do: (
- # let val = `val`
- # JS_IsNull(val) or JS_IsUndefined(val)
- # ),
- # quote do:
- # let `s` = Table[`a`, `b`](),
- # fallback)
+ elif g == bool.getTypeInst():
+ hasBoolean = true
+ elif g == int.getTypeInst(): #TODO should be SomeNumber
+ numg = some(g)
+ else:
+ error("Type not supported yet")
+
# 10. If Type(V) is Object, then:
# Sequence:
if seqg.issome:
@@ -977,7 +990,7 @@ proc addUnionParam0(gen: var JSFuncGenerator, tt: NimNode, s: NimNode, val: NimN
)
let a = seqg.get[1]
gen.addUnionParamBranch(query, quote do:
- let `s` = fromJS_or_return(seq[`a`], ctx, `val`),
+ let `s` = fromJS_or_die(seq[`a`], ctx, `val`, `ev`, `dl`),
fallback)
# Record:
if tableg.issome:
@@ -986,21 +999,50 @@ proc addUnionParam0(gen: var JSFuncGenerator, tt: NimNode, s: NimNode, val: NimN
let query = quote do:
JS_IsObject(`val`)
gen.addUnionParamBranch(query, quote do:
- let `s` = fromJS_or_return(Table[`a`, `b`], ctx, `val`),
+ let `s` = fromJS_or_die(Table[`a`, `b`], ctx, `val`, `ev`, `dl`),
fallback)
# Object (JSObject variant):
- #TODO non-JS objects
+ #TODO non-JS objects (i.e. ref object)
if hasJSObject:
let query = quote do:
JS_IsObject(`val`)
gen.addUnionParamBranch(query, quote do:
- let `s` = fromJS_or_return(JSValue, ctx, `val`),
+ let `s` = fromJS_or_die(JSValue, ctx, `val`, `ev`, `dl`),
+ fallback)
+ # 11. If Type(V) is Boolean, then:
+ if hasBoolean:
+ let query = quote do:
+ JS_IsBool(`val`)
+ gen.addUnionParamBranch(query, quote do:
+ let `s` = fromJS_or_die(bool, ctx, `val`, `ev`, `dl`),
+ fallback)
+ # 12. If Type(V) is Number, then:
+ if numg.isSome:
+ let ng = numg.get
+ let query = quote do:
+ JS_IsNumber(`val`)
+ gen.addUnionParamBranch(query, quote do:
+ let `s` = fromJS_or_die(`ng`, ctx, `val`, `ev`, `dl`),
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: `val`, fallback)
+ if hasString:
+ gen.addParam2(s, string.getType(), quote do: `val`, fallback)
+ # 16. If types includes a numeric type, then return the result of converting
+ # V to that numeric type.
+ elif numg.isSome:
+ gen.addParam2(s, numg.get.getType(), quote do: `val`, fallback)
+ # 17. If types includes boolean, then return the result of converting V to
+ # boolean.
+ elif hasBoolean:
+ gen.addParam2(s, bool.getType(), quote do: `val`, fallback)
+ # 19. Throw a TypeError.
+ else:
+ gen.addParam2(s, string.getType(), quote do:
+ if true:
+ discard JS_ThrowTypeError(ctx, "No match for union type")
+ return `ev`
+ JS_NULL, fallback)
for branch in gen.newBranchList:
gen.jsFunCallLists.add(branch)
@@ -1099,15 +1141,12 @@ proc newJSProcBody(gen: var JSFuncGenerator, isva: bool): NimNode =
)
if gen.thisname.isSome:
let tn = ident(gen.thisname.get)
+ let ev = gen.errval
result.add(quote do:
if not (JS_IsUndefined(`tn`) or ctx.isGlobal(`tt`)) and not isInstanceOf(ctx, `tn`, `tt`):
# undefined -> global.
- let err = JS_ThrowTypeError(ctx, "'%s' called on an object that is not an instance of %s", `fn`, `tt`)
- when result is JSValue:
- return err
- else:
- discard err
- return -1
+ discard JS_ThrowTypeError(ctx, "'%s' called on an object that is not an instance of %s", `fn`, `tt`)
+ return `ev`
)
if gen.funcName in js_errors:
@@ -1153,7 +1192,7 @@ proc setupGenerator(fun: NimNode, t: BoundFunctionType, thisname = some("this"))
result.minArgs = result.funcParams.getMinArgs()
result.original = fun
result.thisname = thisname
- if t == PROPERTY_GETTER:
+ if t in {PROPERTY_GET, PROPERTY_HAS}:
result.errval = quote do: cint(-1)
else:
result.errval = quote do: JS_EXCEPTION
@@ -1236,8 +1275,27 @@ macro jsctor*(fun: typed) =
gen.registerFunction()
result = newStmtList(fun)
+macro jshasprop*(fun: typed) =
+ var gen = setupGenerator(fun, PROPERTY_HAS, thisname = some("obj"))
+ if gen.funcName in js_funcs:
+ #TODO TODO TODO ditto
+ error("Function overloading hasn't been implemented yet...")
+ else:
+ gen.addFixParam("obj")
+ gen.addFixParam("atom")
+ gen.finishFunCallList()
+ let jfcl = gen.jsFunCallList
+ let dl = gen.dielabel
+ gen.jsCallAndRet = quote do:
+ block `dl`:
+ let retv = `jfcl`
+ return cint(retv)
+ let jsProc = gen.newJSProc(getJSHasPropParams(), false)
+ gen.registerFunction()
+ result = newStmtList(fun, jsProc)
+
macro jsgetprop*(fun: typed) =
- var gen = setupGenerator(fun, PROPERTY_GETTER, thisname = some("obj"))
+ var gen = setupGenerator(fun, PROPERTY_GET, thisname = some("obj"))
if gen.funcName in js_funcs:
#TODO TODO TODO ditto
error("Function overloading hasn't been implemented yet...")
@@ -1257,19 +1315,17 @@ macro jsgetprop*(fun: typed) =
desc[].flags = 0
return cint(1)
return cint(0)
- let jsProc = gen.newJSProc(getJSNamedPropertyParams(), false)
+ let jsProc = gen.newJSProc(getJSGetPropParams(), false)
gen.registerFunction()
result = newStmtList(fun, jsProc)
macro jsfget*(fun: typed) =
var gen = setupGenerator(fun, GETTER)
- if gen.minArgs != 1 and gen.minArgs != 2 or gen.funcParams.len != gen.minArgs:
- error("jsfget functions must accept one or two parameters")
+ if gen.minArgs != 1 or gen.funcParams.len != gen.minArgs:
+ error("jsfget functions must one parameters")
if gen.returnType.isnone:
error("jsfget functions must have a return type")
gen.addFixParam("this")
- if gen.minArgs == 2:
- gen.addFixParam("key")
gen.finishFunCallList()
let jfcl = gen.jsFunCallList
let dl = gen.dielabel #TODO this is redundant, getters have no arguments
@@ -1411,7 +1467,8 @@ macro registerType*(ctx: typed, t: typed, parent: JSClassID = 0, asglobal = fals
var ctorFun: NimNode
var ctorImpl: NimNode
# generic property getter (e.g. attribute["id"])
- var propFun: NimNode
+ var propGetFun = newNilLit()
+ var propHasFun = newNilLit()
# property setters/getters declared on classes (with jsget, jsset)
var setters, getters: Table[string, NimNode]
let tabList = newNimNode(nnkBracket)
@@ -1463,8 +1520,10 @@ macro registerType*(ctx: typed, t: typed, parent: JSClassID = 0, asglobal = fals
getters[f0] = f1
of SETTER:
setters[f0] = f1
- of PROPERTY_GETTER:
- propFun = f1
+ of PROPERTY_GET:
+ propGetFun = f1
+ of PROPERTY_HAS:
+ propHasFun = f1
for k, v in getters:
if k in setters:
@@ -1495,12 +1554,13 @@ macro registerType*(ctx: typed, t: typed, parent: JSClassID = 0, asglobal = fals
let endstmts = newStmtList()
let cdname = "classDef" & name
let classDef = ident("classDef")
- if propFun != nil:
+ if propGetFun.kind != nnkNilLit or propHasFun.kind != nnkNilLit:
endstmts.add(quote do:
# YES! IT COMPILES! AHAHAHAHAHAHA
{.emit: ["""
static JSClassExoticMethods exotic = {
- .get_own_property = """, `propFun`, """
+ .get_own_property = """, `propGetFun`, """,
+ .has_property = """, `propHasFun`, """
};
static JSClassDef """, `cdname`, """ = {
""", "\"", `name`, "\"", """,
diff --git a/src/utils/twtstr.nim b/src/utils/twtstr.nim
index 91676d5a..b66c5d65 100644
--- a/src/utils/twtstr.nim
+++ b/src/utils/twtstr.nim
@@ -102,21 +102,9 @@ func toLowerAscii2*(str: string): string =
result = newString(str.len)
prepareMutation(result)
copyMem(addr result[0], unsafeAddr str[0], i)
- while i < str.len:
+ for i in i ..< str.len:
result[i] = str[i].tolower()
-proc toLowerAsciiIp*(str: var string) =
- var i = 0
- block noconv:
- while i < str.len:
- let c = str[i]
- if c in AsciiUpperAlpha:
- break noconv
- inc i
- return
- while i < str.len:
- str[i] = str[i].tolower()
-
func toHeaderCase*(str: string): string =
result = str
var flip = true