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

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