Debian Codegraph @

texmf-dist/tex/luatex/luaxml/luaxml-mod-html.lua

raw
1 --- HTML parsing module for LuaXML
2 -- @module luaxml-mod-html
3 -- @author Michal Hoftich <[email protected]
4 -- Copyright Michal Hoftich, 2022
5 -- HTML parser inspired by https://browser.engineering/html.html
6 -- but then redone using https://html.spec.whatwg.org/multipage/parsing.html
7 --
8 -- There main purpose of this module is to create an useful DOM for later processing
9 -- using LuaXML functions. Either for cleanup, or for translation to output formats,
10 -- for example LaTeX.
11 --
12 -- It should be possible to serialize DOM back to the original HTML code.
13 --
14 -- We attempt to do some basic fixes, like to close paragraphs or list items that
15 -- aren't closed correctly in the original code. We don't fix tables or
16 -- formatting elements (see https://html.spec.whatwg.org/multipage/parsing.html#the-list-of-active-formatting-elements)
17 -- as these features don't seem necessary for the purpose of this module. We may change
18 -- this policy in the future, if it turns out that they are necessary.
19 --
20 --
21 local M = {}
22
23 -- use local copies of utf8 functions
24 local ucodepoint = utf8.codepoint
25 local utfchar = utf8.char
26 local function uchar(codepoint)
27 if codepoint and codepoint > -1 then
28 return utfchar(codepoint)
29 end
30 return ""
31 end
32
33 -- declare namespaces
34 local xmlns = {
35 HTML = "http://www.w3.org/1999/xhtml",
36 MathML = "http://www.w3.org/1998/Math/MathML",
37 SVG = "http://www.w3.org/2000/svg",
38 XLink = "http://www.w3.org/1999/xlink",
39 XML = "http://www.w3.org/XML/1998/namespace",
40 XMLNS = "http://www.w3.org/2000/xmlns/",
41 }
42
43 -- we must make search tree for named entities, as their support
44 -- is quite messy
45 local named_entities
46 if kpse then
47 named_entities = require "luaxml-namedentities"
48 else
49 named_entities = require "luaxml.namedentities"
50 end
51
52 local entity_tree = {children = {}}
53
54 local function update_tree(tree, char)
55 local children = tree.children or {}
56 local current = children[char] or {}
57 children[char] = current
58 tree.children = children
59 return current
60 end
61
62 -- loop over named entities and update tree
63 for entity, char in pairs(named_entities) do
64 local tree = entity_tree
65 for char in entity:gmatch(".") do
66 tree = update_tree(tree,char)
67 end
68 tree.entity = entity
69 tree.char = char
70 end
71
72 local function search_entity_tree(tbl)
73 -- get named entity for the list of characters
74 local tree = entity_tree
75 for _,char in ipairs(tbl) do
76 if tree.children then
77 tree = tree.children[char]
78 if not tree then return nil end
79 else
80 return nil
81 end
82 end
83 -- print("tree", tree.char)
84 return tree
85 end
86
87
88 -- declare basic node types
89
90 local Root = {
91 _type = "root",
92 xmlns = xmlns.HTML
93 }
94
95 function Root:init()
96 local o = {}
97 setmetatable(o, self)
98 self.__index = self
99 self.__tostring = function (x) return "_ROOT" end
100 o.children = {}
101 return o
102 end
103
104 function Root:add_child(node)
105 table.insert(self.children, node)
106 end
107
108 local Doctype = {
109 _type = "doctype"
110 }
111 function Doctype:init(name, parent)
112 local o = {}
113 setmetatable(o, self)
114 self.__index = self
115 self.__tostring = function (x)
116 if x.data then
117 return "<!DOCTYPE " .. x.name .. " " .. x.data .. ">"
118 else
119 return "<!DOCTYPE " .. x.name .. ">"
120 end
121 end
122 self.add_child = Root.add_child
123 o.parent = parent
124 o.name = name
125 o.children = {}
126 return o
127 end
128
129 function Doctype:add_data(data)
130 self.data = data
131 end
132
133
134 local Text = {
135 _type = "text"
136 }
137
138 function Text:init(text, parent)
139 local o = {}
140 setmetatable(o, self)
141 self.__index = self
142 o.text = text
143 self.__tostring = function (x) return "'" .. x.text .. "'" end
144 self.add_child = Root.add_child
145 o.parent = parent
146 o.children = {}
147 return o
148 end
149
150 local Comment = {
151 _type = "comment"
152 }
153
154 function Comment:init(text, parent)
155 local o = {}
156 setmetatable(o, self)
157 self.__index = self
158 o.text = text
159 self.__tostring = function (x) return "<!--" .. x.text .. "-->" end
160 self.add_child = Root.add_child
161 o.parent = parent
162 o.children = {}
163 return o
164 end
165
166
167
168 local Element = {
169 _type = "element"
170 }
171
172 function Element:init(tag, parent)
173 local o = {}
174 setmetatable(o, self)
175 self.__index = self
176 -- tag can be table with unicode characters
177 if type(tag) == "table" then
178 o.tag = table.concat(tag)
179 else
180 o.tag = tag
181 end
182 self.__tostring = function(x)
183 local attr = {}
184 for _, el in ipairs(x.attr) do
185 -- handle attributes
186 local value
187 if el.value:match('"') then
188 value = "'" .. el.value .. "'"
189 else
190 value = '"' .. el.value .. '"'
191 end
192 attr[#attr+1] = el.name .. "=" .. value
193 end
194 local closing = ">"
195 if x.self_closing then
196 closing = " />"
197 end
198 if #attr > 0 then
199 return "<" .. x.tag .. " " .. table.concat(attr, " ") .. closing
200 else
201 return "<" .. x.tag .. closing
202 end
203 end
204 self.add_child = Root.add_child
205 o.children = {}
206 o.attr = {}
207 o.parent = parent
208 -- default xmlns
209 o.xmlns = xmlns.HTML
210 return o
211 end
212
213 -- state machine functions
214
215 -- each function takes HtmlParser as an argument
216 local HtmlStates = {}
217
218 -- declare codepoints for more efficient processing
219 local less_than = ucodepoint("<")
220 local greater_than = ucodepoint(">")
221 local amperesand = ucodepoint("&")
222 local exclam = ucodepoint("!")
223 local question = ucodepoint("?")
224 local solidus = ucodepoint("/")
225 local equals = ucodepoint("=")
226 local quoting = ucodepoint('"')
227 local apostrophe = ucodepoint("'")
228 local semicolon = ucodepoint(";")
229 local hyphen = ucodepoint("-")
230 local dash = ucodepoint("-")
231 local numbersign = ucodepoint("#")
232 local smallx = ucodepoint("x")
233 local bigx = ucodepoint("X")
234 local right_square = ucodepoint("]")
235 local EOF = -1 -- special character, meaning end of stream
236 local null = 0
237
238 local function is_upper_alpha(codepoint)
239 if (64 < codepoint and codepoint < 91) then
240 return true
241 end
242 end
243 local function is_lower_alpha(codepoint)
244 if (96 < codepoint and codepoint < 123) then
245 return true
246 end
247 end
248
249 local function is_alpha(codepoint)
250 -- detect if codepoint is alphanumeric
251 if is_upper_alpha(codepoint) or
252 is_lower_alpha(codepoint) then
253 return true
254 end
255 return false
256 end
257
258
259 local function is_numeric(codepoint)
260 if 47 < codepoint and codepoint < 58 then
261 return true
262 end
263 end
264
265 local function is_upper_hex(codepoint)
266 if 64 < codepoint and codepoint < 71 then
267 return true
268 end
269 end
270
271 local function is_lower_hex(codepoint)
272 if 96 < codepoint and codepoint < 103 then
273 return true
274 end
275 end
276
277 local function is_hexadecimal(codepoint)
278 if is_numeric(codepoint) or
279 is_lower_hex(codepoint) or
280 is_upper_hex(codepoint)
281 then
282 return true
283 end
284 end
285
286
287 local function is_alphanumeric(codepoint)
288 return is_alpha(codepoint) or is_numeric(codepoint)
289 end
290
291 local function is_space(codepoint)
292 -- detect space characters
293 if codepoint==0x0009 or codepoint==0x000A or codepoint==0x000C or codepoint==0x0020 then
294 return true
295 end
296 return false
297 end
298
299 local function is_surrogate(codepoint)
300 return 0xD800 <= codepoint and codepoint <= 0xDFFF
301 end
302
303
304 character_entity_replace_table = {
305 [0x80] = 0x20AC,
306 [0x82] = 0x201A,
307 [0x83] = 0x0192,
308 [0x84] = 0x201E,
309 [0x85] = 0x2026,
310 [0x86] = 0x2020,
311 [0x87] = 0x2021,
312 [0x88] = 0x02C6,
313 [0x89] = 0x2030,
314 [0x8A] = 0x0160,
315 [0x8B] = 0x2039,
316 [0x8C] = 0x0152,
317 [0x8E] = 0x017D,
318 [0x91] = 0x2018,
319 [0x92] = 0x2019,
320 [0x93] = 0x201C,
321 [0x94] = 0x201D,
322 [0x95] = 0x2022,
323 [0x96] = 0x2013,
324 [0x97] = 0x2014,
325 [0x98] = 0x02DC,
326 [0x99] = 0x2122,
327 [0x9A] = 0x0161,
328 [0x9B] = 0x203A,
329 [0x9C] = 0x0153,
330 [0x9E] = 0x017E,
331 [0x9F] = 0x0178
332 }
333
334 local function fix_null(codepoint)
335 if codepoint == null then
336 return 0xFFFD
337 else
338 return codepoint
339 end
340 end
341
342 HtmlStates.data = function(parser)
343 -- this is the default state
344 local codepoint = parser.codepoint
345 -- print("codepoint", parser.codepoint)
346 if codepoint == less_than then
347 -- start of tag
348 return "tag_open"
349 elseif codepoint == amperesand then
350 -- we must save the current state
351 -- what we will return to after entity
352 parser.return_state = "data"
353 return "character_reference"
354 elseif codepoint == EOF then
355 parser:emit_eof()
356 else
357 parser:emit_character(uchar(codepoint))
358 end
359 return "data"
360 end
361
362 HtmlStates.tag_open = function(parser)
363 -- parse tag contents
364 local codepoint = parser.codepoint
365 if codepoint == exclam then
366 return "markup_declaration_open"
367 elseif codepoint == solidus then
368 return "end_tag_open"
369 elseif codepoint == question then
370 parser:start_token("comment",{data={}})
371 return "bogus_comment"
372 elseif is_alpha(codepoint) then
373 local data = {
374 name = {},
375 attr = {},
376 current_attr_name = {},
377 current_attr_value = {},
378 self_closing = false
379 }
380 parser:start_token("start_tag", data)
381 return parser:tokenize("tag_name")
382 elseif codepoint == EOF then
383 parser:emit_character(">")
384 parser:emit_eof()
385 else
386 -- invalid tag
387 -- emit "<" and reconsume current character as data
388 parser:emit_character("<")
389 return parser:tokenize("data")
390 end
391 end
392
393 HtmlStates.character_reference = function(parser)
394 -- parse HTML entities
395 -- initialize temp buffer
396 parser.temp_buffer = {"&"}
397 local codepoint = parser.codepoint
398 if is_alphanumeric(codepoint) then
399 return parser:tokenize("named_character_reference")
400 elseif codepoint == numbersign then
401 table.insert(parser.temp_buffer, uchar(codepoint))
402 return "numeric_character_reference"
403 else
404 parser:flush_temp_buffer()
405 return parser:tokenize(parser.return_state)
406 end
407
408 end
409
410 HtmlStates.named_character_reference = function(parser)
411 -- named entity parsing is pretty complicated
412 -- https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state
413 local codepoint = parser.codepoint
414 -- test if the current entity name is included in the named entity list
415 local search_table = {}
416 -- first char in temp buffer is &, which we don't want to lookup in the search tree
417 for i=2, #parser.temp_buffer do search_table[#search_table+1] = parser.temp_buffer[i] end
418 if codepoint == semicolon then
419 -- close named entity
420 local entity = search_entity_tree(search_table)
421 if entity and entity.char then
422 parser:add_entity(entity.char)
423 else
424 -- if the current name doesn't correspond to any named entity, flush everything into text
425 parser:flush_temp_buffer()
426 return parser:tokenize(parser.return_state)
427 end
428 return parser.return_state
429 else
430 local char = uchar(codepoint)
431 -- try if the current entity name is in the named entity search tree
432 table.insert(search_table, char)
433 local entity = search_entity_tree(search_table)
434 if entity then
435 -- keep parsing name entity while we match a name
436 table.insert(parser.temp_buffer, char)
437 return "named_character_reference"
438 else
439 -- here this will be more complicated
440 if #search_table > 1 then
441 local token = parser.current_token
442 if token.type == "start_tag" and (codepoint == equals or is_alphanumeric(codepoint)) then
443 -- in attribute value, flush characters and retokenize
444 parser:flush_temp_buffer()
445 return parser:tokenize(parser.return_state)
446 else
447 -- try to get entity for characters preceding the current character
448 table.remove(search_table)
449 local newentity = search_entity_tree(search_table)
450 if newentity and newentity.char then
451 parser:add_entity(newentity.char)
452 else
453 -- we need to find if parts of the current substring match a named entity
454 -- for example &notit; -> ¬it; but &notin; -> ∉
455 local rest = {}
456 -- loop over the table with characters, and try to find if it matches entity
457 for i = #search_table, 1,-1 do
458 local removed_char = table.remove(search_table)
459 --
460 table.insert(rest, 1, removed_char)
461 newentity = search_entity_tree(search_table)
462 if newentity and newentity.char then
463 parser:add_entity(newentity.char)
464 parser.temp_buffer = rest
465 break
466 end
467 end
468 -- replace temporary buffer witch characters that followed the matched entity
469 parser:flush_temp_buffer()
470 end
471 return parser:tokenize(parser.return_state)
472 end
473 else
474 -- search table contains only the current character
475 parser:flush_temp_buffer()
476 return parser:tokenize(parser.return_state)
477 end
478 end
479 end
480
481 end
482
483 HtmlStates.numeric_character_reference = function(parser)
484 -- this variable will hold the number
485 local codepoint = parser.codepoint
486 parser.character_reference_code = 0
487 if codepoint == smallx or codepoint == bigx then
488 -- hexadecimal entity
489 table.insert(parser.temp_buffer, uchar(codepoint))
490 return "hexadecimal_character_reference_start"
491 else
492 -- try decimal entity
493 return parser:tokenize("decimal_character_reference_start")
494 end
495
496 end
497
498 HtmlStates.hexadecimal_character_reference_start = function(parser)
499 local codepoint = parser.codepoint
500 if is_hexadecimal(codepoint) then
501 return parser:tokenize("hexadecimal_character_reference")
502 else
503 parser:flush_temp_buffer()
504 return parser:tokenize(parser.return_state)
505 end
506 end
507
508 HtmlStates.decimal_character_reference_start = function(parser)
509 local codepoint = parser.codepoint
510 if is_numeric(codepoint) then
511 return parser:tokenize("decimal_character_reference")
512 else
513 parser:flush_temp_buffer()
514 return parser:tokenize(parser.return_state)
515 end
516 end
517
518
519 HtmlStates.decimal_character_reference = function(parser)
520 local codepoint = parser.codepoint
521 -- helper functions for easier working with the character_reference_code
522 local function multiply(number)
523 parser.character_reference_code = parser.character_reference_code * number
524 end
525 local function add(number)
526 parser.character_reference_code = parser.character_reference_code + number
527 end
528 if is_numeric(codepoint) then
529 multiply(10)
530 add(codepoint - 0x30)
531 elseif codepoint == semicolon then
532 return "numeric_reference_end_state"
533 else
534 -- this adds current entity
535 parser:tokenize("numeric_reference_end_state")
536 -- now tokenize the current character
537 return parser:tokenize(parser.return_state)
538 end
539 return "decimal_character_reference"
540 end
541
542 HtmlStates.hexadecimal_character_reference = function(parser)
543 local codepoint = parser.codepoint
544 -- helper functions for easier working with the character_reference_code
545 local function multiply(number)
546 parser.character_reference_code = parser.character_reference_code * number
547 end
548 local function add(number)
549 parser.character_reference_code = parser.character_reference_code + number
550 end
551 if is_numeric(codepoint) then
552 multiply(16)
553 add(codepoint - 0x30)
554 elseif is_upper_hex(codepoint) then
555 multiply(16)
556 add(codepoint - 0x37)
557 elseif is_lower_hex(codepoint) then
558 multiply(16)
559 add(codepoint - 0x57)
560 elseif codepoint == semicolon then
561 return "numeric_reference_end_state"
562 else
563 -- this adds current entity
564 parser:tokenize("numeric_reference_end_state")
565 -- now tokenize the current character
566 return parser:tokenize(parser.return_state)
567 end
568 return "hexadecimal_character_reference"
569 end
570
571 HtmlStates.numeric_reference_end_state = function(parser)
572 -- in this state, we don't need to
573 local character = parser.character_reference_code
574 -- we need to clean invalid character codes
575 if character == 0x00 or
576 character > 0x10FFFF or
577 is_surrogate(character)
578 then
579 character = 0xFFFD
580 -- should we add special support for "noncharacter"? I think we can pass them to the output anyway
581 elseif character_entity_replace_table[character] then
582 character = character_entity_replace_table[character]
583 end
584 parser:add_entity(uchar(character))
585 return parser.return_state
586 end
587
588
589 HtmlStates.markup_declaration_open = function(parser)
590 -- started by <!
591 -- we now need to find the following text, to find if we started comment, doctype, or cdata
592 local comment_pattern = "^%-%-"
593 local doctype_pattern = "^[Dd][Oo][Cc][Tt][Yy][Pp][Ee]"
594 local cdata_pattern = "^%[CDATA%["
595 local start_pos = parser.position
596 local text = parser.body
597 if text:match(comment_pattern, start_pos) then
598 -- local _, newpos = text:find(comment_pattern, start_pos)
599 -- we need to ignore next few characters
600 parser.ignored_pos = start_pos + 1
601 parser:start_token("comment", {data = {}})
602 return "comment_start"
603 elseif text:match(doctype_pattern, start_pos) then
604 parser.ignored_pos = start_pos + 6
605 parser:start_token("doctype", {name = {}, data = {}, force_quirks = false})
606 return "doctype"
607 elseif text:match(cdata_pattern, start_pos) then
608 parser.ignored_pos = start_pos + 6
609 local current_element = parser:current_node()
610 if current_element.xmlns == xmlns.HTML or not current_element.xmlns then
611 -- we change CDATA simply to comments
612 parser:start_token("comment", {data = {"[CDATA["}})
613 return "bogus_comment"
614 else
615 -- we are in XML mode, this happens for included SVG or MathML
616 return "cdata_section"
617 end
618 else
619 parser:start_token("comment", {data = {}})
620 return "bogus_comment"
621 end
622 -- local start, stop = string.find(parser.body, comment_pattern, parser.position)
623 end
624
625
626 HtmlStates.cdata_section = function(parser)
627 local codepoint = parser.codepoint
628 if codepoint == right_square then
629 return "cdata_section_bracket"
630 elseif codepoint == EOF then
631 parser:emit_eof()
632 else
633 parser:emit_character(uchar(codepoint))
634 return "cdata_section"
635 end
636 end
637
638 HtmlStates.cdata_section_bracket = function(parser)
639 local codepoint = parser.codepoint
640 if codepoint == right_square then
641 return "cdata_section_end"
642 else
643 parser:emit_character("]")
644 return parser:tokenize("cdata_section")
645 end
646 end
647
648 HtmlStates.cdata_section_end = function(parser)
649 local codepoint = parser.codepoint
650 if codepoint == right_square then
651 parser:emit_character("]")
652 return "cdata_section_end"
653 elseif codepoint == greater_than then
654 return "data"
655 else
656 parser:emit_character("]")
657 return parser:tokenize("cdata_section")
658 end
659 end
660
661
662 HtmlStates.comment_start = function(parser)
663 local codepoint = parser.codepoint
664 if codepoint == hyphen then
665 return "comment_start_dash"
666 elseif codepoint == greater_than then
667 parser:emit()
668 return "data"
669 else
670 return parser:tokenize("comment")
671 end
672 end
673
674 HtmlStates.comment_start_dash = function(parser)
675 local codepoint = parser.codepoint
676 if codepoint == hyphen then
677 return "comment_end"
678 elseif codepoint == greater_than then
679 parser:emit()
680 return data
681 elseif codepoint == EOF then
682 parser:emit()
683 parser:emit_eof()
684 else
685 parser:append_token_data("data", "-")
686 return parser:tokenize("comment")
687 end
688 end
689
690 HtmlStates.comment = function(parser)
691 local codepoint = parser.codepoint
692 codepoint = fix_null(codepoint)
693 if codepoint == less_than then
694 parser:append_token_data("data", uchar(codepoint))
695 return "comment_less_than"
696 elseif codepoint == hyphen then
697 return "comment_end_dash"
698 elseif codepoint == EOF then
699 parser:emit()
700 parser:emit_eof()
701 else
702 parser:append_token_data("data", uchar(codepoint))
703 end
704 return "comment"
705 end
706
707 HtmlStates.comment_less_than = function(parser)
708 local codepoint = parser.codepoint
709 if codepoint == exclam then
710 parser:append_token_data("data", uchar(codepoint))
711 return "comment_less_than_bang"
712 elseif codepoint == less_than then
713 parser:append_token_data("data", uchar(codepoint))
714 return "comment_less_than"
715 else
716 return parser:tokenize("comment")
717 end
718 end
719
720 HtmlStates.comment_less_than_bang = function(parser)
721 local codepoint = parser.codepoint
722 if codepoint == hyphen then
723 return "comment_less_than_bang_dash"
724 else
725 return parser:tokenize("comment")
726 end
727 end
728
729 HtmlStates.comment_less_than_bang_dash = function(parser)
730 local codepoint = parser.codepoint
731 if codepoint == hyphen then
732 return "comment_less_than_bang_dash_dash"
733 else
734 return parser:tokenize("comment_end_dash")
735 end
736
737 end
738
739 HtmlStates.comment_less_than_bang_dash_dash = function(parser)
740 -- these comment states start to be ridiculous
741 local codepoint = parser.codepoint
742 if codepoint == greater_than or codepoint == EOF then
743 return parser:tokenize("comment_end")
744 else
745 return parser:tokenize("comment_end")
746 end
747 end
748
749 HtmlStates.comment_end_dash = function(parser)
750 local codepoint = parser.codepoint
751 if codepoint == hyphen then
752 return "comment_end"
753 elseif codepoint == EOF then
754 parser:emit()
755 parser:emit_eof()
756 else
757 parser:append_token_data("data", uchar(codepoint))
758 return parser:tokenize("comment")
759 end
760 end
761
762 HtmlStates.comment_end = function(parser)
763 local codepoint = parser.codepoint
764 if codepoint == greater_than then
765 parser:emit()
766 return "data"
767 elseif codepoint == exclam then
768 return "comment_end_bang"
769 elseif codepoint == hyphen then
770 parser:append_token_data("data", "-")
771 return "comment_end"
772 elseif codepoint == EOF then
773 parser:emit()
774 parser:emit_eof()
775 else
776 parser:append_token_data("data", "--")
777 return parser:tokenize("comment")
778 end
779 end
780
781 HtmlStates.comment_end_bang = function(parser)
782 local codepoint = parser.codepoint
783 if codepoint == hyphen then
784 parser:append_token_data("data", "--!")
785 return "comment_end_dash"
786 elseif codepoint == greater_than then
787 parser:emit()
788 return "data"
789 elseif codepoint == EOF then
790 parser:emit()
791 parser:emit_eof()
792 else
793 parser:append_token_data("data", "--!")
794 return parser:tokenize("comment")
795 end
796 end
797
798 HtmlStates.end_tag_open = function(parser)
799 local codepoint = parser.codepoint
800 if is_alpha(codepoint) then
801 local data = {
802 name = {}
803 }
804 parser:start_token("end_tag", data)
805 return parser:tokenize("tag_name")
806 elseif codepoint == greater_than then
807 return "data"
808 elseif codepoint == EOF then
809 parser:discard_token()
810 parser:emit_character("</")
811 parser:emit_eof()
812 else
813 data = {
814 data = {}
815 }
816 parser:start_token("comment", data)
817 return parser:tokenize("bogus_comment")
818 end
819 end
820
821 HtmlStates.bogus_comment = function(parser)
822 -- started by <?
823 local codepoint = parser.codepoint
824 codepoint = fix_null(codepoint)
825 if codepoint == greater_than then
826 parser:emit()
827 return "data"
828 elseif codepoint == EOF then
829 parser:emit()
830 parser:emit_eof()
831 else
832 parser:append_token_data("data", uchar(codepoint))
833 return "bogus_comment"
834 end
835 end
836
837 local function doctype_eof(parser)
838 parser:set_token_data("force_quirks", true)
839 parser:emit()
840 parser:emit_eof()
841 end
842
843 HtmlStates.doctype = function(parser)
844 local codepoint = parser.codepoint
845 if is_space(codepoint) then
846 return "before_doctype_name"
847 elseif codepoint == greater_than then
848 return parser:tokenize("before_doctype_name")
849 elseif codepoint == EOF then
850 doctype_eof(parser)
851 else
852 return parser:tokenize("before_doctype_name")
853 end
854 end
855
856 HtmlStates.before_doctype_name = function(parser)
857 local codepoint = parser.codepoint
858 codepoint = fix_null(codepoint)
859 if is_space(codepoint) then
860 return "before_doctype_name"
861 elseif codepoint == greater_than then
862 parser:set_token_data("force_quirks", true)
863 parser:emit()
864 return "data"
865 elseif codepoint == EOF then
866 doctype_eof(parser)
867 elseif is_upper_alpha(codepoint) then
868 -- add lowercase name
869 parser:append_token_data("name", uchar(codepoint + 0x20))
870 return "doctype_name"
871 else
872 parser:append_token_data("name", uchar(codepoint))
873 return "doctype_name"
874 end
875 end
876
877 HtmlStates.doctype_name = function(parser)
878
879 local codepoint = parser.codepoint
880 codepoint = fix_null(codepoint)
881 if is_space(codepoint) then
882 return "after_doctype_name"
883 elseif codepoint == greater_than then
884 parser:emit()
885 return "data"
886 elseif codepoint == EOF then
887 doctype_eof(parser)
888 elseif is_upper_alpha(codepoint) then
889 -- add lowercase name
890 parser:append_token_data("name", uchar(codepoint + 0x20))
891 return "doctype_name"
892 else
893 parser:append_token_data("name", uchar(codepoint))
894 return "doctype_name"
895 end
896 end
897
898 HtmlStates.after_doctype_name = function(parser)
899 local codepoint = parser.codepoint
900 if is_space(codepoint) then
901 return "after_doctype_name"
902 elseif codepoint == greater_than then
903 parser:emit()
904 return "data"
905 elseif codepoint == EOF then
906 doctype_eof(parser)
907 else
908 parser:append_token_data("data", uchar(codepoint))
909 -- there are lot of complicated rules how to consume doctype,
910 -- but I think that for our purpose they aren't interesting.
911 -- so everything until EOF or > is consumed as token.data
912 return "consume_doctype_data"
913 end
914 end
915
916 HtmlStates.consume_doctype_data = function(parser)
917 -- this state just reads everything inside doctype as data
918 local codepoint = parser.codepoint
919 if codepoint == greater_than then
920 parser:emit()
921 return "data"
922 elseif codepoint == EOF then
923 doctype_eof(parser)
924 else
925 parser:append_token_data("data", uchar(codepoint))
926 return "consume_doctype_data"
927 end
928 end
929
930 HtmlStates.tag_name = function(parser)
931 local codepoint = parser.codepoint
932 codepoint = fix_null(codepoint)
933 if is_space(codepoint) then
934 return "before_attribute_name"
935 elseif codepoint == solidus then
936 return "self_closing_tag"
937 elseif codepoint == greater_than then
938 parser:emit()
939 return "data"
940 elseif is_upper_alpha(codepoint) then
941 local lower = string.lower(uchar(codepoint))
942 parser:append_token_data("name", lower)
943 elseif codepoint==EOF then
944 parser:emit()
945 parser:emit_eof()
946 else
947 local char = uchar(codepoint)
948 parser:append_token_data("name", char)
949 end
950 return "tag_name"
951
952 end
953
954 HtmlStates.self_closing_tag = function(parser)
955 local codepoint = parser.codepoint
956 if codepoint == greater_than then
957 parser.current_token.self_closing = true
958 parser:emit()
959 return "data"
960 else
961 return parser:tokenize("before_attribute_name")
962 end
963 end
964
965
966 HtmlStates.before_attribute_name = function(parser)
967 local codepoint = parser.codepoint
968 if is_space(codepoint) then
969 -- ignore spacing
970 return "before_attribute_name"
971 elseif codepoint == solidus or codepoint == greater_than then
972 -- reconsume in after_attribute_name
973 return parser:tokenize("after_attribute_name")
974 elseif codepoint == equals then
975 -- ToDo: handle https://html.spec.whatwg.org/multipage/parsing.html#parse-error-unexpected-equals-sign-before-attribute-name
976 else
977 -- start new attribute
978 parser:start_attribute()
979 return parser:tokenize("attribute_name")
980 end
981 end
982
983 HtmlStates.attribute_name = function(parser)
984 local codepoint = parser.codepoint
985 if is_space(codepoint)
986 or codepoint == solidus
987 or codepoint == greater_than
988 then
989 return parser:tokenize("after_attribute_name")
990 elseif codepoint == equals then
991 return "before_attribute_value"
992 elseif is_upper_alpha(codepoint) then
993 -- lowercase attribute names
994 local lower = string.lower(uchar(codepoint))
995 parser:append_token_data("current_attr_name", lower)
996 return "attribute_name"
997 else
998 parser:append_token_data("current_attr_name", uchar(codepoint))
999 return "attribute_name"
1000 end
1001 end
1002
1003 HtmlStates.after_attribute_name = function(parser)
1004 local codepoint = parser.codepoint
1005 if is_space(codepoint) then
1006 return "after_attribute_name"
1007 elseif codepoint == equals then
1008 return "before_attribute_value"
1009 elseif codepoint == solidus then
1010 return "self_closing_tag"
1011 elseif codepoint == greater_than then
1012 parser:emit()
1013 return "data"
1014 else
1015 parser:start_attribute()
1016 return parser:tokenize("attribute_name")
1017 end
1018 end
1019
1020 HtmlStates.before_attribute_value = function(parser)
1021 local codepoint = parser.codepoint
1022 if is_space(codepoint) then
1023 return "before_attribute_value"
1024 elseif codepoint == quoting then
1025 return "attribute_value_quoting"
1026 elseif codepoint == apostrophe then
1027 return "attribute_value_apostrophe"
1028 elseif codepoint == greater_than then
1029 parser:emit()
1030 return "data"
1031 else
1032 return parser:tokenize("attribute_value_unquoted")
1033 end
1034 end
1035
1036 HtmlStates.attribute_value_quoting = function(parser)
1037 local codepoint = parser.codepoint
1038 if codepoint == quoting then
1039 return "after_attribute_value_quoting"
1040 elseif codepoint == amperesand then
1041 parser.return_state = "attribute_value_quoting"
1042 return "character_reference"
1043 else
1044 parser:append_token_data("current_attr_value", uchar(codepoint))
1045 return "attribute_value_quoting"
1046 end
1047 end
1048
1049 HtmlStates.attribute_value_apostrophe = function(parser)
1050 local codepoint = parser.codepoint
1051 if codepoint == apostrophe then
1052 return "after_attribute_value_quoting"
1053 elseif codepoint == amperesand then
1054 parser.return_state = "attribute_value_apostrophe"
1055 return "character_reference"
1056 else
1057 parser:append_token_data("current_attr_value", uchar(codepoint))
1058 return "attribute_value_apostrophe"
1059 end
1060 end
1061
1062 HtmlStates.attribute_value_unquoted = function(parser)
1063 local codepoint = parser.codepoint
1064 if is_space(codepoint) then
1065 return "before_attribute_name"
1066 elseif codepoint == amperesand then
1067 parser.return_state = "attribute_value_unquoted"
1068 return "character_reference"
1069 elseif codepoint == greater_than then
1070 parser:emit()
1071 return "data"
1072 else
1073 parser:append_token_data("current_attr_value", uchar(codepoint))
1074 return "attribute_value_unquoted"
1075 end
1076 end
1077
1078 HtmlStates.after_attribute_value_quoting = function(parser)
1079 local codepoint = parser.codepoint
1080 if is_space(codepoint) then
1081 return "before_attribute_name"
1082 elseif codepoint == solidus then
1083 return "self_closing_tag"
1084 elseif codepoint == greater_than then
1085 parser:emit()
1086 return "data"
1087 else
1088 return parser:tokenize("before_attribute_name")
1089 end
1090 end
1091
1092 HtmlStates.rcdata = function(parser)
1093 -- this is the default state
1094 local codepoint = parser.codepoint
1095 -- print("codepoint", parser.codepoint)
1096 codepoint = fix_null(codepoint)
1097 if codepoint == less_than then
1098 -- start of tag
1099 return "rcdata_less_than"
1100 elseif codepoint == amperesand then
1101 -- we must save the current state
1102 -- what we will return to after entity
1103 parser.return_state = "rcdata"
1104 return "character_reference"
1105 elseif codepoint == EOF then
1106 parser:emit_eof()
1107 else
1108 parser:emit_character(uchar(codepoint))
1109 end
1110 return "rcdata"
1111 end
1112
1113 local function discard_rcdata_end_tag(parser, text)
1114 parser:discard_token()
1115 parser:emit_character(text)
1116 end
1117
1118 HtmlStates.rcdata_less_than = function(parser)
1119 local codepoint = parser.codepoint
1120 if codepoint == solidus then
1121 return "rcdata_end_tag_open"
1122 else
1123 discard_rcdata_end_tag(parser, "<")
1124 return parser:tokenize("rcdata")
1125 end
1126 end
1127
1128 HtmlStates.rcdata_end_tag_open = function(parser)
1129 local codepoint = parser.codepoint
1130 if is_alpha(codepoint) then
1131 parser:start_token("end_tag", {name={}})
1132 parser.temp_buffer = {}
1133 return parser:tokenize("rcdata_end_tag_name")
1134 else
1135 discard_rcdata_end_tag(parser, "</")
1136 return parser:tokenize("rcdata")
1137 end
1138 end
1139
1140
1141
1142 HtmlStates.rcdata_end_tag_name = function(parser)
1143 -- we need to find name of the currently opened tag
1144 local parent = parser:get_parent() or {}
1145 local opened_tag = parent.tag
1146 local current_tag = table.concat(parser.current_token.name or {})
1147 local codepoint = parser.codepoint
1148 if is_upper_alpha(codepoint) then
1149 parser:append_token_data("name", uchar(codepoint + 0x20))
1150 -- insert current char to temp buffer
1151 table.insert(parser.temp_buffer, uchar(codepoint))
1152 return "rcdata_end_tag_name"
1153 elseif is_lower_alpha(codepoint) then
1154 parser:append_token_data("name", uchar(codepoint))
1155 table.insert(parser.temp_buffer, uchar(codepoint))
1156 return "rcdata_end_tag_name"
1157 elseif opened_tag == current_tag then
1158 if is_space(codepoint) then
1159 return "before_attribute_name"
1160 elseif codepoint == solidus then
1161 return "self_closing_tag"
1162 elseif codepoint == greater_than then
1163 parser:emit()
1164 return "data"
1165 end
1166 else
1167 discard_rcdata_end_tag(parser, "</" .. table.concat(parser.temp_buffer))
1168 parser.temp_buffer = {}
1169 return parser:tokenize("rcdata")
1170 end
1171 end
1172
1173 HtmlStates.rawtext = function(parser)
1174 local codepoint = parser.codepoint
1175 codepoint = fix_null(codepoint)
1176 if codepoint == less_than then
1177 return "rawtext_less_than"
1178 elseif codepoint == EOF then
1179 parser:emit_eof()
1180 else
1181 parser:emit_character(uchar(codepoint))
1182 return "rawtext"
1183 end
1184 end
1185
1186 HtmlStates.rawtext_less_than = function(parser)
1187 local codepoint = parser.codepoint
1188 if codepoint == solidus then
1189 return "rawtext_end_tag_open"
1190 else
1191 parser:emit_character("<")
1192 return parser:tokenize("rawtext")
1193 end
1194 end
1195
1196 HtmlStates.rawtext_end_tag_open = function(parser)
1197 local codepoint = parser.codepoint
1198 if is_alpha(codepoint) then
1199 parser:start_token("end_tag", {name={}})
1200 parser.temp_buffer = {}
1201 return parser:tokenize("rawtext_end_tag_name")
1202 else
1203 parser:emit_character("</")
1204 return parser:tokenize("rawtext")
1205 end
1206 end
1207
1208 HtmlStates.rawtext_end_tag_name = function(parser)
1209 -- we need to find name of the currently opened tag
1210 local parent = parser:get_parent() or {}
1211 local opened_tag = parent.tag
1212 local current_tag = table.concat(parser.current_token.name or {})
1213 local codepoint = parser.codepoint
1214 if is_upper_alpha(codepoint) then
1215 parser:append_token_data("name", uchar(codepoint + 0x20))
1216 table.insert(parser.temp_buffer, uchar(codepoint))
1217 return "rawtext_end_tag_name"
1218 elseif is_lower_alpha(codepoint) then
1219 parser:append_token_data("name", uchar(codepoint))
1220 table.insert(parser.temp_buffer, uchar(codepoint))
1221 return "rawtext_end_tag_name"
1222 elseif opened_tag == current_tag then
1223 if is_space(codepoint) then
1224 return "before_attribute_name"
1225 elseif codepoint == solidus then
1226 return "self_closing_tag"
1227 elseif codepoint == greater_than then
1228 parser:emit()
1229 return "data"
1230 end
1231 else
1232 discard_rcdata_end_tag(parser, "</" .. table.concat(parser.temp_buffer))
1233 parser.temp_buffer = {}
1234 return parser:tokenize("rawtext")
1235 end
1236 end
1237
1238 HtmlStates.script_data = function(parser)
1239 local codepoint = parser.codepoint
1240 codepoint = fix_null(codepoint)
1241 if codepoint == less_than then
1242 return "script_data_less_than"
1243 elseif codepoint == EOF then
1244 parser:emit_eof()
1245 else
1246 parser:emit_character(uchar(codepoint))
1247 return "script_data"
1248 end
1249 end
1250
1251 HtmlStates.script_data_less_than = function(parser)
1252 local codepoint = parser.codepoint
1253 if codepoint == solidus then
1254 parser.temp_buffer = {}
1255 return "script_data_end_tag_open"
1256 elseif codepoint == exclam then
1257 parser:emit_character("<!")
1258 return "script_data_escape_start"
1259 else
1260 parser:emit_character("<")
1261 return parser:tokenize("script_data")
1262 end
1263 end
1264
1265 HtmlStates.script_data_end_tag_open = function(parser)
1266 local codepoint = parser.codepoint
1267 if is_alpha(codepoint) then
1268 parser:start_token("end_tag", {name={}})
1269 return parser:tokenize("script_data_end_tag_name")
1270 else
1271 parser:emit_character("</")
1272 return parser:tokenize("script_data")
1273 end
1274 end
1275
1276 HtmlStates.script_data_end_tag_name = function(parser)
1277 -- we need to find name of the currently opened tag
1278 local parent = parser:get_parent() or {}
1279 local opened_tag = parent.tag
1280 local current_tag = table.concat(parser.current_token.name or {})
1281 local codepoint = parser.codepoint
1282 if is_upper_alpha(codepoint) then
1283 parser:append_token_data("name", uchar(codepoint + 0x20))
1284 table.insert(parser.temp_buffer, uchar(codepoint))
1285 return "script_data_end_tag_name"
1286 elseif is_lower_alpha(codepoint) then
1287 parser:append_token_data("name", uchar(codepoint))
1288 table.insert(parser.temp_buffer, uchar(codepoint))
1289 return "script_data_end_tag_name"
1290 elseif opened_tag == current_tag then
1291 if is_space(codepoint) then
1292 return "before_attribute_name"
1293 elseif codepoint == solidus then
1294 return "self_closing_tag"
1295 elseif codepoint == greater_than then
1296 parser:emit()
1297 return "data"
1298 end
1299 else
1300 discard_rcdata_end_tag(parser, "</" .. table.concat(parser.temp_buffer))
1301 parser.temp_buffer = {}
1302 return parser:tokenize("script_data")
1303 end
1304
1305 end
1306
1307 HtmlStates.script_data_escape_start = function(parser)
1308 local codepoint = parser.codepoint
1309 if codepoint == hyphen then
1310 parser:emit_character("-")
1311 return "script_data_escape_start_dash"
1312 else
1313 parser:tokenize("script_data")
1314 end
1315 end
1316
1317 HtmlStates.script_data_escape_start_dash = function(parser)
1318 local codepoint = parser.codepoint
1319 if codepoint == hyphen then
1320 parser:emit_character("-")
1321 return "script_data_escaped_dash_dash"
1322 else
1323 parser:tokenize("script_data")
1324 end
1325
1326 end
1327
1328
1329 HtmlStates.script_data_escaped = function(parser)
1330 local codepoint = parser.codepoint
1331 codepoint = fix_null(codepoint)
1332 if codepoint == hyphen then
1333 parser:emit_character("-")
1334 return "script_data_escaped_dash"
1335 elseif codepoint == less_than then
1336 return "script_data_escaped_less_than_sign"
1337 elseif codepoint == EOF then
1338 parser:emit_eof()
1339 else
1340 parser:emit_character(uchar(codepoint))
1341 return "script_data_escaped"
1342 end
1343 end
1344
1345 HtmlStates.script_data_escaped_dash = function(parser)
1346 local codepoint = parser.codepoint
1347 codepoint = fix_null(codepoint)
1348 if codepoint == hyphen then
1349 parser:emit_character("-")
1350 return "script_data_escaped_dash_dash"
1351 elseif codepoint == less_than then
1352 return "script_data_escaped_less_than_sign"
1353 elseif codepoint == EOF then
1354 parser:emit_eof()
1355 else
1356 parser:emit_character(uchar(codepoint))
1357 return "script_data_escaped"
1358 end
1359
1360 end
1361
1362 HtmlStates.script_data_escaped_dash_dash = function(parser)
1363 local codepoint = parser.codepoint
1364 codepoint = fix_null(codepoint)
1365 if codepoint == hyphen then
1366 parser:emit_character("-")
1367 return "script_data_escaped_dash_dash"
1368 elseif codepoint == less_than then
1369 return "script_data_escaped_less_than_sign"
1370 elseif codepoint == greater_than then
1371 parser:emit_character(">")
1372 return "script_data"
1373 elseif codepoint == EOF then
1374 parser:emit_eof()
1375 else
1376 parser:emit_character(uchar(codepoint))
1377 return "script_data_escaped"
1378 end
1379
1380 end
1381
1382 HtmlStates.script_data_escaped_less_than_sign = function(parser)
1383 local codepoint = parser.codepoint
1384 if codepoint == solidus then
1385 parser.temp_buffer = {}
1386 return "script_data_escaped_end_tag_open"
1387 elseif is_alpha(codepoint) then
1388 parser.temp_buffer = {}
1389 parser:emit_character("<")
1390 return parser:tokenize("script_data_double_escape_start")
1391 else
1392 parser:emit_character("<")
1393 return parser:tokenize("script_data_escaped")
1394 end
1395 end
1396
1397 HtmlStates.script_data_escaped_end_tag_open = function(parser)
1398 local codepoint = parser.codepoint
1399 if is_alpha(codepoint) then
1400 parser:start_token("end_tag", {name={}})
1401 return parser:tokenize("script_data_escaped_end_tag_name")
1402 else
1403 parser:emit_character("</")
1404 return parser:tokenize("script_data_escaped")
1405 end
1406 end
1407
1408 HtmlStates.script_data_escaped_end_tag_name = function(parser)
1409 -- we need to find name of the currently opened tag
1410 local parent = parser:get_parent() or {}
1411 local opened_tag = parent.tag
1412 local current_tag = table.concat(parser.current_token.name or {})
1413 local codepoint = parser.codepoint
1414 if is_upper_alpha(codepoint) then
1415 parser:append_token_data("name", uchar(codepoint + 0x20))
1416 table.insert(parser.temp_buffer, uchar(codepoint))
1417 return "script_data_escaped_end_tag_name"
1418 elseif is_lower_alpha(codepoint) then
1419 parser:append_token_data("name", uchar(codepoint))
1420 table.insert(parser.temp_buffer, uchar(codepoint))
1421 return "script_data_escaped_end_tag_name"
1422 elseif opened_tag == current_tag then
1423 if is_space(codepoint) then
1424 return "before_attribute_name"
1425 elseif codepoint == solidus then
1426 return "self_closing_tag"
1427 elseif codepoint == greater_than then
1428 parser:emit()
1429 return "data"
1430 end
1431 else
1432 discard_rcdata_end_tag(parser, "</" .. table.concat(parser.temp_buffer))
1433 parser.temp_buffer = {}
1434 return parser:tokenize("script_data_escaped")
1435 end
1436 end
1437
1438 HtmlStates.script_data_double_escape_start = function(parser)
1439 local codepoint = parser.codepoint
1440 if is_alpha(codepoint) or
1441 codepoint == solidus or
1442 codepoint == greater_than
1443 then
1444 local current_tag = table.concat(parser.current_token.name or {})
1445 parser:emit_character(uchar(codepoint))
1446 if current_tag == "script" then
1447 return "script_data_double_escaped"
1448 else
1449 return "script_data_escaped"
1450 end
1451 elseif is_upper_alpha(codepoint) then
1452 parser:emit_character(uchar(codepoint))
1453 table.insert(parser.temp_buffer, uchar(codepoint) + 0x20)
1454 return "script_data_double_escape_start"
1455 elseif is_lower_alpha(codepoint) then
1456 parser:emit_character(uchar(codepoint))
1457 table.insert(parser.temp_buffer, uchar(codepoint))
1458 return "script_data_double_escape_start"
1459 else
1460 return parser:tokenize("script_data_escaped")
1461 end
1462 end
1463
1464 HtmlStates.script_data_double_escaped = function(parser)
1465 local codepoint = parser.codepoint
1466 codepoint = fix_null(codepoint)
1467 if codepoint == hyphen then
1468 parser:emit_character("-")
1469 return "script_data_double_escaped_dash"
1470 elseif codepoint == less_than then
1471 parser:emit_character("<")
1472 return "script_data_double_escaped_less_than_sign"
1473 elseif codepoint == EOF then
1474 parser:emit_eof()
1475 else
1476 parser:emit_character(uchar(codepoint))
1477 return "script_data_double_escaped"
1478 end
1479 end
1480
1481 HtmlStates.script_data_double_escaped_dash = function(parser)
1482 local codepoint = parser.codepoint
1483 codepoint = fix_null(codepoint)
1484 if codepoint == hyphen then
1485 parser:emit_character("-")
1486 return "script_data_double_escaped_dash"
1487 elseif codepoint == less_than then
1488 parser:emit_character("<")
1489 return "script_data_double_escaped_less_than_sign"
1490 elseif codepoint == greater_than then
1491 parser:emit_character(">")
1492 return "script_data"
1493 elseif codepoint == EOF then
1494 parser:emit_eof()
1495 else
1496 parser:emit_character(uchar(codepoint))
1497 return "script_data_double_escaped"
1498 end
1499 end
1500
1501 HtmlStates.script_data_double_escaped_less_than_sign = function(parser)
1502 local codepoint = parser.codepoint
1503 if codepoint == solidus then
1504 parser:emit("/")
1505 return "script_data_double_escape_end"
1506 else
1507 return parser:tokenize("script_data_double_escaped")
1508 end
1509 end
1510
1511 HtmlStates.script_data_double_escape_end = function(parser)
1512 local codepoint = parser.codepoint
1513 if is_alpha(codepoint) or
1514 codepoint == solidus or
1515 codepoint == greater_than
1516 then
1517 local current_tag = table.concat(parser.current_token.name or {})
1518 parser:emit_character(uchar(codepoint))
1519 if current_tag == "script" then
1520 return "script_data_escaped"
1521 else
1522 return "script_data_double_escaped"
1523 end
1524 elseif is_upper_alpha(codepoint) then
1525 parser:emit_character(uchar(codepoint))
1526 table.insert(parser.temp_buffer, uchar(codepoint) + 0x20)
1527 return "script_data_double_escape_start"
1528 elseif is_lower_alpha(codepoint) then
1529 parser:emit_character(uchar(codepoint))
1530 table.insert(parser.temp_buffer, uchar(codepoint))
1531 return "script_data_double_escape_start"
1532 else
1533 return parser:tokenize("script_data_double_escaped")
1534 end
1535
1536 end
1537
1538 -- formatting elements needs special treatment
1539 local formatting_element_names ={
1540 a = true, b = true, big = true, code = true, em = true, font = true, i = true, nobr = true, s = true, small = true, strike = true, strong = true, tt = true, u = true
1541 }
1542 local function is_formatting_element(name)
1543 return formatting_element_names[name]
1544 end
1545
1546 local function hash_from_array(tbl)
1547 local t = {}
1548 for _, v in ipairs(tbl) do t[v] = true end
1549 return t
1550 end
1551
1552
1553 local special_elements_list = hash_from_array {"address", "applet", "area", "article", "aside",
1554 "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption",
1555 "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt",
1556 "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame",
1557 "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup",
1558 "hr", "html", "iframe", "img", "input", "keygen", "li", "link", "listing",
1559 "main", "marquee", "menu", "meta", "nav", "noembed", "noframes", "noscript",
1560 "object", "ol", "p", "param", "plaintext", "pre", "script", "section",
1561 "select", "source", "style", "summary", "table", "tbody", "td", "template",
1562 "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp",
1563 "mi","mo","mn","ms","mtext", "annotation-xml","foreignObject","desc", "title"
1564 }
1565
1566
1567 local function is_special(name)
1568 return special_elements_list[name]
1569 end
1570
1571 -- these lists are used in HtmlParser:generate_implied_endtags()
1572 local implied_endtags = {dd=true, dt=true, li = true, optgroup = true, option = true, p = true, rb = true, rp = true, rd = true, trc = true}
1573 local implied_endtags_thoroughly = {dd=true, dt=true, li = true, optgroup = true, option = true, p = true,
1574 rb = true, rp = true, rd = true, trc = true, caption = true, colgroup = true, tbody = true, td = true,
1575 tfoot = true, th = true, thead = true, tr = true
1576 }
1577
1578 -- find if unfinished tags list contain a tag
1579 -- it fails if any element from element_list is matched before that tag
1580 local function is_in_scope(parser, target, element_list)
1581 for i = #parser.unfinished, 1, -1 do
1582 local node = parser.unfinished[i]
1583 local tag = node.tag
1584 if tag == target then
1585 return true
1586 elseif element_list[tag] then
1587 return false
1588 end
1589 end
1590 return false
1591 end
1592
1593 local particular_scope_elements = { applet = true, caption = true, html = true, table = true, td = true,
1594 th = true, marquee = true, object = true, template = true, mi = true, mo = true, mn = true,
1595 ms = true, mtext = true, ["annotation-xml"] = true, foreignObject = true, desc = true, title = true,
1596 }
1597
1598 local function is_in_particular_scope(parser, target)
1599 return is_in_scope(parser, target, particular_scope_elements)
1600 end
1601
1602 -- derived scope lists
1603 --
1604 -- list_item scope
1605 local list_item_scope_elements = {ol = true, ul = true}
1606 for k,v in pairs(particular_scope_elements) do list_item_scope_elements[k] = v end
1607
1608 local function is_in_list_item_scope(parser, target)
1609 return is_in_scope(parser, target, list_item_scope_elements)
1610 end
1611
1612 -- button scope
1613 local button_scope_elements = {button = true}
1614 for k,v in pairs(particular_scope_elements) do button_scope_elements[k] = v end
1615
1616 local function is_in_button_scope(parser, target)
1617 return is_in_scope(parser, target, button_scope_elements)
1618 end
1619
1620 -- table scope
1621 local table_scope_elements = {html = true, table = true, template = true}
1622
1623 local function is_in_table_scope(parser, target)
1624 return is_in_scope(parser, target, table_scope_elements)
1625 end
1626
1627 -- select scope
1628 local function is_in_select_scope(parser, target)
1629 -- this scope is specific, because it supports all tags except two
1630 for i = #parser.unfinished, 1, -1 do
1631 local node = parser.unfinished[i]
1632 local tag = node.tag
1633 if tag == target then
1634 return true
1635 elseif tag == "optgroup" or tag == "option" then
1636 -- only these two tags are supported
1637 else
1638 return false
1639 end
1640 end
1641 return false
1642 end
1643
1644 -- List of active formatting elements
1645 -- https://html.spec.whatwg.org/multipage/parsing.html#the-list-of-active-formatting-elements
1646 -- we don't implement it yet, but maybe in the future.
1647
1648
1649 local HtmlTreeStates = {}
1650
1651
1652
1653
1654
1655
1656 --- @type HtmlParser
1657 local HtmlParser = {}
1658
1659 --- Initialize the HTML Object
1660 ---@param body string HTML to be parsed
1661 ---@return table initialized object
1662 function HtmlParser:init(body)
1663 local o ={}
1664 setmetatable(o, self)
1665 self.__index = self
1666 o.body = self:normalize_newlines(body) -- HTML string
1667 o.position = 0 -- position in the parsed string
1668 o.unfinished = {} -- insert Root node into the list of opened elements
1669 o.Document = Root:init()
1670 o.default_state = "data" -- default state machine state
1671 o.state = o.default_state -- working state of the machine
1672 o.return_state = o.default_state -- special state set by entities parsing
1673 o.temp_buffer = {} -- keep temporary data
1674 o.current_token = {type="start"} -- currently processed token
1675 o.insertion_mode = "initial" -- tree construction state
1676 o.head_pointer = nil -- pointer to the Head element
1677 o.form_pointer = nil
1678 o.active_formatting = {} -- list of active formatting elements
1679 o.scripting_flag = false -- we will not support scripting
1680 return o
1681 end
1682
1683 function HtmlParser:normalize_newlines(body)
1684 -- we must normalize newlines
1685 return body:gsub("\r\n", "\n"):gsub("\r", "\n")
1686 end
1687
1688 -- declare void elements
1689 local self_closing_tags_list = {"area", "base", "br", "col", "embed", "hr", "img", "input",
1690 "link", "meta", "param", "source", "track", "wbr"}
1691
1692 local self_closing_tags = {}
1693 for _,v in ipairs(self_closing_tags_list) do self_closing_tags[v] = true end
1694
1695
1696
1697 --- Execute the HTML parser
1698 --- @return table Root node of the HTML DOM
1699 function HtmlParser:parse()
1700 -- we assume utf8 input, you must convert it yourself if the source is
1701 -- in a different encoding. for example using luaxml-encodings library
1702 self.text = {}
1703 self.state = self.default_state
1704 -- this should enable us to pass over some characters that we want to ignore
1705 -- for example scripts, css, etc.
1706 self.ignored_pos = -1
1707 for pos, ucode in utf8.codes(self.body) do
1708 -- save buffer info and require the tokenize function
1709 if pos > self.ignored_pos then
1710 self.position = pos
1711 self.codepoint = ucode
1712 self.character = uchar(ucode)
1713 self.state = self:tokenize(self.state) or self.state -- if tokenizer don't return new state, assume that it continues in the current state
1714 end
1715 end
1716 return self:finish()
1717 end
1718
1719 function HtmlParser:tokenize(state)
1720 local state = state or self.state
1721 local ucode = self.codepoint
1722 local text = self.text
1723
1724 self.last_position = self.position
1725 self.element_state = false
1726 -- execute state machine object and return new state
1727 local fn = HtmlStates[state] or function(parser) return self.default_state end
1728 local newstate = fn(self)
1729 -- this should enable changing state from elements that needs special treatment, like <script> or <style>
1730 if self.element_state then return self.element_state end
1731 -- print("newstate", newstate, state, uchar(ucode or 32))
1732 return newstate
1733 end
1734
1735 function HtmlParser:start_token(typ, data)
1736 -- emit the previous token
1737 -- self:emit()
1738 data.type = typ
1739 self.current_token = data
1740 end
1741
1742 function HtmlParser:discard_token()
1743 self.current_token = {type="empty"}
1744 end
1745
1746
1747
1748 function HtmlParser:append_token_data(name, data)
1749 -- append data to the current token
1750 local token = self.current_token or {}
1751 if token[name] and type(token[name]) == "table" then
1752 table.insert(token[name], data)
1753 end
1754 end
1755
1756 function HtmlParser:set_token_data(name, data)
1757 local token = self.current_token or {}
1758 token[name] = data
1759 end
1760
1761 function HtmlParser:flush_temp_buffer()
1762 -- write stuff from the temp buffer back to the document
1763 local token = self.current_token
1764 if token.type == "start_tag" then
1765 -- in start tag, entities can be only in attribute value
1766 for _, char in ipairs(self.temp_buffer) do
1767 table.insert(token.current_attr_value, char)
1768 end
1769 elseif self.return_state == "data" then
1770 -- handle entities in text
1771 for _, char in ipairs(self.temp_buffer) do
1772 self:start_token("character", {char=char})
1773 self:emit()
1774 end
1775 end
1776 self.temp_buffer = {}
1777 end
1778
1779 function HtmlParser:add_entity(char)
1780 local token = self.current_token
1781 if token.type == "start_tag" then
1782 table.insert(token.current_attr_value, char)
1783 else
1784 self:start_token("character", {char=char})
1785 self:emit()
1786 end
1787 self.temp_buffer = {}
1788 end
1789
1790 function HtmlParser:emit(token)
1791 -- state machine functions should use this function to emit tokens
1792 local token = token or self.current_token
1793 -- print("Emit", token.type)
1794 local token_type = token.type
1795 if token_type == "character" then
1796 table.insert(self.text, token.char)
1797 elseif token_type == "doctype" then
1798 self:add_text()
1799 self:add_doctype()
1800 elseif token_type == "start_tag" then
1801 self:add_text()
1802 -- self:start_attribute()
1803 self:reset_insertion_mode()
1804 self:start_tag()
1805 -- print("Emit start tag", table.concat(token.name))
1806 -- save last attribute
1807 elseif token_type == "end_tag" then
1808 self:add_text()
1809 self:end_tag()
1810 -- print("Emit end tag", table.concat(token.name))
1811 elseif token_type == "comment" then
1812 self:add_text()
1813 self:add_comment()
1814 -- self:start_attribute()
1815 elseif token_type == "empty" then
1816
1817 end
1818 -- self.current_token = {type="empty"}
1819 end
1820
1821 function HtmlParser:emit_character(text)
1822 self:start_token("character", {char=text})
1823 self:emit()
1824 end
1825
1826 function HtmlParser:emit_eof()
1827 self:start_token("end_of_file", {})
1828 self:emit()
1829 end
1830
1831 function HtmlParser:get_parent()
1832 -- return parent element
1833 return self.unfinished[#self.unfinished] or self.Document
1834 end
1835
1836 function HtmlParser:close_element()
1837 -- return parent element and remove it from the unfinished list
1838 return table.remove(self.unfinished)
1839 end
1840
1841 function HtmlParser:add_text(text)
1842 -- process current text node
1843 local text = text
1844 if not text then
1845 text = self.text
1846 end
1847 if type(text) == "table" then
1848 if #text > 0 then
1849 text = table.concat(text)
1850 end
1851 end
1852 if type(text) == "string" and text~="" then
1853 local parent = self:get_parent()
1854 local node = Text:init(text, parent)
1855 parent:add_child(node)
1856 end
1857 self.text = {}
1858 end
1859
1860
1861 function HtmlParser:start_attribute()
1862 local token = self.current_token or {}
1863 if token.type == "start_tag" then
1864 local attr_name = table.concat(token.current_attr_name)
1865 local attr_value = table.concat(token.current_attr_value) or ""
1866 if attr_name ~= "" then
1867 -- token.attr[attr_name] = attr_value
1868 table.insert(token.attr, {name = attr_name, value = attr_value})
1869 -- print("saving attribute", attr_name, attr_value)
1870 end
1871 self:set_token_data("current_attr_name", {})
1872 self:set_token_data("current_attr_value", {})
1873 end
1874 end
1875
1876 function HtmlParser:set_xmlns(node, parent)
1877 -- handle xmlns
1878 local in_attr = false
1879 -- try to find xmlns in node's attributes first
1880 for _, attr in ipairs(node.attr) do
1881 if attr.name == "xmlns" then
1882 node.xmlns = attr.value
1883 in_attr = true
1884 break
1885 end
1886 end
1887 if not in_attr then
1888 -- if we cannot find xmlns attribute, then use
1889 -- xmlns from the parent element, or the default xmlns
1890 local parent = self:get_parent()
1891 node.xmlns = parent.xmlns or xmlns.HTML
1892 end
1893 end
1894
1895 function HtmlParser:pop_element()
1896 -- close the current element and add it to the DOM
1897 local el = self:close_element()
1898 local parent = self:get_parent()
1899 parent:add_child(el)
1900 return el
1901 end
1902
1903 local close_p_at_start = hash_from_array {"address", "article", "aside", "blockquote", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "main", "menu", "nav", "ol", "p", "search", "section", "summary", "ul", "pre", "listing", "form", "table", "xmp", "hr"}
1904
1905 local close_headers = hash_from_array {"h1", "h2", "h3", "h4", "h5", "h6"}
1906
1907 local body_modes = hash_from_array {"in_body", "in_cell", "in_row", "in_select", "in_table", "in_table_body", "in_frameset"}
1908
1909 local list_items = hash_from_array {"li", "dt", "dd"}
1910
1911 local close_address_at_end = hash_from_array{"address", "article", "aside", "blockquote", "button", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "main", "menu", "nav", "ol", "pre", "search", "section", "summary", "ul", "form"}
1912
1913
1914 function HtmlParser:close_unfinished(name)
1915 -- close all unfinished elements until the element with the given name is found
1916 for i = #self.unfinished, 1, -1 do
1917 local el = self:pop_element()
1918 if el.tag == name then
1919 break
1920 end
1921 end
1922 end
1923
1924
1925 function HtmlParser:close_paragraph()
1926 -- close currently open <p> elements
1927 self:close_unfinished("p")
1928 end
1929
1930 function HtmlParser:current_element_name()
1931 -- return name of the current element
1932 return self:get_parent().tag
1933 end
1934
1935 local not_specials = hash_from_array { "address", "div", "p"}
1936
1937 local function handle_list_item(self, name)
1938 -- we handle li, dt and dd. dt and dd should close each other, li closes only itself
1939 local names = {dt = true, dd = true}
1940 if name == "li" then names = {li=true} end
1941 for i = #self.unfinished, 1, -1 do
1942 local current = self.unfinished[i]
1943 local current_tag = current.tag
1944 if names[current_tag] then
1945 self:generate_implied_endtags(nil, {current.tag})
1946 for j = #self.unfinished, i, -1 do
1947 self:pop_element()
1948 end
1949 break
1950 elseif is_special(current_tag) and not not_specials[name] then
1951 break
1952 end
1953 end
1954 end
1955
1956 local close_paragraph = function(self)
1957 if is_in_button_scope(self, "p") then
1958 self:close_paragraph()
1959 end
1960 end
1961
1962 function HtmlParser:handle_insertion_mode(token)
1963 -- simple handling of https://html.spec.whatwg.org/multipage/parsing.html#tree-construction
1964 -- we don't support most rules, just the most important for avoiding mismatched tags
1965
1966 if body_modes[self.insertion_mode] then
1967 if token.type == "start_tag" then
1968 local name = table.concat(token.name)
1969 if close_p_at_start[name] then close_paragraph(self) end
1970 if close_headers[name] then
1971 close_paragraph(self)
1972 -- close current element if it is already header
1973 if close_headers[self:current_element_name()] then
1974 self:pop_element()
1975 end
1976 elseif name == "pre" or name == "listing" then
1977 -- we should ignore next "\n" char token
1978 elseif name == "image" then
1979 -- image tag is an error, change to <img>
1980 token.name = {"img"}
1981 elseif list_items[name] then
1982 handle_list_item(self, name)
1983 close_paragraph(self)
1984 end
1985 elseif token.type == "end_tag" then
1986 local name = table.concat(token.name)
1987 if close_address_at_end[name] then
1988 if is_in_scope(self, name, {}) then
1989 self:generate_implied_endtags()
1990 self:close_unfinished(name)
1991 return false
1992 else
1993 token.type = "ignore"
1994 end
1995 elseif name == "p" then
1996 if not is_in_button_scope(self, "p") then
1997 local parent = self:get_parent()
1998 local node = Element:init("p", parent)
1999 table.insert(self.unfinished, node)
2000 end
2001 -- use self:close_paragraph() instead of close_paragraph() because we don't need to check scope at this point
2002 self:close_paragraph()
2003 elseif name == "br" then
2004 token.type = "start_tag"
2005 elseif close_headers[name] then
2006 local header_in_scope = false
2007 -- detect, if there are any open h1-h6 tag and close it
2008 for el, _ in pairs(close_headers) do
2009 if is_in_scope(self, el, {}) then
2010 header_in_scope = el
2011 break
2012 end
2013 end
2014 if not header_in_scope then
2015 token.type = "ignore"
2016 else
2017 self:close_unfinished(header_in_scope)
2018 end
2019 end
2020 end
2021 end
2022 return true
2023 end
2024
2025 local rawtext_elements = hash_from_array {"style", "textarea", "xmp"}
2026
2027
2028 function HtmlParser:start_tag()
2029 local token = self.current_token
2030 self:handle_insertion_mode(token)
2031 if token.type == "start_tag" then
2032 -- close all currently opened attributes
2033 self:start_attribute()
2034 -- initiate Element object, pass attributes and info about self_closing
2035 local name = table.concat(token.name)
2036 local parent = self:get_parent()
2037 local node = Element:init(name, parent)
2038 node.attr = token.attr
2039 node.self_closing = token.self_closing
2040 self:set_xmlns(node)
2041 -- in this handler we should close <p> or <li> elements without explicit closing tags
2042 if token.self_closing -- <img />
2043 or self_closing_tags[name] -- void elements
2044 then
2045 parent:add_child(node, node.tag)
2046 else
2047 -- add to the unfinished list
2048 table.insert(self.unfinished, node)
2049 end
2050 if name == "title" then
2051 self.element_state = "rcdata"
2052 elseif rawtext_elements[name] then
2053 self.element_state = "rawtext"
2054 elseif name == "script" then
2055 self.element_state = "script_data"
2056 end
2057 end
2058 end
2059
2060 function HtmlParser:end_tag()
2061 -- close current opened element
2062 local token = self.current_token
2063 local should_pop = self:handle_insertion_mode(token)
2064 if token.type == "end_tag" then
2065 if #self.unfinished==0 then return nil end
2066 -- we shouldn't close elements if handle_insertion_mode() already closed them
2067 if should_pop then
2068 -- close the current element only if the token is in the current scope
2069 if is_in_scope(self, table.concat(token.name), {}) then
2070 self:pop_element()
2071 end
2072 end
2073 end
2074 end
2075
2076 function HtmlParser:add_comment()
2077 local token = self.current_token
2078 if token.type == "comment" then
2079 self:start_attribute()
2080 local parent = self:get_parent()
2081 local text = table.concat(token.data)
2082 local node = Comment:init(text, parent)
2083 parent:add_child(node)
2084 end
2085 end
2086
2087 function HtmlParser:add_doctype()
2088 local token = self.current_token
2089 if token.type == "doctype" then
2090 self:start_attribute()
2091 local parent = self:get_parent()
2092 local name = table.concat(token.name)
2093 local node = Doctype:init(name, parent)
2094 if #token.data > 0 then
2095 node:add_data(table.concat(token.data))
2096 end
2097 parent:add_child(node)
2098 end
2099 end
2100
2101 function HtmlParser:switch_insertion(name)
2102 self.insertion_mode = name
2103 end
2104
2105 function HtmlParser:current_node()
2106 return self:get_parent()
2107 end
2108
2109 function HtmlParser:adjusted_current_node()
2110 -- we don't support this feature yet
2111 -- https://html.spec.whatwg.org/multipage/parsing.html#adjusted-current-node
2112 return self:current_node()
2113 end
2114
2115
2116 local simple_modes = {
2117 body = "in_body",
2118 td = "in_cell",
2119 th = "in_cell",
2120 tr = "in_row",
2121 tbody = "in_table_body",
2122 thead = "in_table_body",
2123 tfoot = "in_table_body",
2124 caption = "in_caption",
2125 colgroup = "in_column_group",
2126 table = "in_table",
2127 template = "current_template_insertion_mode",
2128 frameset = "in_frameset"
2129 }
2130
2131 function HtmlParser:reset_insertion_mode()
2132 -- https://html.spec.whatwg.org/multipage/parsing.html#reset-the-insertion-mode-appropriately
2133 local last = false
2134 for position = #self.unfinished, 1, -1 do
2135 local node = self.unfinished[position]
2136 if position == 1 then last = true end
2137 local name = node.tag
2138 -- switch to insertion mode based on the current element name
2139 -- there is lot of other cases, but we support only basic ones
2140 -- we can support other insertion modes in the future
2141 if name == "head" and last == true then
2142 self:switch_insertion("in_head")
2143 return
2144 elseif name == "html" then
2145 if not self.head_pointer then
2146 self:switch_insertion("before_head")
2147 return
2148 else
2149 self:switch_insertion("after_head")
2150 return
2151 end
2152 elseif name == "select" then
2153 if not last then
2154 for x = position -1, 1, -1 do
2155 if x == 1 then break end
2156 local ancestor = self.unfinished[x]
2157 local ancestor_name = ancestor.tag
2158 if ancestor_name == "template" then
2159 break
2160 elseif ancestor_name == "table" then
2161 self:switch_insertion("in_select_in_table")
2162 return
2163 end
2164 end
2165 end
2166 self:switch_insertion("in_select")
2167 return
2168 elseif simple_modes[name] then
2169 self:switch_insertion(simple_modes[name])
2170 return
2171 elseif last == true then
2172 self:switch_insertion("in_body")
2173 return
2174 end
2175 end
2176 -- by default use in_body
2177 self:switch_insertion("in_body")
2178 end
2179
2180
2181 -- https://html.spec.whatwg.org/multipage/parsing.html#closing-elements-that-have-implied-end-tags
2182 function HtmlParser:generate_implied_endtags(included, ignored)
2183 local included = included or implied_endtags
2184 -- parser can pass list of elements that should be removed from the "included" list
2185 local ignored = ignored or {}
2186 for _, name in ipairs(ignored) do included[name] = nil end
2187 local current = self:current_node() or {}
2188 -- keep removing elements while they are in the "included" list
2189 if included[current.tag] then
2190 self:pop_element()
2191 self:generate_implied_endtags(included, ignored)
2192 end
2193 end
2194
2195 function HtmlParser:finish()
2196 -- tokenize without any real character
2197 self.codepoint = EOF
2198 self:tokenize(self.state)
2199 -- self:emit()
2200 self:add_text()
2201 -- close all unfinished elements
2202 if #self.unfinished == 0 then
2203 -- add implicit html tag
2204 self:start_tag("html")
2205 end
2206 while #self.unfinished > 0 do
2207 self:pop_element()
2208 end
2209 -- return root element
2210 return self.Document -- self:close_element()
2211 end
2212
2213 --
2214 M.Text = Text
2215 M.Element = Element
2216 M.HtmlParser = HtmlParser
2217 M.HtmlStates = HtmlStates -- table with functions for particular parser states
2218 M.self_closing_tags = self_closing_tags -- list of void elements
2219 M.search_entity_tree = search_entity_tree
2220 M.is_in_particular_scope = is_in_particular_scope
2221 M.is_in_list_item_scope = is_in_list_item_scope
2222 M.is_in_button_scope = is_in_button_scope
2223 M.is_in_table_scope = is_in_table_scope
2224 M.is_in_select_scope = is_in_select_scope
2225
2226 return M