ยปCore Development>Code coverage>Lib/sgmllib.py

Python code coverage for Lib/sgmllib.py

#countcontent
11"""A parser for SGML, using the derived class as a static DTD."""
2n/a
3n/a# XXX This only supports those SGML features used by HTML.
4n/a
5n/a# XXX There should be a way to distinguish between PCDATA (parsed
6n/a# character data -- the normal case), RCDATA (replaceable character
7n/a# data -- only char and entity references and end tags are special)
8n/a# and CDATA (character data -- only end tags are special). RCDATA is
9n/a# not supported at all.
10n/a
11n/a
121from warnings import warnpy3k
131warnpy3k("the sgmllib module has been removed in Python 3.0",
141 stacklevel=2)
151del warnpy3k
16n/a
171import markupbase
181import re
19n/a
201__all__ = ["SGMLParser", "SGMLParseError"]
21n/a
22n/a# Regular expressions used for parsing
23n/a
241interesting = re.compile('[&<]')
251incomplete = re.compile('&([a-zA-Z][a-zA-Z0-9]*|#[0-9]*)?|'
26n/a '<([a-zA-Z][^<>]*|'
27n/a '/([a-zA-Z][^<>]*)?|'
28n/a '![^<>]*)?')
29n/a
301entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
311charref = re.compile('&#([0-9]+)[^0-9]')
32n/a
331starttagopen = re.compile('<[>a-zA-Z]')
341shorttagopen = re.compile('<[a-zA-Z][-.a-zA-Z0-9]*/')
351shorttag = re.compile('<([a-zA-Z][-.a-zA-Z0-9]*)/([^/]*)/')
361piclose = re.compile('>')
371endbracket = re.compile('[<>]')
381tagfind = re.compile('[a-zA-Z][-_.a-zA-Z0-9]*')
391attrfind = re.compile(
401 r'\s*([a-zA-Z_][-:.a-zA-Z_0-9]*)(\s*=\s*'
41n/a r'(\'[^\']*\'|"[^"]*"|[][\-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~\'"@]*))?')
42n/a
43n/a
442class SGMLParseError(RuntimeError):
451 """Exception raised for all parse errors."""
461 pass
47n/a
48n/a
49n/a# SGML parser base class -- find tags and call handler functions.
50n/a# Usage: p = SGMLParser(); p.feed(data); ...; p.close().
51n/a# The dtd is defined by deriving a class which defines methods
52n/a# with special names to handle tags: start_foo and end_foo to handle
53n/a# <foo> and </foo>, respectively, or do_foo to handle <foo> by itself.
54n/a# (Tags are converted to lower case for this purpose.) The data
55n/a# between tags is passed to the parser by calling self.handle_data()
56n/a# with some data as argument (the data may be split up in arbitrary
57n/a# chunks). Entity references are passed by calling
58n/a# self.handle_entityref() with the entity reference as argument.
59n/a
602class SGMLParser(markupbase.ParserBase):
61n/a # Definition of entities -- derived classes may override
621 entity_or_charref = re.compile('&(?:'
63n/a '([a-zA-Z][-.a-zA-Z0-9]*)|#([0-9]+)'
64n/a ')(;?)')
65n/a
661 def __init__(self, verbose=0):
67n/a """Initialize and reset this instance."""
6834 self.verbose = verbose
6934 self.reset()
70n/a
711 def reset(self):
72n/a """Reset this instance. Loses all unprocessed data."""
7334 self.__starttag_text = None
7434 self.rawdata = ''
7534 self.stack = []
7634 self.lasttag = '???'
7734 self.nomoretags = 0
7834 self.literal = 0
7934 markupbase.ParserBase.reset(self)
80n/a
811 def setnomoretags(self):
82n/a """Enter literal mode (CDATA) till EOF.
83n/a
84n/a Intended for derived classes only.
85n/a """
860 self.nomoretags = self.literal = 1
87n/a
881 def setliteral(self, *args):
89n/a """Enter literal mode (CDATA).
90n/a
91n/a Intended for derived classes only.
92n/a """
932 self.literal = 1
94n/a
951 def feed(self, data):
96n/a """Feed some data to the parser.
97n/a
98n/a Call this as often as you want, with as little or as much text
99n/a as you want (may include '\n'). (This just saves the text,
100n/a all the processing is done by goahead().)
101n/a """
102n/a
1031193 self.rawdata = self.rawdata + data
1041193 self.goahead(0)
105n/a
1061 def close(self):
107n/a """Handle the remaining data."""
10832 self.goahead(1)
109n/a
1101 def error(self, message):
1111 raise SGMLParseError(message)
112n/a
113n/a # Internal -- handle data as far as reasonable. May leave state
114n/a # and data to be processed by a subsequent call. If 'end' is
115n/a # true, force handling all data as if followed by EOF marker.
1161 def goahead(self, end):
1171225 rawdata = self.rawdata
1181225 i = 0
1191225 n = len(rawdata)
1201662 while i < n:
1211587 if self.nomoretags:
1220 self.handle_data(rawdata[i:n])
1230 i = n
1240 break
1251587 match = interesting.search(rawdata, i)
1261587 if match: j = match.start()
127156 else: j = n
1281587 if i < j:
129434 self.handle_data(rawdata[i:j])
1301587 i = j
1311587 if i == n: break
1321431 if rawdata[i] == '<':
1331406 if starttagopen.match(rawdata, i):
134957 if self.literal:
1351 self.handle_data(rawdata[i])
1361 i = i+1
1371 continue
138956 k = self.parse_starttag(i)
139956 if k < 0: break
140227 i = k
141227 continue
142449 if rawdata.startswith("</", i):
143222 k = self.parse_endtag(i)
144222 if k < 0: break
145180 i = k
146180 self.literal = 0
147180 continue
148227 if self.literal:
1495 if n > (i + 1):
1501 self.handle_data("<")
1511 i = i+1
152n/a else:
153n/a # incomplete
1544 break
1550 continue
156222 if rawdata.startswith("<!--", i):
157n/a # Strictly speaking, a comment is --.*--
158n/a # within a declaration tag <!...>.
159n/a # This should be removed,
160n/a # and comments handled only in parse_declaration.
16120 k = self.parse_comment(i)
16220 if k < 0: break
1638 i = k
1648 continue
165202 if rawdata.startswith("<?", i):
16624 k = self.parse_pi(i)
16724 if k < 0: break
1681 i = i+k
1691 continue
170178 if rawdata.startswith("<!", i):
171n/a # This is some sort of declaration; in "HTML as
172n/a # deployed," this should only be the document type
173n/a # declaration ("<!DOCTYPE html...>").
174132 k = self.parse_declaration(i)
175131 if k < 0: break
1766 i = k
1776 continue
17825 elif rawdata[i] == '&':
17925 if self.literal:
1801 self.handle_data(rawdata[i])
1811 i = i+1
1821 continue
18324 match = charref.match(rawdata, i)
18424 if match:
1851 name = match.group(1)
1861 self.handle_charref(name)
1871 i = match.end(0)
1881 if rawdata[i-1] != ';': i = i-1
1890 continue
19023 match = entityref.match(rawdata, i)
19123 if match:
1926 name = match.group(1)
1936 self.handle_entityref(name)
1946 i = match.end(0)
1956 if rawdata[i-1] != ';': i = i-1
1960 continue
197n/a else:
1980 self.error('neither < nor & ??')
199n/a # We get here only if incomplete matches but
200n/a # nothing else
20163 match = incomplete.match(rawdata, i)
20263 if not match:
2030 self.handle_data(rawdata[i])
2040 i = i+1
2050 continue
20663 j = match.end(0)
20763 if j == n:
20858 break # Really incomplete
2095 self.handle_data(rawdata[i:j])
2105 i = j
211n/a # end while
2121224 if end and i < n:
2131 self.handle_data(rawdata[i:n])
2141 i = n
2151224 self.rawdata = rawdata[i:]
216n/a # XXX if end: check for empty stack
217n/a
218n/a # Extensions for the DOCTYPE scanner:
2191 _decl_otherchars = '='
220n/a
221n/a # Internal -- parse processing instr, return length or -1 if not terminated
2221 def parse_pi(self, i):
22324 rawdata = self.rawdata
22424 if rawdata[i:i+2] != '<?':
2250 self.error('unexpected call to parse_pi()')
22624 match = piclose.search(rawdata, i+2)
22724 if not match:
22823 return -1
2291 j = match.start(0)
2301 self.handle_pi(rawdata[i+2: j])
2311 j = match.end(0)
2321 return j-i
233n/a
2341 def get_starttag_text(self):
2350 return self.__starttag_text
236n/a
237n/a # Internal -- handle starttag, return length or -1 if not terminated
2381 def parse_starttag(self, i):
239956 self.__starttag_text = None
240956 start_pos = i
241956 rawdata = self.rawdata
242956 if shorttagopen.match(rawdata, i):
243n/a # SGML shorthand: <tag/data/ == <tag>data</tag>
244n/a # XXX Can data contain &... (entity or char refs)?
245n/a # XXX Can data contain < or > (tag characters)?
246n/a # XXX Can there be whitespace before the first /?
2470 match = shorttag.match(rawdata, i)
2480 if not match:
2490 return -1
2500 tag, data = match.group(1, 2)
2510 self.__starttag_text = '<%s/' % tag
2520 tag = tag.lower()
2530 k = match.end(0)
2540 self.finish_shorttag(tag, data)
2550 self.__starttag_text = rawdata[start_pos:match.end(1) + 1]
2560 return k
257n/a # XXX The following should skip matching quotes (' or ")
258n/a # As a shortcut way to exit, this isn't so bad, but shouldn't
259n/a # be used to locate the actual end of the start tag since the
260n/a # < or > characters may be embedded in an attribute value.
261956 match = endbracket.search(rawdata, i+1)
262956 if not match:
263729 return -1
264227 j = match.start(0)
265n/a # Now parse the data between i+1 and j into a tag and attrs
266227 attrs = []
267227 if rawdata[i:i+2] == '<>':
268n/a # SGML shorthand: <> == <last open tag seen>
2690 k = j
2700 tag = self.lasttag
271n/a else:
272227 match = tagfind.match(rawdata, i+1)
273227 if not match:
2740 self.error('unexpected call to parse_starttag')
275227 k = match.end(0)
276227 tag = rawdata[i+1:k].lower()
277227 self.lasttag = tag
278501 while k < j:
279316 match = attrfind.match(rawdata, k)
280316 if not match: break
281274 attrname, rest, attrvalue = match.group(1, 2, 3)
282274 if not rest:
2837 attrvalue = attrname
284n/a else:
285267 if (attrvalue[:1] == "'" == attrvalue[-1:] or
286240 attrvalue[:1] == '"' == attrvalue[-1:]):
287n/a # strip quotes
288250 attrvalue = attrvalue[1:-1]
289267 attrvalue = self.entity_or_charref.sub(
290267 self._convert_ref, attrvalue)
291274 attrs.append((attrname.lower(), attrvalue))
292274 k = match.end(0)
293227 if rawdata[j] == '>':
294226 j = j+1
295227 self.__starttag_text = rawdata[start_pos:j]
296227 self.finish_starttag(tag, attrs)
297227 return j
298n/a
299n/a # Internal -- convert entity or character reference
3001 def _convert_ref(self, match):
30144 if match.group(2):
3028 return self.convert_charref(match.group(2)) or \
3034 '&#%s%s' % match.groups()[1:]
30436 elif match.group(3):
3059 return self.convert_entityref(match.group(1)) or \
3062 '&%s;' % match.group(1)
307n/a else:
30827 return '&%s' % match.group(1)
309n/a
310n/a # Internal -- parse endtag
3111 def parse_endtag(self, i):
312222 rawdata = self.rawdata
313222 match = endbracket.search(rawdata, i+1)
314222 if not match:
31542 return -1
316180 j = match.start(0)
317180 tag = rawdata[i+2:j].strip().lower()
318180 if rawdata[j] == '>':
319179 j = j+1
320180 self.finish_endtag(tag)
321180 return j
322n/a
323n/a # Internal -- finish parsing of <tag/data/ (same as <tag>data</tag>)
3241 def finish_shorttag(self, tag, data):
3250 self.finish_starttag(tag, [])
3260 self.handle_data(data)
3270 self.finish_endtag(tag)
328n/a
329n/a # Internal -- finish processing of start tag
330n/a # Return -1 for unknown tag, 0 for open-only tag, 1 for balanced tag
3311 def finish_starttag(self, tag, attrs):
332227 try:
333227 method = getattr(self, 'start_' + tag)
334220 except AttributeError:
335220 try:
336220 method = getattr(self, 'do_' + tag)
337220 except AttributeError:
338220 self.unknown_starttag(tag, attrs)
339220 return -1
340n/a else:
3410 self.handle_starttag(tag, method, attrs)
3420 return 0
343n/a else:
3447 self.stack.append(tag)
3457 self.handle_starttag(tag, method, attrs)
3467 return 1
347n/a
348n/a # Internal -- finish processing of end tag
3491 def finish_endtag(self, tag):
350180 if not tag:
3510 found = len(self.stack) - 1
3520 if found < 0:
3530 self.unknown_endtag(tag)
3540 return
355n/a else:
356180 if tag not in self.stack:
357173 try:
358173 method = getattr(self, 'end_' + tag)
359173 except AttributeError:
360173 self.unknown_endtag(tag)
361n/a else:
3620 self.report_unbalanced(tag)
363173 return
3647 found = len(self.stack)
36515 for i in range(found):
3668 if self.stack[i] == tag: found = i
36714 while len(self.stack) > found:
3687 tag = self.stack[-1]
3697 try:
3707 method = getattr(self, 'end_' + tag)
3712 except AttributeError:
3722 method = None
3737 if method:
3745 self.handle_endtag(tag, method)
375n/a else:
3762 self.unknown_endtag(tag)
3777 del self.stack[-1]
378n/a
379n/a # Overridable -- handle start tag
3801 def handle_starttag(self, tag, method, attrs):
3817 method(attrs)
382n/a
383n/a # Overridable -- handle end tag
3841 def handle_endtag(self, tag, method):
3855 method()
386n/a
387n/a # Example -- report an unbalanced </...> tag.
3881 def report_unbalanced(self, tag):
3890 if self.verbose:
3900 print '*** Unbalanced </' + tag + '>'
3910 print '*** Stack:', self.stack
392n/a
3931 def convert_charref(self, name):
394n/a """Convert character reference, may be overridden."""
3958 try:
3968 n = int(name)
3970 except ValueError:
3980 return
3998 if not 0 <= n <= 127:
4003 return
4015 return self.convert_codepoint(n)
402n/a
4031 def convert_codepoint(self, codepoint):
4045 return chr(codepoint)
405n/a
4061 def handle_charref(self, name):
407n/a """Handle character reference, no need to override."""
4081 replacement = self.convert_charref(name)
4091 if replacement is None:
4101 self.unknown_charref(name)
411n/a else:
4120 self.handle_data(replacement)
413n/a
414n/a # Definition of entities -- derived classes may override
415n/a entitydefs = \
4161 {'lt': '<', 'gt': '>', 'amp': '&', 'quot': '"', 'apos': '\''}
417n/a
4181 def convert_entityref(self, name):
419n/a """Convert entity references.
420n/a
421n/a As an alternative to overriding this method; one can tailor the
422n/a results by setting up the self.entitydefs mapping appropriately.
423n/a """
42415 table = self.entitydefs
42515 if name in table:
4268 return table[name]
427n/a else:
4287 return
429n/a
4301 def handle_entityref(self, name):
431n/a """Handle entity references, no need to override."""
4326 replacement = self.convert_entityref(name)
4336 if replacement is None:
4345 self.unknown_entityref(name)
435n/a else:
4361 self.handle_data(replacement)
437n/a
438n/a # Example -- handle data, should be overridden
4391 def handle_data(self, data):
440271 pass
441n/a
442n/a # Example -- handle comment, could be overridden
4431 def handle_comment(self, data):
4447 pass
445n/a
446n/a # Example -- handle declaration, could be overridden
4471 def handle_decl(self, decl):
4480 pass
449n/a
450n/a # Example -- handle processing instruction, could be overridden
4511 def handle_pi(self, data):
4520 pass
453n/a
454n/a # To be overridden -- handlers for unknown objects
455195 def unknown_starttag(self, tag, attrs): pass
456167 def unknown_endtag(self, tag): pass
4572 def unknown_charref(self, ref): pass
4586 def unknown_entityref(self, ref): pass
459n/a
460n/a
4612class TestSGMLParser(SGMLParser):
462n/a
4631 def __init__(self, verbose=0):
4640 self.testdata = ""
4650 SGMLParser.__init__(self, verbose)
466n/a
4671 def handle_data(self, data):
4680 self.testdata = self.testdata + data
4690 if len(repr(self.testdata)) >= 70:
4700 self.flush()
471n/a
4721 def flush(self):
4730 data = self.testdata
4740 if data:
4750 self.testdata = ""
4760 print 'data:', repr(data)
477n/a
4781 def handle_comment(self, data):
4790 self.flush()
4800 r = repr(data)
4810 if len(r) > 68:
4820 r = r[:32] + '...' + r[-32:]
4830 print 'comment:', r
484n/a
4851 def unknown_starttag(self, tag, attrs):
4860 self.flush()
4870 if not attrs:
4880 print 'start tag: <' + tag + '>'
489n/a else:
4900 print 'start tag: <' + tag,
4910 for name, value in attrs:
4920 print name + '=' + '"' + value + '"',
4930 print '>'
494n/a
4951 def unknown_endtag(self, tag):
4960 self.flush()
4970 print 'end tag: </' + tag + '>'
498n/a
4991 def unknown_entityref(self, ref):
5000 self.flush()
5010 print '*** unknown entity ref: &' + ref + ';'
502n/a
5031 def unknown_charref(self, ref):
5040 self.flush()
5050 print '*** unknown char ref: &#' + ref + ';'
506n/a
5071 def unknown_decl(self, data):
5080 self.flush()
5090 print '*** unknown decl: [' + data + ']'
510n/a
5111 def close(self):
5120 SGMLParser.close(self)
5130 self.flush()
514n/a
515n/a
5161def test(args = None):
5170 import sys
518n/a
5190 if args is None:
5200 args = sys.argv[1:]
521n/a
5220 if args and args[0] == '-s':
5230 args = args[1:]
5240 klass = SGMLParser
525n/a else:
5260 klass = TestSGMLParser
527n/a
5280 if args:
5290 file = args[0]
530n/a else:
5310 file = 'test.html'
532n/a
5330 if file == '-':
5340 f = sys.stdin
535n/a else:
5360 try:
5370 f = open(file, 'r')
5380 except IOError, msg:
5390 print file, ":", msg
5400 sys.exit(1)
541n/a
5420 data = f.read()
5430 if f is not sys.stdin:
5440 f.close()
545n/a
5460 x = klass()
5470 for c in data:
5480 x.feed(c)
5490 x.close()
550n/a
551n/a
5521if __name__ == '__main__':
5530 test()