about summary refs log tree commit diff stats
path: root/src/html/catom.nim
blob: 3f5bd7166ba5d14975a12f3235f43df0440ff347 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import std/hashes
import std/macros
import std/sets
import std/strutils

import chame/tags
import monoucha/fromjs
import monoucha/javascript
import monoucha/tojs
import types/opt
import utils/twtstr

# create a static enum compatible with chame/tags

macro makeStaticAtom =
  # declare inside the macro to avoid confusion with StaticAtom0
  type
    StaticAtom0 = enum
      satAbort = "abort"
      satAcceptCharset = "accept-charset"
      satAction = "action"
      satAlign = "align"
      satAlt = "alt"
      satAlternate = "alternate"
      satAsync = "async"
      satAutofocus = "autofocus"
      satBgcolor = "bgcolor"
      satBlocking = "blocking"
      satCellspacing = "cellspacing"
      satCharset = "charset"
      satChecked = "checked"
      satClass = "class"
      satClassList = "classList"
      satClick = "click"
      satColor = "color"
      satCols = "cols"
      satColspan = "colspan"
      satContent = "content"
      satCrossorigin = "crossorigin"
      satDOMContentLoaded = "DOMContentLoaded"
      satDefer = "defer"
      satDirname = "dirname"
      satDisabled = "disabled"
      satEnctype = "enctype"
      satError = "error"
      satEvent = "event"
      satEvents = "events"
      satFor = "for"
      satForm = "form"
      satFormaction = "formaction"
      satFormenctype = "formenctype"
      satFormmethod = "formmethod"
      satHash = "hash"
      satHeight = "height"
      satHost = "host"
      satHostname = "hostname"
      satHref = "href"
      satId = "id"
      satIntegrity = "integrity"
      satIsmap = "ismap"
      satLanguage = "language"
      satLoad = "load"
      satLoadend = "loadend"
      satLoadstart = "loadstart"
      satMax = "max"
      satMedia = "media"
      satMethod = "method"
      satMin = "min"
      satMousewheel = "mousewheel"
      satMultiple = "multiple"
      satName = "name"
      satNamespaceHTML = "http://www.w3.org/1999/xhtml",
      satNamespaceMathML = "http://www.w3.org/1998/Math/MathML",
      satNamespaceSVG = "http://www.w3.org/2000/svg",
      satNamespaceXLink = "http://www.w3.org/1999/xlink",
      satNamespaceXML = "http://www.w3.org/XML/1998/namespace",
      satNamespaceXMLNS = "http://www.w3.org/2000/xmlns/",
      satNomodule = "nomodule"
      satNovalidate = "novalidate"
      satOnclick = "onclick"
      satOnload = "onload"
      satOrigin = "origin"
      satPassword = "password"
      satPathname = "pathname"
      satPort = "port"
      satProgress = "progress"
      satProtocol = "protocol"
      satReadystatechange = "readystatechange"
      satReferrerpolicy = "referrerpolicy"
      satRel = "rel"
      satRequired = "required"
      satRows = "rows"
      satRowspan = "rowspan"
      satSearch = "search"
      satSelected = "selected"
      satSize = "size"
      satSizes = "sizes"
      satSlot = "slot"
      satSrc = "src"
      satSrcset = "srcset"
      satStyle = "style"
      satStylesheet = "stylesheet"
      satSvgevents = "svgevents"
      satTarget = "target"
      satText = "text"
      satTimeout = "timeout"
      satTitle = "title"
      satToString = "toString"
      satTouchmove = "touchmove"
      satTouchstart = "touchstart"
      satType = "type"
      satUEvent = "Event"
      satUempty = ""
      satUsemap = "usemap"
      satUsername = "username"
      satValign = "valign"
      satValue = "value"
      satWheel = "wheel"
      satWidth = "width"
      satXlink = "xlink"
      satXml = "xml"
      satXmlns = "xmlns"
  let decl = quote do:
    type StaticAtom* {.inject.} = enum
      atUnknown = ""
  let decl0 = decl[0][2]
  var seen: HashSet[string]
  for t in TagType:
    if t == TAG_UNKNOWN:
      continue
    let tn = $t
    let name = "sat" & tn[0].toUpperAscii() & tn.substr(1).kebabToCamelCase()
    seen.incl(tn)
    decl0.add(newNimNode(nnkEnumFieldDef).add(ident(name), newStrLitNode(tn)))
  for i, f in StaticAtom0.getType():
    if i == 0:
      continue
    let tn = $StaticAtom0(i - 1)
    if tn in seen:
      continue
    decl0.add(newNimNode(nnkEnumFieldDef).add(ident(f.strVal),
      newStrLitNode(tn)))
  decl

makeStaticAtom

#TODO use a better hash map
const CAtomFactoryStrMapLength = 1024 # must be a power of 2
static:
  doAssert (CAtomFactoryStrMapLength and (CAtomFactoryStrMapLength - 1)) == 0

type
  CAtom* = distinct uint32

  CAtomFactoryInit = object
    obj: CAtomFactoryObj

  CAtomFactoryObj = object
    strMap: array[CAtomFactoryStrMapLength, seq[CAtom]]
    atomMap: seq[string]
    lowerMap: seq[CAtom]
    namespaceMap: array[Namespace, CAtom]
    prefixMap: array[NamespacePrefix, CAtom]

  #TODO could be a ptr probably
  CAtomFactory* = ref CAtomFactoryObj

# This maps to JS null.
const CAtomNull* = CAtom(0)

# Mandatory Atom functions
func `==`*(a, b: CAtom): bool {.borrow.}
func hash*(atom: CAtom): Hash {.borrow.}

when defined(debug):
  func `$`*(a: CAtom): string {.borrow.}

func toAtom(factory: var CAtomFactoryObj; s: string;
    isInit: static bool = false): CAtom =
  let h = s.hash()
  let i = h and (factory.strMap.len - 1)
  for atom in factory.strMap[i]:
    if factory.atomMap[int(atom)] == s:
      # Found
      return atom
  # Not found
  let atom = CAtom(factory.atomMap.len)
  factory.atomMap.add(s)
  when not isInit:
    let lower = if AsciiUpperAlpha notin s:
      atom
    else:
      factory.toAtom(s.toLowerAscii())
    factory.lowerMap.add(lower)
  factory.strMap[i].add(atom)
  return atom

const factoryInit = (func(): CAtomFactoryInit =
  var init = CAtomFactoryInit()
  # Null atom
  init.obj.atomMap.add("")
  init.obj.lowerMap.add(CAtom(0))
  # StaticAtom includes TagType too.
  for sa in StaticAtom(1) .. StaticAtom.high:
    discard init.obj.toAtom($sa, isInit = true)
  for sa in StaticAtom(1) .. StaticAtom.high:
    let atom = init.obj.toAtom(($sa).toLowerAscii(), isInit = true)
    init.obj.lowerMap.add(atom)
  # fill slots of newly added lower mappings
  while init.obj.lowerMap.len < init.obj.atomMap.len:
    init.obj.lowerMap.add(CAtom(init.obj.lowerMap.len))
  let olen = init.obj.atomMap.len
  for it in Namespace:
    if it == NO_NAMESPACE:
      init.obj.namespaceMap[it] = CAtomNull
    else:
      init.obj.namespaceMap[it] = init.obj.toAtom($it)
  for it in NamespacePrefix:
    if it == NO_PREFIX:
      init.obj.prefixMap[it] = CAtomNull
    else:
      init.obj.prefixMap[it] = init.obj.toAtom($it)
  assert init.obj.atomMap.len == olen
  return init
)()

proc newCAtomFactory*(): CAtomFactory =
  let factory = new(CAtomFactory)
  factory[] = factoryInit.obj
  return factory

func toLowerAscii*(factory: CAtomFactory; a: CAtom): CAtom =
  return factory.lowerMap[int32(a)]

func equalsIgnoreCase*(factory: CAtomFactory; a, b: CAtom): bool =
  return factory.lowerMap[int32(a)] == factory.lowerMap[int32(b)]

func containsIgnoreCase*(factory: CAtomFactory; aa: openArray[CAtom];
    a: CAtom): bool =
  let a = factory.toLowerAscii(a)
  for it in aa:
    if a == factory.toLowerAscii(it):
      return true
  return false

func toAtom*(factory: CAtomFactory; s: string): CAtom =
  return factory[].toAtom(s)

func toAtom*(factory: CAtomFactory; tagType: TagType): CAtom =
  assert tagType != TAG_UNKNOWN
  return CAtom(tagType)

func toAtom*(factory: CAtomFactory; attrType: StaticAtom): CAtom =
  assert attrType != atUnknown
  return CAtom(attrType)

func toAtomLower*(factory: CAtomFactory; s: string): CAtom =
  return factory.lowerMap[int32(factory.toAtom(s))]

func toStr*(factory: CAtomFactory; atom: CAtom): string =
  return factory.atomMap[int(atom)]

func toStr*(factory: CAtomFactory; sa: StaticAtom): string =
  return factory.toStr(factory.toAtom(sa))

func toTagType*(atom: CAtom): TagType =
  let i = int(atom)
  if i <= int(TagType.high):
    return TagType(i)
  return TAG_UNKNOWN

func toStaticAtom*(factory: CAtomFactory; atom: CAtom): StaticAtom =
  let i = int(atom)
  if i <= int(StaticAtom.high):
    return StaticAtom(i)
  return atUnknown

func toStaticAtom*(factory: CAtomFactory; s: string): StaticAtom =
  return factory.toStaticAtom(factory.toAtom(s))

func toNamespace*(factory: CAtomFactory; atom: CAtom): Namespace =
  case factory.toStaticAtom(atom)
  of satUempty: return NO_NAMESPACE
  of satNamespaceHTML: return Namespace.HTML
  of satNamespaceMathML: return Namespace.MATHML
  of satNamespaceSVG: return Namespace.SVG
  of satNamespaceXLink: return Namespace.XLINK
  of satNamespaceXML: return Namespace.XML
  of satNamespaceXMLNS: return Namespace.XMLNS
  else: return NAMESPACE_UNKNOWN

func toAtom*(factory: CAtomFactory; namespace: Namespace): CAtom =
  return factory.namespaceMap[namespace]

func toAtom*(factory: CAtomFactory; prefix: NamespacePrefix): CAtom =
  return factory.prefixMap[prefix]

# Forward declaration hack
var getFactoryImpl*: proc(ctx: JSContext): CAtomFactory {.nimcall, noSideEffect,
  raises: [].}

proc toAtom*(ctx: JSContext; atom: StaticAtom): CAtom =
  return ctx.getFactoryImpl().toAtom(atom)

proc toAtom*(ctx: JSContext; s: string): CAtom =
  return ctx.getFactoryImpl().toAtom(s)

proc toStaticAtom*(ctx: JSContext; atom: CAtom): StaticAtom =
  return ctx.getFactoryImpl().toStaticAtom(atom)

proc toStaticAtom*(ctx: JSContext; s: string): StaticAtom =
  return ctx.getFactoryImpl().toStaticAtom(s)

proc toStr*(ctx: JSContext; atom: CAtom): string =
  return ctx.getFactoryImpl().toStr(atom)

proc toStr*(ctx: JSContext; sa: StaticAtom): string =
  return ctx.getFactoryImpl().toStr(sa)

proc fromJS*(ctx: JSContext; val: JSValue; res: var CAtom): Opt[void] =
  var s: string
  ?ctx.fromJS(val, s)
  res = ctx.getFactoryImpl().toAtom(s)
  return ok()

proc fromJS*(ctx: JSContext; val: JSAtom; res: var CAtom): Opt[void] =
  var s: string
  ?ctx.fromJS(val, s)
  res = ctx.getFactoryImpl().toAtom(s)
  return ok()

proc fromJS*(ctx: JSContext; val: JSAtom; res: var StaticAtom): Opt[void] =
  var ca: CAtom
  ?ctx.fromJS(val, ca)
  res = ctx.getFactoryImpl().toStaticAtom(ca)
  return ok()

proc toJS*(ctx: JSContext; atom: CAtom): JSValue =
  if atom == CAtomNull:
    return JS_NULL
  return ctx.toJS(ctx.getFactoryImpl().toStr(atom))

proc toJS*(ctx: JSContext; atom: StaticAtom): JSValue =
  return ctx.toJS($atom)