OILS / lazylex / html.py View on Github | oils.pub

996 lines, 513 significant
1#!/usr/bin/env python2
2"""
3lazylex/html.py - Low-Level HTML Processing.
4
5See lazylex/README.md for details.
6
7Conflicts between HTML5 and XML:
8
9- In XML, <source> is like any tag, and must be closed,
10- In HTML, <source> is a VOID tag, and must NOT be closedlike any tag, and must be closed,
11
12- In XML, <script> and <style> don't have special treatment
13- In HTML, they do
14
15- The header is different - <!DOCTYPE html> vs. <?xml version= ... ?>
16
17So do have a mode for <script> <style> and void tags? Upgrade HX8 into HTM8?
18"""
19from __future__ import print_function
20
21try:
22 from cStringIO import StringIO
23except ImportError:
24 from io import StringIO # python3
25import re
26import sys
27
28if sys.version_info.major == 2:
29 from typing import List, Tuple, Optional
30
31
32def log(msg, *args):
33 msg = msg % args
34 print(msg, file=sys.stderr)
35
36
37class LexError(Exception):
38 """
39 Examples of lex errors:
40
41 - Tok.Invalid, like <> or &&
42 - Unclosed <!-- <? <![CDATA[ <script> <style>
43 """
44
45 def __init__(self, s, start_pos):
46 self.s = s
47 self.start_pos = start_pos
48
49 def __str__(self):
50 return '(LexError %r)' % (self.s[self.start_pos:self.start_pos + 20])
51
52
53def FindLineNum(s, error_pos):
54 current_pos = 0
55 line_num = 1
56 while True:
57 newline_pos = s.find('\n', current_pos)
58 #log('current = %d, N %d, line %d', current_pos, newline_pos, line_num)
59
60 if newline_pos == -1: # this is the last line
61 return line_num
62 if newline_pos >= error_pos:
63 return line_num
64 line_num += 1
65 current_pos = newline_pos + 1
66
67
68class ParseError(Exception):
69 """
70 Examples of parse errors
71
72 - unbalanced tag structure
73 - ul_table.py errors
74 """
75
76 def __init__(self, msg, s=None, start_pos=-1):
77 self.msg = msg
78 self.s = s
79 self.start_pos = start_pos
80
81 def __str__(self):
82 if self.s is not None:
83 assert self.start_pos != -1, self.start_pos
84 snippet = (self.s[self.start_pos:self.start_pos + 20])
85
86 line_num = FindLineNum(self.s, self.start_pos)
87 else:
88 snippet = ''
89 line_num = -1
90 msg = 'line %d: %r %r' % (line_num, self.msg, snippet)
91 return msg
92
93
94class Output(object):
95 """Takes an underlying input buffer and an output file. Maintains a
96 position in the input buffer.
97
98 Print FROM the input or print new text to the output.
99 """
100
101 def __init__(self, s, f, left_pos=0, right_pos=-1):
102 self.s = s
103 self.f = f
104 self.pos = left_pos
105 self.right_pos = len(s) if right_pos == -1 else right_pos
106
107 def SkipTo(self, pos):
108 """Skip to a position."""
109 self.pos = pos
110
111 def PrintUntil(self, pos):
112 """Print until a position."""
113 piece = self.s[self.pos:pos]
114 self.f.write(piece)
115 self.pos = pos
116
117 def PrintTheRest(self):
118 """Print until the end of the string."""
119 self.PrintUntil(self.right_pos)
120
121 def Print(self, s):
122 """Print text to the underlying buffer."""
123 self.f.write(s)
124
125
126# HTML Tokens
127# CommentBegin, ProcessingBegin, CDataBegin are "pseudo-tokens", not visible
128TOKENS = 'Decl Comment CommentBegin Processing ProcessingBegin CData CDataBegin StartTag StartEndTag EndTag DecChar HexChar CharEntity RawData HtmlCData Invalid EndOfStream'.split(
129)
130
131
132class Tok(object):
133 """
134 Avoid lint errors by using these aliases
135 """
136 pass
137
138
139TOKEN_NAMES = [None] * len(TOKENS) # type: List[str]
140
141this_module = sys.modules[__name__]
142for i, tok_str in enumerate(TOKENS):
143 setattr(this_module, tok_str, i)
144 setattr(Tok, tok_str, i)
145 TOKEN_NAMES[i] = tok_str
146
147
148def TokenName(tok_id):
149 return TOKEN_NAMES[tok_id]
150
151
152def MakeLexer(rules):
153 return [(re.compile(pat, re.VERBOSE), i) for (pat, i) in rules]
154
155
156#
157# Eggex
158#
159# Tag = / ~['>']+ /
160
161# Is this valid? A single character?
162# Tag = / ~'>'* /
163
164# Maybe better: / [NOT '>']+/
165# capital letters not allowed there?
166#
167# But then this is confusing:
168# / [NOT ~digit]+/
169#
170# / [NOT digit] / is [^\d]
171# / ~digit / is \D
172#
173# Or maybe:
174#
175# / [~ digit]+ /
176# / [~ '>']+ /
177# / [NOT '>']+ /
178
179# End = / '</' Tag '>' /
180# StartEnd = / '<' Tag '/>' /
181# Start = / '<' Tag '>' /
182#
183# EntityRef = / '&' dot{* N} ';' /
184
185# Tag name, or attribute name
186# colon is used in XML
187
188# https://www.w3.org/TR/xml/#NT-Name
189# Hm there is a lot of unicode stuff. We are simplifying parsing
190
191_NAME = r'[a-zA-Z][a-zA-Z0-9:_\-]*' # must start with letter
192
193CHAR_LEX = [
194 # Characters
195 # https://www.w3.org/TR/xml/#sec-references
196 (r'&\# [0-9]+ ;', Tok.DecChar),
197 (r'&\# x[0-9a-fA-F]+ ;', Tok.HexChar),
198 (r'& %s ;' % _NAME, Tok.CharEntity),
199]
200
201LEXER = CHAR_LEX + [
202 (r'<!--', Tok.CommentBegin),
203
204 # Processing instruction are used for the XML header:
205 # <?xml version="1.0" encoding="UTF-8"?>
206 # They are technically XML-only, but in HTML5, they are another kind of
207 # comment:
208 #
209 # https://developer.mozilla.org/en-US/docs/Web/API/ProcessingInstruction
210 #
211 (r'<\?', Tok.ProcessingBegin),
212 # Not necessary in HTML5, but occurs in XML
213 (r'<!\[CDATA\[', Tok.CDataBegin), # <![CDATA[
214
215 # Markup declarations
216 # - In HTML5, there is only <!DOCTYPE html>
217 # - XML has 4 more declarations: <!ELEMENT ...> ATTLIST ENTITY NOTATION
218 # - these seem to be part of DTD
219 # - it's useful to skip these, and be able to parse the rest of the document
220 # - Note: < is allowed?
221 (r'<! [^>\x00]+ >', Tok.Decl),
222
223 # Tags
224 # Notes:
225 # - We look for a valid tag name, but we don't validate attributes.
226 # That's done in the tag lexer.
227 # - We don't allow leading whitespace
228 (r'</ (%s) >' % _NAME, Tok.EndTag),
229 # self-closing <br/> comes before StartTag
230 # could/should these be collapsed into one rule?
231 (r'< (%s) [^>\x00]* />' % _NAME, Tok.StartEndTag), # end </a>
232 (r'< (%s) [^>\x00]* >' % _NAME, Tok.StartTag), # start <a>
233
234 # HTML5 allows unescaped > in raw data, but < is not allowed.
235 # https://stackoverflow.com/questions/10462348/right-angle-bracket-in-html
236 #
237 # - My early blog has THREE errors when disallowing >
238 # - So do some .wwz files
239 (r'[^&<\x00]+', Tok.RawData),
240 (r'.', Tok.Invalid), # error!
241]
242
243# Old notes:
244#
245# Non-greedy matches are regular and can be matched in linear time
246# with RE2.
247#
248# https://news.ycombinator.com/item?id=27099798
249#
250# Maybe try combining all of these for speed.
251
252# . is any char except newline
253# https://re2c.org/manual/manual_c.html
254
255# Discarded options
256#(r'<!-- .*? -->', Tok.Comment),
257
258# Hack from Claude: \s\S instead of re.DOTALL. I don't like this
259#(r'<!-- [\s\S]*? -->', Tok.Comment),
260#(r'<!-- (?:.|[\n])*? -->', Tok.Comment),
261
262LEXER = MakeLexer(LEXER)
263
264
265class Lexer(object):
266
267 def __init__(self, s, left_pos=0, right_pos=-1, no_special_tags=False):
268 self.s = s
269 self.pos = left_pos
270 self.right_pos = len(s) if right_pos == -1 else right_pos
271 self.no_special_tags = no_special_tags
272
273 self.cache = {} # string -> compiled regex pattern object
274
275 # either </script> or </style> - we search until we see that
276 self.search_state = None # type: Optional[str]
277
278 # Position of tag name, if applicable
279 # - Set after you get a StartTag, EndTag, or StartEndTag
280 # - Unset on other tags
281 self.tag_pos_left = -1
282 self.tag_pos_right = -1
283
284 def _Peek(self):
285 # type: () -> Tuple[int, int]
286 """
287 Note: not using _Peek() now
288 """
289 if self.pos == self.right_pos:
290 return Tok.EndOfStream, self.pos
291
292 assert self.pos < self.right_pos, self.pos
293
294 if self.search_state is not None and not self.no_special_tags:
295 pos = self.s.find(self.search_state, self.pos)
296 if pos == -1:
297 # unterminated <script> or <style>
298 raise LexError(self.s, self.pos)
299 self.search_state = None
300 # beginning
301 return Tok.HtmlCData, pos
302
303 # Find the first match.
304 # Note: frontend/match.py uses _LongestMatch(), which is different!
305 # TODO: reconcile them. This lexer should be expressible in re2c.
306
307 for pat, tok_id in LEXER:
308 m = pat.match(self.s, self.pos)
309 if m:
310 if tok_id in (Tok.StartTag, Tok.EndTag, Tok.StartEndTag):
311 self.tag_pos_left = m.start(1)
312 self.tag_pos_right = m.end(1)
313 else:
314 # Reset state
315 self.tag_pos_left = -1
316 self.tag_pos_right = -1
317
318 if tok_id == Tok.CommentBegin:
319 pos = self.s.find('-->', self.pos)
320 if pos == -1:
321 # unterminated <!--
322 raise LexError(self.s, self.pos)
323 return Tok.Comment, pos + 3 # -->
324
325 if tok_id == Tok.ProcessingBegin:
326 pos = self.s.find('?>', self.pos)
327 if pos == -1:
328 # unterminated <?
329 raise LexError(self.s, self.pos)
330 return Tok.Processing, pos + 2 # ?>
331
332 if tok_id == Tok.CDataBegin:
333 pos = self.s.find(']]>', self.pos)
334 if pos == -1:
335 # unterminated <![CDATA[
336 raise LexError(self.s, self.pos)
337 return Tok.CData, pos + 3 # ]]>
338
339 if tok_id == Tok.StartTag:
340 if self.TagNameEquals('script'):
341 self.search_state = '</script>'
342 elif self.TagNameEquals('style'):
343 self.search_state = '</style>'
344
345 return tok_id, m.end()
346 else:
347 raise AssertionError('Tok.Invalid rule should have matched')
348
349 def TagNameEquals(self, expected):
350 # type: (str) -> bool
351 assert self.tag_pos_left != -1, self.tag_pos_left
352 assert self.tag_pos_right != -1, self.tag_pos_right
353
354 # TODO: In C++, this does not need an allocation
355 # TODO: conditionally lower() case here (maybe not in XML mode)
356 return expected == self.s[self.tag_pos_left:self.tag_pos_right]
357
358 def TagName(self):
359 # type: () -> None
360 assert self.tag_pos_left != -1, self.tag_pos_left
361 assert self.tag_pos_right != -1, self.tag_pos_right
362
363 # TODO: conditionally lower() case here (maybe not in XML mode)
364 return self.s[self.tag_pos_left:self.tag_pos_right]
365
366 def Read(self):
367 # type: () -> Tuple[int, int]
368 tok_id, end_pos = self._Peek()
369 self.pos = end_pos # advance
370 return tok_id, end_pos
371
372 def LookAhead(self, regex):
373 # Cache the regex compilation. This could also be LookAheadFor(THEAD)
374 # or something.
375 pat = self.cache.get(regex)
376 if pat is None:
377 pat = re.compile(regex)
378 self.cache[regex] = pat
379
380 m = pat.match(self.s, self.pos)
381 return m is not None
382
383
384def _Tokens(s, left_pos, right_pos):
385 """
386 Args:
387 s: string to parse
388 left_pos, right_pos: Optional span boundaries.
389 """
390 lx = Lexer(s, left_pos, right_pos)
391 while True:
392 tok_id, pos = lx.Read()
393 yield tok_id, pos
394 if tok_id == Tok.EndOfStream:
395 break
396
397
398def ValidTokens(s, left_pos=0, right_pos=-1):
399 """Wrapper around _Tokens to prevent callers from having to handle Invalid.
400
401 I'm not combining the two functions because I might want to do a
402 'yield' transformation on Tokens()? Exceptions might complicate the
403 issue?
404 """
405 pos = left_pos
406 for tok_id, end_pos in _Tokens(s, left_pos, right_pos):
407 if tok_id == Tok.Invalid:
408 raise LexError(s, pos)
409 yield tok_id, end_pos
410 pos = end_pos
411
412
413def ValidTokenList(s, no_special_tags=False):
414 """A wrapper that can be more easily translated to C++. Doesn't use iterators."""
415
416 start_pos = 0
417 tokens = []
418 lx = Lexer(s, no_special_tags=no_special_tags)
419 while True:
420 tok_id, end_pos = lx.Read()
421 tokens.append((tok_id, end_pos))
422 if tok_id == Tok.EndOfStream:
423 break
424 if tok_id == Tok.Invalid:
425 raise LexError(s, start_pos)
426 start_pos = end_pos
427 return tokens
428
429
430# Tag names:
431# Match <a or </a
432# Match <h2, but not <2h
433#
434# HTML 5 doesn't restrict tag names at all
435# https://html.spec.whatwg.org/#toc-syntax
436#
437# XML allows : - .
438# https://www.w3.org/TR/xml/#NT-NameChar
439
440# Namespaces for MathML, SVG
441# XLink, XML, XMLNS
442#
443# https://infra.spec.whatwg.org/#namespaces
444#
445# Allow - for td-attrs
446
447# Be very lenient - just no whitespace or special HTML chars
448# I don't think this is more lenient than HTML5, though we should check.
449_UNQUOTED_VALUE = r'''[^ \t\r\n<>&"'\x00]*'''
450
451# TODO: we don't need to capture the tag name here? That's done at the top
452# level
453_TAG_RE = re.compile(r'/? \s* (%s)' % _NAME, re.VERBOSE)
454
455_TAG_LAST_RE = re.compile(r'\s* /? >', re.VERBOSE)
456
457# To match href="foo"
458# Note: in HTML5 and XML, single quoted attributes are also valid
459
460# <button disabled> is standard usage
461
462_ATTR_RE = re.compile(
463 r'''
464\s+ # Leading whitespace is required
465(%s) # Attribute name
466(?: # Optional attribute value
467 \s* = \s*
468 (?:
469 " ([^>"\x00]*) " # double quoted value
470 | ' ([^>'\x00]*) ' # single quoted value
471 | (%s) # Attribute value
472 )
473)?
474''' % (_NAME, _UNQUOTED_VALUE), re.VERBOSE)
475
476TagName, AttrName, UnquotedValue, QuotedValue = range(4)
477
478
479class TagLexer(object):
480 """
481 Given a tag like <a href="..."> or <link type="..." />, the TagLexer
482 provides a few operations:
483
484 - What is the tag?
485 - Iterate through the attributes, giving (name, value_start_pos, value_end_pos)
486 """
487
488 def __init__(self, s):
489 self.s = s
490 self.start_pos = -1 # Invalid
491 self.end_pos = -1
492
493 def Reset(self, start_pos, end_pos):
494 """Reuse instances of this object."""
495 assert start_pos >= 0, start_pos
496 assert end_pos >= 0, end_pos
497
498 self.start_pos = start_pos
499 self.end_pos = end_pos
500
501 def TagString(self):
502 return self.s[self.start_pos:self.end_pos]
503
504 def TagName(self):
505 # First event
506 tok_id, start, end = next(self.Tokens())
507 return self.s[start:end]
508
509 def GetSpanForAttrValue(self, attr_name):
510 """
511 Used by oils_doc.py, for href shortcuts
512 """
513 # Algorithm: search for QuotedValue or UnquotedValue after AttrName
514 # TODO: Could also cache these
515
516 events = self.Tokens()
517 val = (-1, -1)
518 try:
519 while True:
520 tok_id, start, end = next(events)
521 if tok_id == AttrName:
522 name = self.s[start:end]
523 if name == attr_name:
524 # The value should come next
525 tok_id, start, end = next(events)
526 if tok_id in (QuotedValue, UnquotedValue):
527 # Note: quoted values may have &amp;
528 # We would need ANOTHER lexer to unescape them.
529 # Right now help_gen.py and oils_doc.py
530 val = start, end
531 break
532
533 except StopIteration:
534 pass
535 return val
536
537 def GetAttrRaw(self, attr_name):
538 """
539 Return the value, which may be UNESCAPED.
540 """
541 start, end = self.GetSpanForAttrValue(attr_name)
542 if start == -1:
543 return None
544 return self.s[start:end]
545
546 def AllAttrsRawSlice(self):
547 """
548 Get a list of pairs [('class', 3, 5), ('href', 9, 12)]
549 """
550 slices = []
551 events = self.Tokens()
552 try:
553 while True:
554 tok_id, start, end = next(events)
555 if tok_id == AttrName:
556 name = self.s[start:end]
557
558 # The value should come next
559 tok_id, start, end = next(events)
560 if tok_id in (QuotedValue, UnquotedValue):
561 # Note: quoted values may have &amp;
562 # We would need ANOTHER lexer to unescape them, but we
563 # don't need that for ul-table
564 slices.append((name, start, end))
565 else:
566 # TODO: no attribute? <button disabled>? Make it equivalent
567 # to the empty string? Or None?
568 pass
569 #slices.append((name, start, end))
570 except StopIteration:
571 pass
572 return slices
573
574 def AllAttrsRaw(self):
575 """
576 Get a list of pairs [('class', 'foo'), ('href', '?foo=1&amp;bar=2')]
577
578 The quoted values may be escaped. We would need another lexer to
579 unescape them.
580 """
581 slices = self.AllAttrsRawSlice()
582 pairs = []
583 for name, start, end in slices:
584 pairs.append((name, self.s[start:end]))
585 return pairs
586
587 def Tokens(self):
588 """
589 Yields a sequence of tokens: Tag (AttrName AttrValue?)*
590
591 Where each Token is (Type, start_pos, end_pos)
592
593 Note that start and end are NOT redundant! We skip over some unwanted
594 characters.
595 """
596 m = _TAG_RE.match(self.s, self.start_pos + 1)
597 if not m:
598 raise RuntimeError("Couldn't find HTML tag in %r" %
599 self.TagString())
600 yield TagName, m.start(1), m.end(1)
601
602 pos = m.end(0)
603 #log('POS %d', pos)
604
605 while True:
606 # don't search past the end
607 m = _ATTR_RE.match(self.s, pos, self.end_pos)
608 if not m:
609 #log('BREAK pos %d', pos)
610 break
611 #log('AttrName %r', m.group(1))
612
613 yield AttrName, m.start(1), m.end(1)
614
615 if m.group(2) is not None:
616 # double quoted
617 yield QuotedValue, m.start(2), m.end(2)
618 elif m.group(3) is not None:
619 # single quoted - TODO: could have different token types
620 yield QuotedValue, m.start(3), m.end(3)
621 elif m.group(4) is not None:
622 yield UnquotedValue, m.start(4), m.end(4)
623
624 # Skip past the "
625 pos = m.end(0)
626
627 #log('TOK %r', self.s)
628
629 m = _TAG_LAST_RE.match(self.s, pos)
630 #log('_TAG_LAST_RE match %r', self.s[pos:])
631 if not m:
632 # Extra data at end of tag. TODO: add messages for all these.
633 raise LexError(self.s, pos)
634
635
636# This is similar but not identical to
637# " ([^>"\x00]*) " # double quoted value
638# | ' ([^>'\x00]*) ' # single quoted value
639#
640# Note: for unquoted values, & isn't allowed, and thus &amp; and &#99; and
641# &#x99; are not allowed. We could relax that?
642ATTR_VALUE_LEXER = CHAR_LEX + [
643 (r'[^>&\x00]+', Tok.RawData),
644 (r'.', Tok.Invalid),
645]
646
647ATTR_VALUE_LEXER = MakeLexer(ATTR_VALUE_LEXER)
648
649
650class AttrValueLexer(object):
651 """
652 <a href="foo=99&amp;bar">
653 <a href='foo=99&amp;bar'>
654 <a href=unquoted>
655 """
656
657 def __init__(self, s):
658 self.s = s
659 self.start_pos = -1 # Invalid
660 self.end_pos = -1
661
662 def Reset(self, start_pos, end_pos):
663 """Reuse instances of this object."""
664 assert start_pos >= 0, start_pos
665 assert end_pos >= 0, end_pos
666
667 self.start_pos = start_pos
668 self.end_pos = end_pos
669
670 def NumTokens(self):
671 num_tokens = 0
672 pos = self.start_pos
673 for tok_id, end_pos in self.Tokens():
674 if tok_id == Tok.Invalid:
675 raise LexError(self.s, pos)
676 pos = end_pos
677 #log('pos %d', pos)
678 num_tokens += 1
679 return num_tokens
680
681 def Tokens(self):
682 pos = self.start_pos
683 while pos < self.end_pos:
684 # Find the first match, like above.
685 # Note: frontend/match.py uses _LongestMatch(), which is different!
686 # TODO: reconcile them. This lexer should be expressible in re2c.
687 for pat, tok_id in ATTR_VALUE_LEXER:
688 m = pat.match(self.s, pos)
689 if m:
690 if 0:
691 tok_str = m.group(0)
692 log('token = %r', tok_str)
693
694 end_pos = m.end(0)
695 yield tok_id, end_pos
696 pos = end_pos
697 break
698 else:
699 raise AssertionError('Tok.Invalid rule should have matched')
700
701
702def ReadUntilStartTag(it, tag_lexer, tag_name):
703 """Find the next <foo>, returning its (start, end) positions
704
705 Raise ParseError if it's not found.
706
707 tag_lexer is RESET.
708 """
709 pos = 0
710 while True:
711 try:
712 tok_id, end_pos = next(it)
713 except StopIteration:
714 break
715 tag_lexer.Reset(pos, end_pos)
716 if tok_id == Tok.StartTag and tag_lexer.TagName() == tag_name:
717 return pos, end_pos
718
719 pos = end_pos
720
721 raise ParseError('No start tag %r' % tag_name)
722
723
724def ReadUntilEndTag(it, tag_lexer, tag_name):
725 """Find the next </foo>, returning its (start, end) position
726
727 Raise ParseError if it's not found.
728
729 tag_lexer is RESET.
730 """
731 pos = 0
732 while True:
733 try:
734 tok_id, end_pos = next(it)
735 except StopIteration:
736 break
737 tag_lexer.Reset(pos, end_pos)
738 if tok_id == Tok.EndTag and tag_lexer.TagName() == tag_name:
739 return pos, end_pos
740
741 pos = end_pos
742
743 raise ParseError('No end tag %r' % tag_name)
744
745
746CHAR_ENTITY = {
747 'amp': '&',
748 'lt': '<',
749 'gt': '>',
750 'quot': '"',
751}
752
753
754def ToText(s, left_pos=0, right_pos=-1):
755 """Given HTML, return text by unquoting &gt; and &lt; etc.
756
757 Used by:
758 doctools/oils_doc.py: PygmentsPlugin
759 doctools/help_gen.py: HelpIndexCards
760
761 In the latter case, we cold process some tags, like:
762
763 - Blue Link (not clickable, but still useful)
764 - Red X
765
766 That should be html.ToAnsi.
767 """
768 f = StringIO()
769 out = Output(s, f, left_pos, right_pos)
770
771 pos = left_pos
772 for tok_id, end_pos in ValidTokens(s, left_pos, right_pos):
773 if tok_id == Tok.RawData:
774 out.SkipTo(pos)
775 out.PrintUntil(end_pos)
776
777 elif tok_id == Tok.CharEntity: # &amp;
778
779 entity = s[pos + 1:end_pos - 1]
780
781 out.SkipTo(pos)
782 out.Print(CHAR_ENTITY[entity])
783 out.SkipTo(end_pos)
784
785 # Not handling these yet
786 elif tok_id == Tok.HexChar:
787 raise AssertionError('Hex Char %r' % s[pos:pos + 20])
788
789 elif tok_id == Tok.DecChar:
790 raise AssertionError('Dec Char %r' % s[pos:pos + 20])
791
792 pos = end_pos
793
794 out.PrintTheRest()
795 return f.getvalue()
796
797
798# https://developer.mozilla.org/en-US/docs/Glossary/Void_element
799VOID_ELEMENTS = [
800 'area',
801 'base',
802 'br',
803 'col',
804 'embed',
805 'hr',
806 'img',
807 'input',
808 'link',
809 'meta',
810 'param',
811 'source',
812 'track',
813 'wbr',
814]
815
816LEX_ATTRS = 1 << 1
817LEX_QUOTED_VALUES = 1 << 2 # href="?x=42&amp;y=99"
818NO_SPECIAL_TAGS = 1 << 3 # <script> <style>, VOID tags, etc.
819BALANCED_TAGS = 1 << 4 # are tags balanced?
820
821
822def Validate(contents, flags, counters):
823 # type: (str, int, Counters) -> None
824
825 tag_lexer = TagLexer(contents)
826 val_lexer = AttrValueLexer(contents)
827
828 no_special_tags = bool(flags & NO_SPECIAL_TAGS)
829 lx = Lexer(contents, no_special_tags=no_special_tags)
830 tokens = []
831 start_pos = 0
832 tag_stack = []
833 while True:
834 tok_id, end_pos = lx.Read()
835 #log('TOP %s %r', TokenName(tok_id), contents[start_pos:end_pos])
836
837 if tok_id == Tok.Invalid:
838 raise LexError(contents, start_pos)
839 if tok_id == Tok.EndOfStream:
840 break
841
842 tokens.append((tok_id, end_pos))
843
844 if tok_id == Tok.StartEndTag:
845 counters.num_start_end_tags += 1
846
847 tag_lexer.Reset(start_pos, end_pos)
848 all_attrs = tag_lexer.AllAttrsRawSlice()
849 counters.num_attrs += len(all_attrs)
850 for name, val_start, val_end in all_attrs:
851 val_lexer.Reset(val_start, val_end)
852 counters.num_val_tokens += val_lexer.NumTokens()
853
854 counters.debug_attrs.extend(all_attrs)
855
856 elif tok_id == Tok.StartTag:
857 counters.num_start_tags += 1
858
859 tag_lexer.Reset(start_pos, end_pos)
860 all_attrs = tag_lexer.AllAttrsRawSlice()
861 counters.num_attrs += len(all_attrs)
862 for name, val_start, val_end in all_attrs:
863 val_lexer.Reset(val_start, val_end)
864 counters.num_val_tokens += val_lexer.NumTokens()
865
866 counters.debug_attrs.extend(all_attrs)
867
868 if flags & BALANCED_TAGS:
869 tag_name = lx.TagName()
870 if flags & NO_SPECIAL_TAGS:
871 tag_stack.append(tag_name)
872 else:
873 # e.g. <meta> is considered self-closing, like <meta/>
874 if tag_name not in VOID_ELEMENTS:
875 tag_stack.append(tag_name)
876
877 counters.max_tag_stack = max(counters.max_tag_stack,
878 len(tag_stack))
879 elif tok_id == Tok.EndTag:
880 if flags & BALANCED_TAGS:
881 try:
882 expected = tag_stack.pop()
883 except IndexError:
884 raise ParseError('Tag stack empty',
885 s=contents,
886 start_pos=start_pos)
887
888 actual = lx.TagName()
889 if expected != actual:
890 raise ParseError(
891 'Got unexpected closing tag %r; opening tag was %r' %
892 (contents[start_pos:end_pos], expected),
893 s=contents,
894 start_pos=start_pos)
895
896 start_pos = end_pos
897
898 if len(tag_stack) != 0:
899 raise ParseError('Missing closing tags at end of doc: %s' %
900 ' '.join(tag_stack),
901 s=contents,
902 start_pos=start_pos)
903
904 counters.num_tokens += len(tokens)
905
906
907class Counters(object):
908
909 def __init__(self):
910 self.num_tokens = 0
911 self.num_start_tags = 0
912 self.num_start_end_tags = 0
913 self.num_attrs = 0
914 self.max_tag_stack = 0
915 self.num_val_tokens = 0
916
917 self.debug_attrs = []
918
919
920def main(argv):
921 action = argv[1]
922
923 if action == 'tokens':
924 contents = sys.stdin.read()
925
926 lx = Lexer(contents)
927 start_pos = 0
928 while True:
929 tok_id, end_pos = lx.Read()
930 if tok_id == Tok.Invalid:
931 raise LexError(contents, start_pos)
932 if tok_id == Tok.EndOfStream:
933 break
934
935 frag = contents[start_pos:end_pos]
936 log('%d %s %r', end_pos, TokenName(tok_id), frag)
937 start_pos = end_pos
938
939 return 0
940
941 elif action in ('lex-htm8', 'parse-htm8', 'parse-xml'):
942
943 errors = []
944 counters = Counters()
945
946 flags = LEX_ATTRS | LEX_QUOTED_VALUES
947 if action.startswith('parse-'):
948 flags |= BALANCED_TAGS
949 if action == 'parse-xml':
950 flags |= NO_SPECIAL_TAGS
951
952 i = 0
953 for line in sys.stdin:
954 filename = line.strip()
955 with open(filename) as f:
956 contents = f.read()
957
958 try:
959 Validate(contents, flags, counters)
960 except LexError as e:
961 log('Lex error in %r: %s', filename, e)
962 errors.append((filename, e))
963 except ParseError as e:
964 log('Parse error in %r: %s', filename, e)
965 errors.append((filename, e))
966 i += 1
967
968 log('')
969 log('%10d tokens', counters.num_tokens)
970 log('%10d start/end tags', counters.num_start_end_tags)
971 log('%10d start tags', counters.num_start_tags)
972 log('%10d attrs', counters.num_attrs)
973 log('%10d max tag stack depth', counters.max_tag_stack)
974 log('%10d attr val tokens', counters.num_val_tokens)
975 log('%10d errors', len(errors))
976 if len(errors):
977 return 1
978 return 0
979
980 elif action == 'todo':
981 # Other algorithms:
982 #
983 # - select first subtree with given ID
984 # - this requires understanding the void tags I suppose
985 # - select all subtrees that have a class
986 # - materialize DOM
987
988 # Safe-HTM8? This is a filter
989 return 0
990
991 else:
992 raise RuntimeError('Invalid action %r' % action)
993
994
995if __name__ == '__main__':
996 sys.exit(main(sys.argv))