Debian Codegraph @

html/lex.go

raw
1 // Package html is an HTML5 lexer following the specifications at http://www.w3.org/TR/html5/syntax.html.
2 package html
3
4 import (
5 "strconv"
6
7 "github.com/tdewolff/parse/v2"
8 )
9
10 // TokenType determines the type of token, eg. a number or a semicolon.
11 type TokenType uint32
12
13 // TokenType values.
14 const (
15 ErrorToken TokenType = iota // extra token when errors occur
16 CommentToken
17 DoctypeToken
18 StartTagToken
19 StartTagCloseToken
20 StartTagVoidToken
21 EndTagToken
22 AttributeToken
23 TextToken
24 SVGToken
25 MathToken
26 XMLToken
27 TemplateToken
28 )
29
30 // String returns the string representation of a TokenType.
31 func (tt TokenType) String() string {
32 switch tt {
33 case ErrorToken:
34 return "Error"
35 case CommentToken:
36 return "Comment"
37 case DoctypeToken:
38 return "Doctype"
39 case StartTagToken:
40 return "StartTag"
41 case StartTagCloseToken:
42 return "StartTagClose"
43 case StartTagVoidToken:
44 return "StartTagVoid"
45 case EndTagToken:
46 return "EndTag"
47 case AttributeToken:
48 return "Attribute"
49 case TextToken:
50 return "Text"
51 case SVGToken:
52 return "SVG"
53 case MathToken:
54 return "Math"
55 case XMLToken:
56 return "XML"
57 case TemplateToken:
58 return "Template"
59 }
60 return "Invalid(" + strconv.Itoa(int(tt)) + ")"
61 }
62
63 ////////////////////////////////////////////////////////////////
64
65 var GoTemplate = [2]string{"{{", "}}"}
66 var HandlebarsTemplate = [2]string{"{{", "}}"}
67 var MustacheTemplate = [2]string{"{{", "}}"}
68 var EJSTemplate = [2]string{"<%", "%>"}
69 var ASPTemplate = [2]string{"<%", "%>"}
70 var PHPTemplate = [2]string{"<?", "?>"}
71
72 // Lexer is the state for the lexer.
73 type Lexer struct {
74 r *parse.Input
75 tmplBegin []byte
76 tmplEnd []byte
77 err error
78
79 rawTag Hash
80 inTag bool
81
82 text []byte
83 attrVal []byte
84 hasTmpl bool
85 }
86
87 // NewLexer returns a new Lexer for a given io.Reader.
88 func NewLexer(r *parse.Input) *Lexer {
89 return &Lexer{
90 r: r,
91 }
92 }
93
94 func NewTemplateLexer(r *parse.Input, tmpl [2]string) *Lexer {
95 return &Lexer{
96 r: r,
97 tmplBegin: []byte(tmpl[0]),
98 tmplEnd: []byte(tmpl[1]),
99 }
100 }
101
102 // Err returns the error encountered during lexing, this is often io.EOF but also other errors can be returned.
103 func (l *Lexer) Err() error {
104 if l.err != nil {
105 return l.err
106 }
107 return l.r.Err()
108 }
109
110 // Text returns the textual representation of a token. This excludes delimiters and additional leading/trailing characters.
111 func (l *Lexer) Text() []byte {
112 return l.text
113 }
114
115 // AttrKey returns the attribute key when an AttributeToken was returned from Next.
116 func (l *Lexer) AttrKey() []byte {
117 return l.text
118 }
119
120 // AttrVal returns the attribute value when an AttributeToken was returned from Next.
121 func (l *Lexer) AttrVal() []byte {
122 return l.attrVal
123 }
124
125 // HasTemplate returns the true if the token value contains a template.
126 func (l *Lexer) HasTemplate() bool {
127 return l.hasTmpl
128 }
129
130 // Next returns the next Token. It returns ErrorToken when an error was encountered. Using Err() one can retrieve the error message.
131 func (l *Lexer) Next() (TokenType, []byte) {
132 l.text = nil
133 l.hasTmpl = false
134 var c byte
135 if l.inTag {
136 l.attrVal = nil
137 for { // before attribute name state
138 if c = l.r.Peek(0); c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' {
139 l.r.Move(1)
140 continue
141 }
142 break
143 }
144 if c == 0 && l.r.Err() != nil {
145 return ErrorToken, nil
146 } else if c != '>' && (c != '/' || l.r.Peek(1) != '>') {
147 return AttributeToken, l.shiftAttribute()
148 }
149 l.r.Skip()
150 l.inTag = false
151 if c == '/' {
152 l.r.Move(2)
153 return StartTagVoidToken, l.r.Shift()
154 }
155 l.r.Move(1)
156 return StartTagCloseToken, l.r.Shift()
157 }
158
159 if l.rawTag != 0 {
160 if rawText := l.shiftRawText(); 0 < len(rawText) {
161 l.text = rawText
162 l.rawTag = 0
163 return TextToken, rawText
164 }
165 l.rawTag = 0
166 }
167
168 for {
169 c = l.r.Peek(0)
170 if 0 < len(l.tmplBegin) && l.at(l.tmplBegin...) {
171 if 0 < l.r.Pos() {
172 l.text = l.r.Shift()
173 return TextToken, l.text
174 }
175 l.r.Move(len(l.tmplBegin))
176 l.moveTemplate()
177 l.hasTmpl = true
178 return TemplateToken, l.r.Shift()
179 } else if c == '<' {
180 c = l.r.Peek(1)
181 isEndTag := c == '/' && l.r.Peek(2) != '>' && (l.r.Peek(2) != 0 || l.r.PeekErr(2) == nil)
182 if !isEndTag && (c < 'a' || 'z' < c) && (c < 'A' || 'Z' < c) && c != '!' && c != '?' {
183 // not a tag
184 l.r.Move(1)
185 } else if 0 < l.r.Pos() {
186 // return currently buffered texttoken so that we can return tag next iteration
187 l.text = l.r.Shift()
188 return TextToken, l.text
189 } else if isEndTag {
190 l.r.Move(2)
191 // only endtags that are not followed by > or EOF arrive here
192 if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
193 return CommentToken, l.shiftBogusComment()
194 }
195 return EndTagToken, l.shiftEndTag()
196 } else if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' {
197 l.r.Move(1)
198 l.inTag = true
199 return l.shiftStartTag()
200 } else if c == '!' {
201 l.r.Move(2)
202 return l.readMarkup()
203 } else if c == '?' {
204 l.r.Move(1)
205 return CommentToken, l.shiftBogusComment()
206 }
207 } else if c == 0 && l.r.Err() != nil {
208 if 0 < l.r.Pos() {
209 l.text = l.r.Shift()
210 return TextToken, l.text
211 }
212 return ErrorToken, nil
213 } else {
214 l.r.Move(1)
215 }
216 }
217 }
218
219 ////////////////////////////////////////////////////////////////
220
221 // The following functions follow the specifications at https://html.spec.whatwg.org/multipage/parsing.html
222
223 func (l *Lexer) shiftRawText() []byte {
224 if l.rawTag == Plaintext {
225 for {
226 if l.r.Peek(0) == 0 && l.r.Err() != nil {
227 return l.r.Shift()
228 }
229 l.r.Move(1)
230 }
231 } else { // RCDATA, RAWTEXT and SCRIPT
232 for {
233 c := l.r.Peek(0)
234 if c == '<' {
235 if l.r.Peek(1) == '/' {
236 mark := l.r.Pos()
237 l.r.Move(2)
238 for {
239 if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
240 break
241 }
242 l.r.Move(1)
243 }
244 if h := ToHash(parse.ToLower(parse.Copy(l.r.Lexeme()[mark+2:]))); h == l.rawTag { // copy so that ToLower doesn't change the case of the underlying slice
245 l.r.Rewind(mark)
246 return l.r.Shift()
247 }
248 } else if l.rawTag == Script && l.r.Peek(1) == '!' && l.r.Peek(2) == '-' && l.r.Peek(3) == '-' {
249 l.r.Move(4)
250 inScript := false
251 for {
252 c := l.r.Peek(0)
253 if c == '-' && l.r.Peek(1) == '-' && l.r.Peek(2) == '>' {
254 l.r.Move(3)
255 break
256 } else if c == '<' {
257 isEnd := l.r.Peek(1) == '/'
258 if isEnd {
259 l.r.Move(2)
260 } else {
261 l.r.Move(1)
262 }
263 mark := l.r.Pos()
264 for {
265 if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
266 break
267 }
268 l.r.Move(1)
269 }
270 if h := ToHash(parse.ToLower(parse.Copy(l.r.Lexeme()[mark:]))); h == Script { // copy so that ToLower doesn't change the case of the underlying slice
271 if !isEnd {
272 inScript = true
273 } else {
274 if !inScript {
275 l.r.Rewind(mark - 2)
276 return l.r.Shift()
277 }
278 inScript = false
279 }
280 }
281 } else if c == 0 && l.r.Err() != nil {
282 return l.r.Shift()
283 } else {
284 l.r.Move(1)
285 }
286 }
287 } else {
288 l.r.Move(1)
289 }
290 } else if 0 < len(l.tmplBegin) && l.at(l.tmplBegin...) {
291 l.r.Move(len(l.tmplBegin))
292 l.moveTemplate()
293 l.hasTmpl = true
294 } else if c == 0 && l.r.Err() != nil {
295 return l.r.Shift()
296 } else {
297 l.r.Move(1)
298 }
299 }
300 }
301 }
302
303 func (l *Lexer) readMarkup() (TokenType, []byte) {
304 if l.at('-', '-') {
305 l.r.Move(2)
306 for {
307 if l.r.Peek(0) == 0 && l.r.Err() != nil {
308 l.text = l.r.Lexeme()[4:]
309 return CommentToken, l.r.Shift()
310 } else if l.at('-', '-', '>') {
311 l.text = l.r.Lexeme()[4:]
312 l.r.Move(3)
313 return CommentToken, l.r.Shift()
314 } else if l.at('-', '-', '!', '>') {
315 l.text = l.r.Lexeme()[4:]
316 l.r.Move(4)
317 return CommentToken, l.r.Shift()
318 }
319 l.r.Move(1)
320 }
321 } else if l.at('[', 'C', 'D', 'A', 'T', 'A', '[') {
322 l.r.Move(7)
323 for {
324 if l.r.Peek(0) == 0 && l.r.Err() != nil {
325 l.text = l.r.Lexeme()[9:]
326 return TextToken, l.r.Shift()
327 } else if l.at(']', ']', '>') {
328 l.text = l.r.Lexeme()[9:]
329 l.r.Move(3)
330 return TextToken, l.r.Shift()
331 }
332 l.r.Move(1)
333 }
334 } else {
335 if l.atCaseInsensitive('d', 'o', 'c', 't', 'y', 'p', 'e') {
336 l.r.Move(7)
337 if l.r.Peek(0) == ' ' {
338 l.r.Move(1)
339 }
340 for {
341 if c := l.r.Peek(0); c == '>' || c == 0 && l.r.Err() != nil {
342 l.text = l.r.Lexeme()[9:]
343 if c == '>' {
344 l.r.Move(1)
345 }
346 return DoctypeToken, l.r.Shift()
347 }
348 l.r.Move(1)
349 }
350 }
351 }
352 return CommentToken, l.shiftBogusComment()
353 }
354
355 func (l *Lexer) shiftBogusComment() []byte {
356 for {
357 c := l.r.Peek(0)
358 if c == '>' {
359 l.text = l.r.Lexeme()[2:]
360 l.r.Move(1)
361 return l.r.Shift()
362 } else if c == 0 && l.r.Err() != nil {
363 l.text = l.r.Lexeme()[2:]
364 return l.r.Shift()
365 }
366 l.r.Move(1)
367 }
368 }
369
370 func (l *Lexer) shiftStartTag() (TokenType, []byte) {
371 for {
372 // spec says only a-zA-Z0-9, but we're lenient here
373 if c := l.r.Peek(0); c == ' ' || c == '>' || c == '/' && l.r.Peek(1) == '>' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == 0 && l.r.Err() != nil || 0 < len(l.tmplBegin) && l.at(l.tmplBegin...) {
374 break
375 }
376 l.r.Move(1)
377 }
378 l.text = parse.ToLower(l.r.Lexeme()[1:])
379 if h := ToHash(l.text); h == Textarea || h == Title || h == Style || h == Xmp || h == Iframe || h == Script || h == Plaintext || h == Svg || h == Math || h == Xml {
380 if h == Svg || h == Math || h == Xml {
381 data := l.shiftXML(h)
382 if l.err != nil {
383 return ErrorToken, nil
384 }
385
386 l.inTag = false
387 if h == Svg {
388 return SVGToken, data
389 } else if h == Math {
390 return MathToken, data
391 }
392 return XMLToken, data
393 }
394 l.rawTag = h
395 }
396 return StartTagToken, l.r.Shift()
397 }
398
399 func (l *Lexer) shiftAttribute() []byte {
400 nameStart := l.r.Pos()
401 var c byte
402 if 0 < len(l.tmplBegin) {
403 for l.at(l.tmplBegin...) {
404 l.r.Move(len(l.tmplBegin))
405 l.moveTemplate()
406 l.hasTmpl = true
407 }
408 }
409 for { // attribute name state
410 if 0 < len(l.tmplBegin) && l.at(l.tmplBegin...) {
411 l.r.Move(len(l.tmplBegin))
412 l.moveTemplate()
413 l.hasTmpl = true
414 continue
415 } else if c = l.r.Peek(0); c == ' ' || c == '=' || c == '>' || c == '/' && l.r.Peek(1) == '>' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == 0 && l.r.Err() != nil {
416 break
417 }
418 l.r.Move(1)
419 }
420 nameEnd := l.r.Pos()
421 for { // after attribute name state
422 if c = l.r.Peek(0); c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' {
423 l.r.Move(1)
424 continue
425 }
426 break
427 }
428 nameHasTmpl := l.hasTmpl
429 if c == '=' {
430 l.r.Move(1)
431 for { // before attribute value state
432 if c = l.r.Peek(0); c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' {
433 l.r.Move(1)
434 continue
435 }
436 break
437 }
438 attrPos := l.r.Pos()
439 delim := c
440 if 0 < len(l.tmplBegin) && l.at(l.tmplBegin...) {
441 l.r.Move(len(l.tmplBegin))
442 l.moveTemplate()
443 for l.at(l.tmplBegin...) {
444 l.r.Move(len(l.tmplBegin))
445 l.moveTemplate()
446 }
447 l.hasTmpl = true
448 } else if delim == '"' || delim == '\'' { // attribute value single- and double-quoted state
449 l.r.Move(1)
450 for {
451 c := l.r.Peek(0)
452 if 0 < len(l.tmplBegin) && l.at(l.tmplBegin...) {
453 l.r.Move(len(l.tmplBegin))
454 l.moveTemplate()
455 for l.at(l.tmplBegin...) {
456 l.r.Move(len(l.tmplBegin))
457 l.moveTemplate()
458 }
459 l.hasTmpl = true
460 } else if c == delim {
461 l.r.Move(1)
462 break
463 } else if c == 0 && l.r.Err() != nil {
464 break
465 } else {
466 l.r.Move(1)
467 }
468 }
469 } else { // attribute value unquoted state
470 for {
471 if c := l.r.Peek(0); c == ' ' || c == '>' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == 0 && l.r.Err() != nil {
472 break
473 }
474 l.r.Move(1)
475 }
476 }
477 l.attrVal = l.r.Lexeme()[attrPos:]
478 } else {
479 l.r.Rewind(nameEnd)
480 l.attrVal = nil
481 }
482 if 0 < len(l.tmplBegin) {
483 for l.at(l.tmplBegin...) {
484 l.r.Move(len(l.tmplBegin))
485 l.moveTemplate()
486 l.hasTmpl = true
487 }
488 }
489 l.text = l.r.Lexeme()[nameStart:nameEnd]
490 if !nameHasTmpl {
491 l.text = parse.ToLower(l.text)
492 }
493 return l.r.Shift()
494 }
495
496 func (l *Lexer) shiftEndTag() []byte {
497 for {
498 c := l.r.Peek(0)
499 if c == '>' {
500 l.text = l.r.Lexeme()[2:]
501 l.r.Move(1)
502 break
503 } else if c == 0 && l.r.Err() != nil {
504 l.text = l.r.Lexeme()[2:]
505 break
506 }
507 l.r.Move(1)
508 }
509
510 end := len(l.text)
511 for end > 0 {
512 if c := l.text[end-1]; c == ' ' || c == '\t' || c == '\n' || c == '\r' {
513 end--
514 continue
515 }
516 break
517 }
518 l.text = l.text[:end]
519 return parse.ToLower(l.r.Shift())
520 }
521
522 // shiftXML parses the content of a svg or math tag according to the XML 1.1 specifications, including the tag itself.
523 // So far we have already parsed `<svg` or `<math`.
524 func (l *Lexer) shiftXML(rawTag Hash) []byte {
525 inQuote := false
526 for {
527 c := l.r.Peek(0)
528 if c == '"' {
529 inQuote = !inQuote
530 l.r.Move(1)
531 } else if c == '<' && !inQuote && l.r.Peek(1) == '/' {
532 mark := l.r.Pos()
533 l.r.Move(2)
534 for {
535 if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') {
536 break
537 }
538 l.r.Move(1)
539 }
540 if h := ToHash(parse.ToLower(parse.Copy(l.r.Lexeme()[mark+2:]))); h == rawTag { // copy so that ToLower doesn't change the case of the underlying slice
541 break
542 }
543 } else if c == 0 {
544 if l.r.Err() == nil {
545 l.err = parse.NewErrorLexer(l.r, "unexpected NULL character")
546 }
547 return l.r.Shift()
548 } else {
549 l.r.Move(1)
550 }
551 }
552
553 for {
554 c := l.r.Peek(0)
555 if c == '>' {
556 l.r.Move(1)
557 break
558 } else if c == 0 {
559 if l.r.Err() == nil {
560 l.err = parse.NewErrorLexer(l.r, "unexpected NULL character")
561 }
562 return l.r.Shift()
563 }
564 l.r.Move(1)
565 }
566 return l.r.Shift()
567 }
568
569 func (l *Lexer) moveTemplate() {
570 for {
571 if c := l.r.Peek(0); c == 0 && l.r.Err() != nil {
572 return
573 } else if l.at(l.tmplEnd...) {
574 l.r.Move(len(l.tmplEnd))
575 return
576 } else if c == '"' || c == '\'' {
577 l.r.Move(1)
578 escape := false
579 for {
580 if c2 := l.r.Peek(0); c2 == 0 && l.r.Err() != nil {
581 return
582 } else if !escape && c2 == c {
583 l.r.Move(1)
584 break
585 } else if c2 == '\\' {
586 escape = !escape
587 } else {
588 escape = false
589 }
590 l.r.Move(1)
591 }
592 } else {
593 l.r.Move(1)
594 }
595 }
596 }
597
598 ////////////////////////////////////////////////////////////////
599
600 func (l *Lexer) at(b ...byte) bool {
601 for i, c := range b {
602 if l.r.Peek(i) != c {
603 return false
604 }
605 }
606 return true
607 }
608
609 func (l *Lexer) atCaseInsensitive(b ...byte) bool {
610 for i, c := range b {
611 if l.r.Peek(i) != c && (l.r.Peek(i)+('a'-'A')) != c {
612 return false
613 }
614 }
615 return true
616 }