about summary refs log tree commit diff stats
path: root/src/html/htmlparser.nim
blob: f43bcf406ca41a7610e195d75fb74da9126a3a51 (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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import streams
import unicode
import strutils
import tables
import json

import ../types/enums
import ../types/tagtypes

import ../utils/twtstr
import ../utils/radixtree

import ../io/twtio

import dom
import entity

type
  HTMLParseState = object
    closed: bool
    parents: seq[Node]
    parsedNode: Node
    a: string
    b: string
    attrs: seq[string]
    in_comment: bool
    in_script: bool
    in_style: bool
    in_noscript: bool
    in_body: bool
    parentNode: Node
    textNode: Text

#func newHtmlElement(tagType: TagType, parentNode: Node): HtmlElement =
#  case tagType
#  of TAG_INPUT: result = new(HtmlInputElement)
#  of TAG_A: result = new(HtmlAnchorElement)
#  of TAG_SELECT: result = new(HtmlSelectElement)
#  of TAG_OPTION: result = new(HtmlOptionElement)
#  else: result = new(HtmlElement)
#
#  result.nodeType = ELEMENT_NODE
#  result.tagType = tagType
#  result.parentNode = parentNode
#  if parentNode.isElemNode():
#    result.parentElement = HtmlElement(parentNode)
#
#  if tagType in DisplayInlineTags:
#    result.display = DISPLAY_INLINE
#  elif tagType in DisplayBlockTags:
#    result.display = DISPLAY_BLOCK
#  elif tagType in DisplayInlineBlockTags:
#    result.display = DISPLAY_INLINE_BLOCK
#  elif tagType == TAG_LI:
#    result.display = DISPLAY_LIST_ITEM
#  else:
#    result.display = DISPLAY_NONE
#
#  case tagType
#  of TAG_CENTER:
#    result.centered = true
#  of TAG_B:
#    result.bold = true
#  of TAG_I:
#    result.italic = true
#  of TAG_U:
#    result.underscore = true
#  of TAG_HEAD:
#    result.hidden = true
#  of TAG_STYLE:
#    result.hidden = true
#  of TAG_SCRIPT:
#    result.hidden = true
#  of TAG_OPTION:
#    result.hidden = true #TODO
#  of TAG_PRE, TAG_TD, TAG_TH:
#    result.margin = 1
#  of TAG_UL, TAG_OL:
#    result.indent = 2
#    result.margin = 1
#  of TAG_H1, TAG_H2, TAG_H3, TAG_H4, TAG_H5, TAG_H6:
#    result.bold = true
#    result.margin = 1
#  of TAG_A:
#    result.islink = true
#  of TAG_INPUT:
#    HtmlInputElement(result).size = 20
#  else: discard
#
#  if parentNode.isElemNode():
#    let parent = HtmlElement(parentNode)
#    result.centered = result.centered or parent.centered
#    result.bold = result.bold or parent.bold
#    result.italic = result.italic or parent.italic
#    result.underscore = result.underscore or parent.underscore
#    result.hidden = result.hidden or parent.hidden
#    result.islink = result.islink or parent.islink

func inputSize*(str: string): int =
  if str.len == 0:
    return 20
  for c in str:
    if not c.isDigit:
      return 20
  return str.parseInt()

#w3m's getescapecmd and parse_tag, transpiled to nim.
#(C) Copyright 1994-2002 by Akinori Ito
#(C) Copyright 2002-2011 by Akinori Ito, Hironori Sakamoto, Fumitoshi Ukai
#
#Use, modification and redistribution of this software is hereby granted,
#provided that this entire copyright notice is included on any copies of
#this software and applications and derivations thereof.
#
#This software is provided on an "as is" basis, without warranty of any
#kind, either expressed or implied, as to any matter including, but not
#limited to warranty of fitness of purpose, or merchantability, or
#results obtained from use of this software.
proc getescapecmd(buf: string, at: var int): string =
  var i = at

  if buf[i] == '#': #num
    inc i
    var num: int
    if buf[i].tolower() == 'x': #hex
      inc i
      if not isdigit(buf[i]):
        at = i
        return ""

      num = hexValue(buf[i])
      inc i
      while i < buf.len and hexValue(buf[i]) != -1:
        num *= 0x10
        num += hexValue(buf[i])
        inc i
    else: #dec
      if not isDigit(buf[i]):
        at = i
        return ""

      num = decValue(buf[i])
      inc i
      while i < buf.len and isDigit(buf[i]):
        num *= 10
        num += decValue(buf[i])
        inc i

    if buf[i] == ';':
      inc i
    at = i
    return $(Rune(num))
  elif not isAlphaAscii(buf[i]):
    return ""

  #TODO this could be way more efficient (and radixnode needs better interface)
  when defined(small):
    var n = entityMap
    var s = ""
    while true:
      s &= buf[i]
      if not entityMap.hasPrefix(s, n):
        break
      let pn = n
      n = n{s}
      if n != pn:
        s = ""
      inc i

    if n.leaf:
      at = i
      return n.value
  else:
    var n = 0
    var s = ""
    while true:
      s &= buf[i]
      if not entityMap.hasPrefix(s, n):
        break
      let pn = n
      n = entityMap{s, n}
      if n != pn:
        s = ""
      inc i

    if entityMap.nodes[n].leaf:
      at = i
      return entityMap.nodes[n].value

  return ""

type
  DOMParsedTag = object
    tagid: TagType
    attrs: Table[string, string]
    open: bool

proc parse_tag(buf: string, at: var int): DOMParsedTag =
  var tag = DOMParsedTag()
  tag.open = true

  #Parse tag name
  var tagname = ""
  inc at
  if buf[at] == '/':
    inc at
    tag.open = false
    at = skipBlanks(buf, at)

  while at < buf.len and not buf[at].isWhitespace() and not (tag.open and buf[at] == '/') and buf[at] != '>':
    tagname &= buf[at].tolower()
    at += buf.runeLenAt(at)

  tag.tagid = tagType(tagname)
  at = skipBlanks(buf, at)

  while at < buf.len and buf[at] != '>':
    var value = ""
    var attrname = ""
    while at < buf.len and buf[at] != '=' and not buf[at].isWhitespace() and buf[at] != '>':
      attrname &= buf[at].tolower()
      at += buf.runeLenAt(at)

    at = skipBlanks(buf, at)
    if buf[at] == '=':
      inc at
      at = skipBlanks(buf, at)
      if at < buf.len and (buf[at] == '"' or buf[at] == '\''):
        let startc = buf[at]
        inc at
        while at < buf.len and buf[at] != startc:
          var r: Rune
          fastRuneAt(buf, at, r)
          if r == Rune('&'):
            value &= getescapecmd(buf, at)
          else:
            value &= $r
        if at < buf.len:
          inc at
      elif at < buf.len:
        while at < buf.len and not buf[at].isWhitespace() and buf[at] != '>':
          value &= buf[at]
          at += buf.runeLenAt(at)

    if attrname.len > 0:
      tag.attrs[attrname] = value

  while at < buf.len and buf[at] != '>':
    at += buf.runeLenAt(at)

  if at < buf.len and buf[at] == '>':
    inc at
  return tag

proc insertNode(parent: Node, node: Node) =
  parent.childNodes.add(node)

  if parent.childNodes.len > 1:
    let prevSibling = parent.childNodes[^1]
    prevSibling.nextSibling = node
    node.previousSibling = prevSibling

  node.parentNode = parent
  if parent.nodeType == ELEMENT_NODE:
    node.parentElement = (Element)parent

  if parent.ownerDocument != nil:
    node.ownerDocument = parent.ownerDocument
  elif parent.nodeType == DOCUMENT_NODE:
    node.ownerDocument = (Document)parent

  if node.nodeType == ELEMENT_NODE:
    parent.children.add((Element)node)

    let element = ((Element)node)
    if element.ownerDocument != nil:
      node.ownerDocument.all_elements.add((Element)node)
      element.ownerDocument.type_elements[element.tagType].add(element)
      if element.id != "":
        if not (element.id in element.ownerDocument.id_elements):
          element.ownerDocument.id_elements[element.id] = newSeq[Element]()
        element.ownerDocument.id_elements[element.id].add(element)

      for c in element.classList:
        if not (c in element.ownerDocument.class_elements):
          element.ownerDocument.class_elements[c] = newSeq[Element]()
        element.ownerDocument.class_elements[c].add(element)

proc processDocumentBody(state: var HTMLParseState) =
  if not state.in_body:
    state.in_body = true
    if state.parentNode.ownerDocument != nil:
      state.parentNode = state.parentNode.ownerDocument.body

proc processDocumentStartNode(state: var HTMLParseState, newNode: Node) =
  if state.parentNode.nodeType == ELEMENT_NODE and ((Element)state.parentNode).tagType == TAG_HTML:
    if state.in_body:
      state.parentNode = state.parentNode.ownerDocument.body
    else:
      state.parentNode = state.parentNode.ownerDocument.head

  insertNode(state.parentNode, newNode)
  state.parentNode = newNode

proc processDocumentEndNode(state: var HTMLParseState) =
  if state.parentNode == nil or state.parentNode.parentNode == nil:
    return
  state.parentNode = state.parentNode.parentNode

proc processDocumentText(state: var HTMLParseState) =
  if state.textNode != nil and state.textNode.data.len > 0:
    processDocumentBody(state)
  if state.textNode == nil:
    state.textNode = newText()

    processDocumentStartNode(state, state.textNode)
    processDocumentEndNode(state)

proc processDocumentStartElement(state: var HTMLParseState, element: Element, tag: DOMParsedTag) =
  var add = true

  for k, v in tag.attrs:
    element.attributes[k] = element.newAttr(k, v)
  
  element.id = element.getAttrValue("id")
  if element.attributes.hasKey("class"):
    for w in unicode.split(element.attributes["class"].value, Rune(' ')):
      element.classList.add(w)

  case element.tagType
  of TAG_SCRIPT:
    state.in_script = true
  of TAG_NOSCRIPT:
    state.in_noscript = true
  of TAG_STYLE:
    state.in_style = true
  of TAG_SELECT:
    HTMLSelectElement(element).name = element.getAttrValue("name")
    HTMLSelectElement(element).value = element.getAttrValue("value")
  of TAG_INPUT:
    HTMLInputElement(element).value = element.getAttrValue("value")
    HTMLInputElement(element).itype = element.getAttrValue("type").inputType()
    HTMLInputElement(element).size = element.getAttrValue("size").inputSize()
  of TAG_A:
    HTMLAnchorElement(element).href = element.getAttrValue("href")
  of TAG_OPTION:
    HTMLOptionElement(element).value = element.getAttrValue("href")
  of TAG_HTML:
    add = false
  of TAG_HEAD:
    add = false
  of TAG_BODY:
    add = false
    processDocumentBody(state)
  else: discard

  if state.parentNode.nodeType == ELEMENT_NODE:
    case element.tagType
    of TAG_LI, TAG_P:
      if Element(state.parentNode).tagType == element.tagType:
        processDocumentEndNode(state)
    of TAG_H1:
      HTMLHeadingElement(element).rank = 1
    of TAG_H2:
      HTMLHeadingElement(element).rank = 2
    of TAG_H3:
      HTMLHeadingElement(element).rank = 3
    of TAG_H4:
      HTMLHeadingElement(element).rank = 4
    of TAG_H5:
      HTMLHeadingElement(element).rank = 5
    of TAG_H6:
      HTMLHeadingElement(element).rank = 6
    else: discard

  if add:
    processDocumentStartNode(state, element)

  if element.tagType in VoidTagTypes:
    processDocumentEndNode(state)

proc processDocumentEndElement(state: var HTMLParseState, tag: DOMParsedTag) =
  if tag.tagid in VoidTagTypes:
    return
  if tag.tagid == TAG_HEAD:
    state.in_body = true
    return
  if tag.tagid == TAG_BODY:
    return
  if state.parentNode.nodeType == ELEMENT_NODE:
    if Element(state.parentNode).tagType in {TAG_LI, TAG_P}:
      processDocumentEndNode(state)
  
  processDocumentEndNode(state)

proc processDocumentTag(state: var HTMLParseState, tag: DOMParsedTag) =
  if state.in_script:
    if tag.tagid == TAG_SCRIPT:
      state.in_script = false
    else:
      return

  if state.in_style:
    if tag.tagid == TAG_STYLE:
      state.in_style = false
    else:
      return

  if state.in_noscript:
    if tag.tagid == TAG_NOSCRIPT:
      state.in_noscript = false
    else:
      return

  if tag.open:
    processDocumentStartElement(state, newHtmlElement(tag.tagid), tag)
  else:
    processDocumentEndElement(state, tag)

proc processDocumentPart(state: var HTMLParseState, buf: string) =
  var at = 0
  var max = 0
  var was_script = false

  max = buf.len

  while at < max:
    case buf[at]
    of '&':
      inc at
      let p = getescapecmd(buf, at)
      if state.in_comment:
        CharacterData(state.parentNode).data &= p
      else:
        processDocumentText(state)
        state.textNode.data &= p
    of '<':
      if state.in_comment:
        CharacterData(state.parentNode).data &= buf[at]
        inc at
      else:
        var p = at
        inc p
        if p < max and buf[p] == '!':
          inc p
          if p < max and buf[p] == '-':
            inc p
            if p < max and buf[p] == '-':
              inc p
              at = p
              state.in_comment = true
              processDocumentStartNode(state, newComment())
              if state.textNode != nil:
                state.textNode.rawtext = state.textNode.getRawText()
                state.textNode = nil
          else:
            #TODO for doctype
            while p < max and buf[p] != '>':
              inc p
            at = p
            continue

        if not state.in_comment:
          if state.textNode != nil:
            state.textNode.rawtext = state.textNode.getRawText()
            state.textNode = nil
          p = at
          var tag = parse_tag(buf, at)
          was_script = state.in_script

          processDocumentTag(state, tag)
#         if (was_script) {
#             if (state->in_script) {
#                 ptr = p;
#                 processDocumentText(&state->parentNode, &state->textNode);
#                 Strcat_char(((CharacterData *)state->textNode)->data, *ptr++);
#             } else if (buffer->javascript_enabled) {
#                 loadJSToBuffer(buffer, childTextContentNode(state->parentNode->lastChild)->ptr, "<inline>", state->document);
#             }
#         }
    elif buf[at] == '-' and state.in_comment:
      var p = at
      inc p
      if p < max and buf[p] == '-':
        inc p
        if p < max and buf[p] == '>':
          inc p
          at = p
          state.in_comment = false
          processDocumentEndNode(state)

      if state.in_comment:
        CharacterData(state.parentNode).data &= buf[at]
        inc at
    else:
      var r: Rune
      fastRuneAt(buf, at, r)
      if state.in_comment:
        CharacterData(state.parentNode).data &= $r
      else:
        processDocumentText(state)
        state.textNode.data &= $r

proc parseHtml*(inputStream: Stream): Document =
  let document = newDocument()
  let html = newHtmlElement(TAG_HTML)
  insertNode(document, html)
  insertNode(html, document.head)
  insertNode(html, document.body)
  #eprint document.body.firstElementChild != nil

  var state = HTMLParseState()
  state.parentNode = html

  var till_when = false

  var buf = ""
  var lineBuf: string
  while not inputStream.atEnd():
    lineBuf = inputStream.readLine()
    buf &= lineBuf

    var at = 0
    while at < lineBuf.len:
      case lineBuf[at]
      of '<':
        till_when = true
      of '>':
        till_when = false
      else: discard
      at += lineBuf.runeLenAt(at)

    if till_when:
      continue

    processDocumentPart(state, buf)
    buf = ""

  inputStream.close()
  return document