1 """A parser for SGML, using the derived class as a static DTD."""
3 # XXX This only supports those SGML features used by HTML.
5 # XXX There should be a way to distinguish between PCDATA (parsed
6 # character data -- the normal case), RCDATA (replaceable character
7 # data -- only char and entity references and end tags are special)
8 # and CDATA (character data -- only end tags are special).
14 __all__
= ["SGMLParser"]
16 # Regular expressions used for parsing
18 interesting
= re
.compile('[&<]')
19 incomplete
= re
.compile('&([a-zA-Z][a-zA-Z0-9]*|#[0-9]*)?|'
24 entityref
= re
.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
25 charref
= re
.compile('&#([0-9]+)[^0-9]')
27 starttagopen
= re
.compile('<[>a-zA-Z]')
28 shorttagopen
= re
.compile('<[a-zA-Z][-.a-zA-Z0-9]*/')
29 shorttag
= re
.compile('<([a-zA-Z][-.a-zA-Z0-9]*)/([^/]*)/')
30 piopen
= re
.compile('<\?')
31 piclose
= re
.compile('>')
32 endtagopen
= re
.compile('</[<>a-zA-Z]')
33 endbracket
= re
.compile('[<>]')
34 special
= re
.compile('<![^<>]*>')
35 commentopen
= re
.compile('<!--')
36 commentclose
= re
.compile(r
'--\s*>')
37 tagfind
= re
.compile('[a-zA-Z][-.a-zA-Z0-9]*')
38 attrfind
= re
.compile(
39 r
'\s*([a-zA-Z_][-.a-zA-Z_0-9]*)(\s*=\s*'
40 r
'(\'[^
\']*\'|
"[^"]*"|[-a-zA-Z0-9./:;+*%?!&$\(\)_#=~]*))?')
42 declname = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\s*')
43 declstringlit = re.compile(r'(\'[^\']*\'|"[^
"]*")\s
*')
46 class SGMLParseError(RuntimeError):
47 """Exception raised for all parse errors."""
51 # SGML parser base class -- find tags and call handler functions.
52 # Usage: p = SGMLParser(); p.feed(data); ...; p.close().
53 # The dtd is defined by deriving a class which defines methods
54 # with special names to handle tags: start_foo and end_foo to handle
55 # <foo> and </foo>, respectively, or do_foo to handle <foo> by itself.
56 # (Tags are converted to lower case for this purpose.) The data
57 # between tags is passed to the parser by calling self.handle_data()
58 # with some data as argument (the data may be split up in arbitrary
59 # chunks). Entity references are passed by calling
60 # self.handle_entityref() with the entity reference as argument.
64 # Interface -- initialize and reset this instance
65 def __init__(self, verbose=0):
66 self.verbose = verbose
69 # Interface -- reset this instance. Loses all unprocessed data
77 # For derived classes only -- enter literal mode (CDATA) till EOF
78 def setnomoretags(self):
79 self.nomoretags = self.literal = 1
81 # For derived classes only -- enter literal mode (CDATA)
82 def setliteral(self, *args):
85 # Interface -- feed some data to the parser. Call this as
86 # often as you want, with as little or as much text as you
87 # want (may include '\n'). (This just saves the text, all the
88 # processing is done by goahead().)
90 self.rawdata = self.rawdata + data
93 # Interface -- handle the remaining data
97 # Internal -- handle data as far as reasonable. May leave state
98 # and data to be processed by a subsequent call. If 'end
' is
99 # true, force handling all data as if followed by EOF marker.
100 def goahead(self, end):
101 rawdata = self.rawdata
106 self.handle_data(rawdata[i:n])
109 match = interesting.search(rawdata, i)
110 if match: j = match.start(0)
112 if i < j: self.handle_data(rawdata[i:j])
115 if rawdata[i] == '<':
116 if starttagopen.match(rawdata, i):
118 self.handle_data(rawdata[i])
121 k = self.parse_starttag(i)
125 if endtagopen.match(rawdata, i):
126 k = self.parse_endtag(i)
131 if commentopen.match(rawdata, i):
133 self.handle_data(rawdata[i])
136 k = self.parse_comment(i)
140 if piopen.match(rawdata, i):
142 self.handle_data(rawdata[i])
149 match = special.match(rawdata, i)
152 self.handle_data(rawdata[i])
155 # This is some sort of declaration; in "HTML as
156 # deployed," this should only be the document type
157 # declaration ("<!DOCTYPE html...>").
158 k = self.parse_declaration(i)
162 elif rawdata[i] == '&':
163 match = charref.match(rawdata, i)
165 name = match.group(1)
166 self.handle_charref(name)
168 if rawdata[i-1] != ';': i = i-1
170 match = entityref.match(rawdata, i)
172 name = match.group(1)
173 self.handle_entityref(name)
175 if rawdata[i-1] != ';': i = i-1
178 raise SGMLParseError('neither
< nor
& ??
')
179 # We get here only if incomplete matches but
181 match = incomplete.match(rawdata, i)
183 self.handle_data(rawdata[i])
188 break # Really incomplete
189 self.handle_data(rawdata[i:j])
193 self.handle_data(rawdata[i:n])
195 self.rawdata = rawdata[i:]
196 # XXX if end: check for empty stack
198 # Internal -- parse comment, return length or -1 if not terminated
199 def parse_comment(self, i):
200 rawdata = self.rawdata
201 if rawdata[i:i+4] != '<!--':
202 raise SGMLParseError('unexpected call to
parse_comment()')
203 match = commentclose.search(rawdata, i+4)
207 self.handle_comment(rawdata[i+4: j])
211 # Internal -- parse declaration.
212 def parse_declaration(self, i):
213 rawdata = self.rawdata
215 # in practice, this should look like: ((name|stringlit) S*)+ '>'
219 # end of declaration syntax
220 self.handle_decl(rawdata[i+2:j])
223 m = declstringlit.match(rawdata, j)
225 # incomplete or an error?
228 elif c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
":
229 m = declname.match(rawdata, j)
231 # incomplete or an error?
234 elif i == len(rawdata):
235 # end of buffer between tokens
238 raise SGMLParseError(
239 "unexpected char
in declaration
: %s" % `rawdata[i]`)
240 assert 0, "can
't get here!"
242 # Internal -- parse processing instr, return length or -1 if not terminated
243 def parse_pi(self, i):
244 rawdata = self.rawdata
245 if rawdata[i:i+2] != '<?
':
246 raise SGMLParseError('unexpected call to
parse_pi()')
247 match = piclose.search(rawdata, i+2)
251 self.handle_pi(rawdata[i+2: j])
255 __starttag_text = None
256 def get_starttag_text(self):
257 return self.__starttag_text
259 # Internal -- handle starttag, return length or -1 if not terminated
260 def parse_starttag(self, i):
261 self.__starttag_text = None
263 rawdata = self.rawdata
264 if shorttagopen.match(rawdata, i):
265 # SGML shorthand: <tag/data/ == <tag>data</tag>
266 # XXX Can data contain &... (entity or char refs)?
267 # XXX Can data contain < or > (tag characters)?
268 # XXX Can there be whitespace before the first /?
269 match = shorttag.match(rawdata, i)
272 tag, data = match.group(1, 2)
273 self.__starttag_text = '<%s/' % tag
276 self.finish_shorttag(tag, data)
277 self.__starttag_text = rawdata[start_pos:match.end(1) + 1]
279 # XXX The following should skip matching quotes (' or ")
280 match = endbracket.search(rawdata, i+1)
284 # Now parse the data between i+1 and j into a tag and attrs
286 if rawdata[i:i+2] == '<>':
287 # SGML shorthand: <> == <last open tag seen>
291 match = tagfind.match(rawdata, i+1)
293 raise SGMLParseError('unexpected call to parse_starttag')
295 tag = rawdata[i+1:k].lower()
298 match = attrfind.match(rawdata, k)
300 attrname, rest, attrvalue = match.group(1, 2, 3)
303 elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
304 attrvalue[:1] == '"' == attrvalue[-1:]:
305 attrvalue = attrvalue[1:-1]
306 attrs.append((attrname.lower(), attrvalue))
308 if rawdata[j] == '>':
310 self.__starttag_text = rawdata[start_pos:j]
311 self.finish_starttag(tag, attrs)
314 # Internal -- parse endtag
315 def parse_endtag(self, i):
316 rawdata = self.rawdata
317 match = endbracket.search(rawdata, i+1)
321 tag = rawdata[i+2:j].strip().lower()
322 if rawdata[j] == '>':
324 self.finish_endtag(tag)
327 # Internal -- finish parsing of <tag/data/ (same as <tag>data</tag>)
328 def finish_shorttag(self, tag, data):
329 self.finish_starttag(tag, [])
330 self.handle_data(data)
331 self.finish_endtag(tag)
333 # Internal -- finish processing of start tag
334 # Return -1 for unknown tag, 0 for open-only tag, 1 for balanced tag
335 def finish_starttag(self, tag, attrs):
337 method = getattr(self, 'start_
' + tag)
338 except AttributeError:
340 method = getattr(self, 'do_
' + tag)
341 except AttributeError:
342 self.unknown_starttag(tag, attrs)
345 self.handle_starttag(tag, method, attrs)
348 self.stack.append(tag)
349 self.handle_starttag(tag, method, attrs)
352 # Internal -- finish processing of end tag
353 def finish_endtag(self, tag):
355 found = len(self.stack) - 1
357 self.unknown_endtag(tag)
360 if tag not in self.stack:
362 method = getattr(self, 'end_
' + tag)
363 except AttributeError:
364 self.unknown_endtag(tag)
366 self.report_unbalanced(tag)
368 found = len(self.stack)
369 for i in range(found):
370 if self.stack[i] == tag: found = i
371 while len(self.stack) > found:
374 method = getattr(self, 'end_
' + tag)
375 except AttributeError:
378 self.handle_endtag(tag, method)
380 self.unknown_endtag(tag)
383 # Overridable -- handle start tag
384 def handle_starttag(self, tag, method, attrs):
387 # Overridable -- handle end tag
388 def handle_endtag(self, tag, method):
391 # Example -- report an unbalanced </...> tag.
392 def report_unbalanced(self, tag):
394 print '*** Unbalanced
</' + tag + '>'
395 print '*** Stack
:', self.stack
397 # Example -- handle character reference, no need to override
398 def handle_charref(self, name):
402 self.unknown_charref(name)
404 if not 0 <= n <= 255:
405 self.unknown_charref(name)
407 self.handle_data(chr(n))
409 # Definition of entities -- derived classes may override
411 {'lt
': '<', 'gt
': '>', 'amp
': '&', 'quot
': '"', 'apos': '\''}
413 # Example -- handle entity reference, no need to override
414 def handle_entityref(self, name):
415 table = self.entitydefs
416 if table.has_key(name):
417 self.handle_data(table[name])
419 self.unknown_entityref(name)
422 # Example -- handle data, should be overridden
423 def handle_data(self, data):
426 # Example -- handle comment, could be overridden
427 def handle_comment(self, data):
430 # Example -- handle declaration, could be overridden
431 def handle_decl(self, decl):
434 # Example -- handle processing instruction, could be overridden
435 def handle_pi(self, data):
438 # To be overridden -- handlers for unknown objects
439 def unknown_starttag(self, tag, attrs): pass
440 def unknown_endtag(self, tag): pass
441 def unknown_charref(self, ref): pass
442 def unknown_entityref(self, ref): pass
445 class TestSGMLParser(SGMLParser):
447 def __init__(self, verbose=0):
449 SGMLParser.__init__(self, verbose)
451 def handle_data(self, data):
452 self.testdata = self.testdata + data
453 if len(`self.testdata`) >= 70:
460 print 'data:', `data`
462 def handle_comment(self, data):
466 r = r[:32] + '...' + r[-32:]
469 def unknown_starttag(self, tag, attrs):
472 print 'start tag: <' + tag + '>'
474 print 'start tag: <' + tag,
475 for name, value in attrs:
476 print name + '=' + '"' + value + '"',
479 def unknown_endtag(self, tag):
481 print 'end tag: </' + tag + '>'
483 def unknown_entityref(self, ref):
485 print '*** unknown entity ref: &' + ref + ';'
487 def unknown_charref(self, ref):
489 print '*** unknown char ref: &#' + ref + ';'
492 SGMLParser.close(self)
496 def test(args = None):
502 if args and args[0] == '-s':
506 klass = TestSGMLParser
523 if f is not sys.stdin:
532 if __name__ == '__main__':