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

881 lines, 448 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
193LEXER = [
194 (r'<!--', Tok.CommentBegin),
195
196 # Processing instruction are used for the XML header:
197 # <?xml version="1.0" encoding="UTF-8"?>
198 # They are technically XML-only, but in HTML5, they are another kind of
199 # comment:
200 #
201 # https://developer.mozilla.org/en-US/docs/Web/API/ProcessingInstruction
202 #
203 (r'<\?', Tok.ProcessingBegin),
204 # Not necessary in HTML5, but occurs in XML
205 (r'<!\[CDATA\[', Tok.CDataBegin), # <![CDATA[
206
207 # Markup declarations
208 # - In HTML5, there is only <!DOCTYPE html>
209 # - XML has 4 more declarations: <!ELEMENT ...> ATTLIST ENTITY NOTATION
210 # - these seem to be part of DTD
211 # - it's useful to skip these, and be able to parse the rest of the document
212 # - Note: < is allowed?
213 (r'<! [^>]+ >', Tok.Decl),
214
215 # Tags
216 # Notes:
217 # - We look for a valid tag name, but we don't validate attributes.
218 # That's done in the tag lexer.
219 # - We don't allow leading whitespace
220 (r'</ (%s) >' % _NAME, Tok.EndTag),
221 # self-closing <br/> comes before StartTag
222 # could/should these be collapsed into one rule?
223 (r'< (%s) [^>]* />' % _NAME, Tok.StartEndTag), # end </a>
224 (r'< (%s) [^>]* >' % _NAME, Tok.StartTag), # start <a>
225
226 # Characters
227 # https://www.w3.org/TR/xml/#sec-references
228 (r'&\# [0-9]+ ;', Tok.DecChar),
229 (r'&\# x[0-9a-fA-F]+ ;', Tok.HexChar),
230 (r'& %s ;' % _NAME, Tok.CharEntity),
231
232 # HTML5 allows unescaped > in raw data, but < is not allowed.
233 # https://stackoverflow.com/questions/10462348/right-angle-bracket-in-html
234 #
235 # - My early blog has THREE errors when disallowing >
236 # - So do some .wwz files
237 (r'[^&<]+', Tok.RawData),
238 (r'.', Tok.Invalid), # error!
239]
240
241# Old notes:
242#
243# Non-greedy matches are regular and can be matched in linear time
244# with RE2.
245#
246# https://news.ycombinator.com/item?id=27099798
247#
248# Maybe try combining all of these for speed.
249
250# . is any char except newline
251# https://re2c.org/manual/manual_c.html
252
253# Discarded options
254#(r'<!-- .*? -->', Tok.Comment),
255
256# Hack from Claude: \s\S instead of re.DOTALL. I don't like this
257#(r'<!-- [\s\S]*? -->', Tok.Comment),
258#(r'<!-- (?:.|[\n])*? -->', Tok.Comment),
259
260LEXER = MakeLexer(LEXER)
261
262
263class Lexer(object):
264
265 def __init__(self, s, left_pos=0, right_pos=-1, no_special_tags=False):
266 self.s = s
267 self.pos = left_pos
268 self.right_pos = len(s) if right_pos == -1 else right_pos
269 self.no_special_tags = no_special_tags
270
271 self.cache = {} # string -> compiled regex pattern object
272
273 # either </script> or </style> - we search until we see that
274 self.search_state = None # type: Optional[str]
275
276 # Position of tag name, if applicable
277 # - Set after you get a StartTag, EndTag, or StartEndTag
278 # - Unset on other tags
279 self.tag_pos_left = -1
280 self.tag_pos_right = -1
281
282 def _Peek(self):
283 # type: () -> Tuple[int, int]
284 """
285 Note: not using _Peek() now
286 """
287 if self.pos == self.right_pos:
288 return Tok.EndOfStream, self.pos
289
290 assert self.pos < self.right_pos, self.pos
291
292 if self.search_state is not None and not self.no_special_tags:
293 pos = self.s.find(self.search_state, self.pos)
294 if pos == -1:
295 # unterminated <script> or <style>
296 raise LexError(self.s, self.pos)
297 self.search_state = None
298 # beginning
299 return Tok.HtmlCData, pos
300
301 # Find the first match.
302 # Note: frontend/match.py uses _LongestMatch(), which is different!
303 # TODO: reconcile them. This lexer should be expressible in re2c.
304
305 for pat, tok_id in LEXER:
306 m = pat.match(self.s, self.pos)
307 if m:
308 if tok_id in (Tok.StartTag, Tok.EndTag, Tok.StartEndTag):
309 self.tag_pos_left = m.start(1)
310 self.tag_pos_right = m.end(1)
311 else:
312 # Reset state
313 self.tag_pos_left = -1
314 self.tag_pos_right = -1
315
316 if tok_id == Tok.CommentBegin:
317 pos = self.s.find('-->', self.pos)
318 if pos == -1:
319 # unterminated <!--
320 raise LexError(self.s, self.pos)
321 return Tok.Comment, pos + 3 # -->
322
323 if tok_id == Tok.ProcessingBegin:
324 pos = self.s.find('?>', self.pos)
325 if pos == -1:
326 # unterminated <?
327 raise LexError(self.s, self.pos)
328 return Tok.Processing, pos + 2 # ?>
329
330 if tok_id == Tok.CDataBegin:
331 pos = self.s.find(']]>', self.pos)
332 if pos == -1:
333 # unterminated <![CDATA[
334 raise LexError(self.s, self.pos)
335 return Tok.CData, pos + 3 # ]]>
336
337 if tok_id == Tok.StartTag:
338 if self.TagNameEquals('script'):
339 self.search_state = '</script>'
340 elif self.TagNameEquals('style'):
341 self.search_state = '</style>'
342
343 return tok_id, m.end()
344 else:
345 raise AssertionError('Tok.Invalid rule should have matched')
346
347 def TagNameEquals(self, expected):
348 # type: (str) -> bool
349 assert self.tag_pos_left != -1, self.tag_pos_left
350 assert self.tag_pos_right != -1, self.tag_pos_right
351
352 # TODO: In C++, this does not need an allocation
353 # TODO: conditionally lower() case here (maybe not in XML mode)
354 return expected == self.s[self.tag_pos_left:self.tag_pos_right]
355
356 def TagName(self):
357 # type: () -> None
358 assert self.tag_pos_left != -1, self.tag_pos_left
359 assert self.tag_pos_right != -1, self.tag_pos_right
360
361 # TODO: conditionally lower() case here (maybe not in XML mode)
362 return self.s[self.tag_pos_left:self.tag_pos_right]
363
364 def Read(self):
365 # type: () -> Tuple[int, int]
366 tok_id, end_pos = self._Peek()
367 self.pos = end_pos # advance
368 return tok_id, end_pos
369
370 def LookAhead(self, regex):
371 # Cache the regex compilation. This could also be LookAheadFor(THEAD)
372 # or something.
373 pat = self.cache.get(regex)
374 if pat is None:
375 pat = re.compile(regex)
376 self.cache[regex] = pat
377
378 m = pat.match(self.s, self.pos)
379 return m is not None
380
381
382def _Tokens(s, left_pos, right_pos):
383 """
384 Args:
385 s: string to parse
386 left_pos, right_pos: Optional span boundaries.
387 """
388 lx = Lexer(s, left_pos, right_pos)
389 while True:
390 tok_id, pos = lx.Read()
391 yield tok_id, pos
392 if tok_id == Tok.EndOfStream:
393 break
394
395
396def ValidTokens(s, left_pos=0, right_pos=-1):
397 """Wrapper around _Tokens to prevent callers from having to handle Invalid.
398
399 I'm not combining the two functions because I might want to do a
400 'yield' transformation on Tokens()? Exceptions might complicate the
401 issue?
402 """
403 pos = left_pos
404 for tok_id, end_pos in _Tokens(s, left_pos, right_pos):
405 if tok_id == Tok.Invalid:
406 raise LexError(s, pos)
407 yield tok_id, end_pos
408 pos = end_pos
409
410
411def ValidTokenList(s, no_special_tags=False):
412 """A wrapper that can be more easily translated to C++. Doesn't use iterators."""
413
414 start_pos = 0
415 tokens = []
416 lx = Lexer(s, no_special_tags=no_special_tags)
417 while True:
418 tok_id, end_pos = lx.Read()
419 tokens.append((tok_id, end_pos))
420 if tok_id == Tok.EndOfStream:
421 break
422 if tok_id == Tok.Invalid:
423 raise LexError(s, start_pos)
424 start_pos = end_pos
425 return tokens
426
427
428# Tag names:
429# Match <a or </a
430# Match <h2, but not <2h
431#
432# HTML 5 doesn't restrict tag names at all
433# https://html.spec.whatwg.org/#toc-syntax
434#
435# XML allows : - .
436# https://www.w3.org/TR/xml/#NT-NameChar
437
438# Namespaces for MathML, SVG
439# XLink, XML, XMLNS
440#
441# https://infra.spec.whatwg.org/#namespaces
442#
443# Allow - for td-attrs
444
445# allow underscore/hyphen. what about colons, like _NAME?
446# what about href=$foo ?
447_UNQUOTED_VALUE = r'[a-zA-Z0-9_\-]+'
448
449# TODO: we don't need to capture the tag name here? That's done at the top
450# level
451_TAG_RE = re.compile(r'/? \s* (%s)' % _NAME, re.VERBOSE)
452
453# To match href="foo"
454# Note: in HTML5 and XML, single quoted attributes are also valid
455
456_ATTR_RE = re.compile(
457 r'''
458\s+ # Leading whitespace is required
459(%s) # Attribute name
460(?: # Optional attribute value
461 \s* = \s*
462 (?:
463 " ([^>"]*) " # double quoted value
464 | (%s) # Attribute value
465 )
466)?
467''' % (_NAME, _UNQUOTED_VALUE), re.VERBOSE)
468
469TagName, AttrName, UnquotedValue, QuotedValue = range(4)
470
471
472class TagLexer(object):
473 """
474 Given a tag like <a href="..."> or <link type="..." />, the TagLexer
475 provides a few operations:
476
477 - What is the tag?
478 - Iterate through the attributes, giving (name, value_start_pos, value_end_pos)
479 """
480
481 def __init__(self, s):
482 self.s = s
483 self.start_pos = -1 # Invalid
484 self.end_pos = -1
485
486 def Reset(self, start_pos, end_pos):
487 """Reuse instances of this object."""
488 self.start_pos = start_pos
489 self.end_pos = end_pos
490
491 def TagString(self):
492 return self.s[self.start_pos:self.end_pos]
493
494 def TagName(self):
495 # First event
496 tok_id, start, end = next(self.Tokens())
497 return self.s[start:end]
498
499 def GetSpanForAttrValue(self, attr_name):
500 """
501 Used by oils_doc.py, for href shortcuts
502 """
503 # Algorithm: search for QuotedValue or UnquotedValue after AttrName
504 # TODO: Could also cache these
505
506 events = self.Tokens()
507 val = (-1, -1)
508 try:
509 while True:
510 tok_id, start, end = next(events)
511 if tok_id == AttrName:
512 name = self.s[start:end]
513 if name == attr_name:
514 # The value should come next
515 tok_id, start, end = next(events)
516 if tok_id in (QuotedValue, UnquotedValue):
517 # Note: quoted values may have &amp;
518 # We would need ANOTHER lexer to unescape them.
519 # Right now help_gen.py and oils_doc.py
520 val = start, end
521 break
522
523 except StopIteration:
524 pass
525 return val
526
527 def GetAttrRaw(self, attr_name):
528 """
529 Return the value, which may be UNESCAPED.
530 """
531 start, end = self.GetSpanForAttrValue(attr_name)
532 if start == -1:
533 return None
534 return self.s[start:end]
535
536 def AllAttrsRaw(self):
537 """
538 Get a list of pairs [('class', 'foo'), ('href', '?foo=1&amp;bar=2')]
539
540 The quoted values may be escaped. We would need another lexer to
541 unescape them.
542 """
543 pairs = []
544 events = self.Tokens()
545 try:
546 while True:
547 tok_id, start, end = next(events)
548 if tok_id == AttrName:
549 name = self.s[start:end]
550
551 # The value should come next
552 tok_id, start, end = next(events)
553 if tok_id in (QuotedValue, UnquotedValue):
554 # Note: quoted values may have &amp;
555 # We would need ANOTHER lexer to unescape them, but we
556 # don't need that for ul-table
557
558 val = self.s[start:end]
559 pairs.append((name, val))
560 except StopIteration:
561 pass
562 return pairs
563
564 def Tokens(self):
565 """
566 Yields a sequence of tokens: Tag (AttrName AttrValue?)*
567
568 Where each Token is (Type, start_pos, end_pos)
569
570 Note that start and end are NOT redundant! We skip over some unwanted
571 characters.
572 """
573 m = _TAG_RE.match(self.s, self.start_pos + 1)
574 if not m:
575 raise RuntimeError("Couldn't find HTML tag in %r" %
576 self.TagString())
577 yield TagName, m.start(1), m.end(1)
578
579 pos = m.end(0)
580
581 while True:
582 # don't search past the end
583 m = _ATTR_RE.match(self.s, pos, self.end_pos)
584 if not m:
585 # A validating parser would check that > or /> is next -- there's no junk
586 break
587
588 yield AttrName, m.start(1), m.end(1)
589
590 # Quoted is group 2, unquoted is group 3.
591 if m.group(2) is not None:
592 yield QuotedValue, m.start(2), m.end(2)
593 elif m.group(3) is not None:
594 yield UnquotedValue, m.start(3), m.end(3)
595
596 # Skip past the "
597 pos = m.end(0)
598
599
600def ReadUntilStartTag(it, tag_lexer, tag_name):
601 """Find the next <foo>, returning its (start, end) positions
602
603 Raise ParseError if it's not found.
604
605 tag_lexer is RESET.
606 """
607 pos = 0
608 while True:
609 try:
610 tok_id, end_pos = next(it)
611 except StopIteration:
612 break
613 tag_lexer.Reset(pos, end_pos)
614 if tok_id == Tok.StartTag and tag_lexer.TagName() == tag_name:
615 return pos, end_pos
616
617 pos = end_pos
618
619 raise ParseError('No start tag %r' % tag_name)
620
621
622def ReadUntilEndTag(it, tag_lexer, tag_name):
623 """Find the next </foo>, returning its (start, end) position
624
625 Raise ParseError if it's not found.
626
627 tag_lexer is RESET.
628 """
629 pos = 0
630 while True:
631 try:
632 tok_id, end_pos = next(it)
633 except StopIteration:
634 break
635 tag_lexer.Reset(pos, end_pos)
636 if tok_id == Tok.EndTag and tag_lexer.TagName() == tag_name:
637 return pos, end_pos
638
639 pos = end_pos
640
641 raise ParseError('No end tag %r' % tag_name)
642
643
644CHAR_ENTITY = {
645 'amp': '&',
646 'lt': '<',
647 'gt': '>',
648 'quot': '"',
649}
650
651
652def ToText(s, left_pos=0, right_pos=-1):
653 """Given HTML, return text by unquoting &gt; and &lt; etc.
654
655 Used by:
656 doctools/oils_doc.py: PygmentsPlugin
657 doctools/help_gen.py: HelpIndexCards
658
659 In the latter case, we cold process some tags, like:
660
661 - Blue Link (not clickable, but still useful)
662 - Red X
663
664 That should be html.ToAnsi.
665 """
666 f = StringIO()
667 out = Output(s, f, left_pos, right_pos)
668
669 pos = left_pos
670 for tok_id, end_pos in ValidTokens(s, left_pos, right_pos):
671 if tok_id == Tok.RawData:
672 out.SkipTo(pos)
673 out.PrintUntil(end_pos)
674
675 elif tok_id == Tok.CharEntity: # &amp;
676
677 entity = s[pos + 1:end_pos - 1]
678
679 out.SkipTo(pos)
680 out.Print(CHAR_ENTITY[entity])
681 out.SkipTo(end_pos)
682
683 # Not handling these yet
684 elif tok_id == Tok.HexChar:
685 raise AssertionError('Hex Char %r' % s[pos:pos + 20])
686
687 elif tok_id == Tok.DecChar:
688 raise AssertionError('Dec Char %r' % s[pos:pos + 20])
689
690 pos = end_pos
691
692 out.PrintTheRest()
693 return f.getvalue()
694
695
696# https://developer.mozilla.org/en-US/docs/Glossary/Void_element
697VOID_ELEMENTS = [
698 'area',
699 'base',
700 'br',
701 'col',
702 'embed',
703 'hr',
704 'img',
705 'input',
706 'link',
707 'meta',
708 'param',
709 'source',
710 'track',
711 'wbr',
712]
713
714LEX_ATTRS = 1 << 1
715LEX_QUOTED_VALUES = 1 << 2 # href="?x=42&amp;y=99"
716NO_SPECIAL_TAGS = 1 << 3 # <script> <style>, VOID tags, etc.
717BALANCED_TAGS = 1 << 4 # are tags balanced?
718
719
720def Validate(contents, flags, counters):
721 # type: (str, int, Counters) -> None
722
723 tag_lexer = TagLexer(contents)
724 no_special_tags = bool(flags & NO_SPECIAL_TAGS)
725 lx = Lexer(contents, no_special_tags=no_special_tags)
726 tokens = []
727 start_pos = 0
728 tag_stack = []
729 while True:
730 tok_id, end_pos = lx.Read()
731
732 if tok_id == Tok.Invalid:
733 raise LexError(contents, start_pos)
734 if tok_id == Tok.EndOfStream:
735 break
736
737 tokens.append((tok_id, end_pos))
738
739 if tok_id == Tok.StartEndTag:
740 counters.num_start_end_tags += 1
741
742 tag_lexer.Reset(start_pos, end_pos)
743 all_attrs = tag_lexer.AllAttrsRaw()
744 counters.num_attrs += len(all_attrs)
745 counters.debug_attrs.extend(all_attrs)
746
747 elif tok_id == Tok.StartTag:
748 counters.num_start_tags += 1
749
750 tag_lexer.Reset(start_pos, end_pos)
751 all_attrs = tag_lexer.AllAttrsRaw()
752 counters.num_attrs += len(all_attrs)
753 counters.debug_attrs.extend(all_attrs)
754
755 if flags & BALANCED_TAGS:
756 tag_name = lx.TagName()
757 if flags & NO_SPECIAL_TAGS:
758 tag_stack.append(tag_name)
759 else:
760 # e.g. <meta> is considered self-closing, like <meta/>
761 if tag_name not in VOID_ELEMENTS:
762 tag_stack.append(tag_name)
763
764 counters.max_tag_stack = max(counters.max_tag_stack,
765 len(tag_stack))
766 elif tok_id == Tok.EndTag:
767 if flags & BALANCED_TAGS:
768 try:
769 expected = tag_stack.pop()
770 except IndexError:
771 raise ParseError('Tag stack empty',
772 s=contents,
773 start_pos=start_pos)
774
775 actual = lx.TagName()
776 if expected != actual:
777 raise ParseError(
778 'Got unexpected closing tag %r; opening tag was %r' %
779 (contents[start_pos:end_pos], expected),
780 s=contents,
781 start_pos=start_pos)
782
783 start_pos = end_pos
784
785 if len(tag_stack) != 0:
786 raise ParseError('Missing closing tags at end of doc: %s' %
787 ' '.join(tag_stack),
788 s=contents,
789 start_pos=start_pos)
790
791 counters.num_tokens += len(tokens)
792
793
794class Counters(object):
795
796 def __init__(self):
797 self.num_tokens = 0
798 self.num_start_tags = 0
799 self.num_start_end_tags = 0
800 self.num_attrs = 0
801 self.max_tag_stack = 0
802
803 self.debug_attrs = []
804
805
806def main(argv):
807 action = argv[1]
808
809 if action == 'tokens':
810 contents = sys.stdin.read()
811
812 lx = Lexer(contents)
813 start_pos = 0
814 while True:
815 tok_id, end_pos = lx.Read()
816 if tok_id == Tok.Invalid:
817 raise LexError(contents, start_pos)
818 if tok_id == Tok.EndOfStream:
819 break
820
821 frag = contents[start_pos:end_pos]
822 log('%d %s %r', end_pos, TokenName(tok_id), frag)
823 start_pos = end_pos
824
825 return 0
826
827 elif action in ('lex-htm8', 'parse-htm8', 'parse-xml'):
828
829 errors = []
830 counters = Counters()
831
832 flags = LEX_ATTRS | LEX_QUOTED_VALUES
833 if action.startswith('parse-'):
834 flags |= BALANCED_TAGS
835 if action == 'parse-xml':
836 flags |= NO_SPECIAL_TAGS
837
838 i = 0
839 for line in sys.stdin:
840 filename = line.strip()
841 with open(filename) as f:
842 contents = f.read()
843
844 try:
845 Validate(contents, flags, counters)
846 except LexError as e:
847 log('Lex error in %r: %s', filename, e)
848 errors.append((filename, e))
849 except ParseError as e:
850 log('Parse error in %r: %s', filename, e)
851 errors.append((filename, e))
852 i += 1
853
854 log('')
855 log(
856 ' %d tokens, %d start/end tags, %d start tags, %d attrs, %d max tag stack depth in %d files',
857 counters.num_tokens, counters.num_start_end_tags,
858 counters.num_start_tags, counters.num_attrs,
859 counters.max_tag_stack, i)
860 log(' %d errors', len(errors))
861 if len(errors):
862 return 1
863 return 0
864
865 elif action == 'todo':
866 # Other algorithms:
867 #
868 # - select first subtree with given ID
869 # - this requires understanding the void tags I suppose
870 # - select all subtrees that have a class
871 # - materialize DOM
872
873 # Safe-HTM8? This is a filter
874 return 0
875
876 else:
877 raise RuntimeError('Invalid action %r' % action)
878
879
880if __name__ == '__main__':
881 sys.exit(main(sys.argv))