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

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