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).
15 # Regular expressions used for parsing
17 interesting
= re
.compile('[&<]')
18 incomplete
= re
.compile('&([a-zA-Z][a-zA-Z0-9]*|#[0-9]*)?|'
23 entityref
= re
.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
24 charref
= re
.compile('&#([0-9]+)[^0-9]')
26 starttagopen
= re
.compile('<[>a-zA-Z]')
27 shorttagopen
= re
.compile('<[a-zA-Z][-.a-zA-Z0-9]*/')
28 shorttag
= re
.compile('<([a-zA-Z][-.a-zA-Z0-9]*)/([^/]*)/')
29 piopen
= re
.compile('<\?')
30 piclose
= re
.compile('>')
31 endtagopen
= re
.compile('</[<>a-zA-Z]')
32 endbracket
= re
.compile('[<>]')
33 special
= re
.compile('<![^<>]*>')
34 commentopen
= re
.compile('<!--')
35 commentclose
= re
.compile('--[%s]*>' % string
.whitespace
)
36 tagfind
= re
.compile('[a-zA-Z][-.a-zA-Z0-9]*')
37 attrfind
= re
.compile(
38 '[%s]*([a-zA-Z_][-.a-zA-Z_0-9]*)' % string
.whitespace
39 + ('([%s]*=[%s]*' % (string
.whitespace
, string
.whitespace
))
40 + r
'(\'[^
\']*\'|
"[^"]*"|[-a-zA-Z0-9./:+*%?!&$\(\)_#=~]*))?')
43 # SGML parser base class -- find tags and call handler functions.
44 # Usage: p = SGMLParser(); p.feed(data); ...; p.close().
45 # The dtd is defined by deriving a class which defines methods
46 # with special names to handle tags: start_foo and end_foo to handle
47 # <foo> and </foo>, respectively, or do_foo to handle <foo> by itself.
48 # (Tags are converted to lower case for this purpose.) The data
49 # between tags is passed to the parser by calling self.handle_data()
50 # with some data as argument (the data may be split up in arbitrary
51 # chunks). Entity references are passed by calling
52 # self.handle_entityref() with the entity reference as argument.
56 # Interface -- initialize and reset this instance
57 def __init__(self, verbose=0):
58 self.verbose = verbose
61 # Interface -- reset this instance. Loses all unprocessed data
69 # For derived classes only -- enter literal mode (CDATA) till EOF
70 def setnomoretags(self):
71 self.nomoretags = self.literal = 1
73 # For derived classes only -- enter literal mode (CDATA)
74 def setliteral(self, *args):
77 # Interface -- feed some data to the parser. Call this as
78 # often as you want, with as little or as much text as you
79 # want (may include '\n'). (This just saves the text, all the
80 # processing is done by goahead().)
82 self.rawdata = self.rawdata + data
85 # Interface -- handle the remaining data
89 # Internal -- handle data as far as reasonable. May leave state
90 # and data to be processed by a subsequent call. If 'end' is
91 # true, force handling all data as if followed by EOF marker.
92 def goahead(self, end):
93 rawdata = self.rawdata
98 self.handle_data(rawdata[i:n])
101 match = interesting.search(rawdata, i)
102 if match: j = match.start(0)
104 if i < j: self.handle_data(rawdata[i:j])
107 if rawdata[i] == '<':
108 if starttagopen.match(rawdata, i):
110 self.handle_data(rawdata[i])
113 k = self.parse_starttag(i)
117 if endtagopen.match(rawdata, i):
118 k = self.parse_endtag(i)
123 if commentopen.match(rawdata, i):
125 self.handle_data(rawdata[i])
128 k = self.parse_comment(i)
132 if piopen.match(rawdata, i):
134 self.handle_data(rawdata[i])
141 match = special.match(rawdata, i)
144 self.handle_data(rawdata[i])
149 elif rawdata[i] == '&':
150 match = charref.match(rawdata, i)
152 name = match.group(1)
153 self.handle_charref(name)
155 if rawdata[i-1] != ';': i = i-1
157 match = entityref.match(rawdata, i)
159 name = match.group(1)
160 self.handle_entityref(name)
162 if rawdata[i-1] != ';': i = i-1
165 raise RuntimeError, 'neither < nor & ??'
166 # We get here only if incomplete matches but
168 match = incomplete.match(rawdata, i)
170 self.handle_data(rawdata[i])
175 break # Really incomplete
176 self.handle_data(rawdata[i:j])
180 self.handle_data(rawdata[i:n])
182 self.rawdata = rawdata[i:]
183 # XXX if end: check for empty stack
185 # Internal -- parse comment, return length or -1 if not terminated
186 def parse_comment(self, i):
187 rawdata = self.rawdata
188 if rawdata[i:i+4] <> '<!--':
189 raise RuntimeError, 'unexpected call to handle_comment'
190 match = commentclose.search(rawdata, i+4)
194 self.handle_comment(rawdata[i+4: j])
198 # Internal -- parse processing instr, return length or -1 if not terminated
199 def parse_pi(self, i):
200 rawdata = self.rawdata
201 if rawdata[i:i+2] <> '<?':
202 raise RuntimeError, 'unexpected call to handle_pi'
203 match = piclose.search(rawdata, i+2)
207 self.handle_pi(rawdata[i+2: j])
211 __starttag_text = None
212 def get_starttag_text(self):
213 return self.__starttag_text
215 # Internal -- handle starttag, return length or -1 if not terminated
216 def parse_starttag(self, i):
217 self.__starttag_text = None
219 rawdata = self.rawdata
220 if shorttagopen.match(rawdata, i):
221 # SGML shorthand: <tag/data/ == <tag>data</tag>
222 # XXX Can data contain &... (entity or char refs)?
223 # XXX Can data contain < or > (tag characters)?
224 # XXX Can there be whitespace before the first /?
225 match = shorttag.match(rawdata, i)
228 tag, data = match.group(1, 2)
229 self.__starttag_text = '<%s/' % tag
230 tag = string.lower(tag)
232 self.finish_shorttag(tag, data)
233 self.__starttag_text = rawdata[start_pos:match.end(1) + 1]
235 # XXX The following should skip matching quotes (' or ")
236 match
= endbracket
.search(rawdata
, i
+1)
240 # Now parse the data between i+1 and j into a tag and attrs
242 if rawdata
[i
:i
+2] == '<>':
243 # SGML shorthand: <> == <last open tag seen>
247 match
= tagfind
.match(rawdata
, i
+1)
249 raise RuntimeError, 'unexpected call to parse_starttag'
251 tag
= string
.lower(rawdata
[i
+1:k
])
254 match
= attrfind
.match(rawdata
, k
)
256 attrname
, rest
, attrvalue
= match
.group(1, 2, 3)
259 elif attrvalue
[:1] == '\'' == attrvalue
[-1:] or \
260 attrvalue
[:1] == '"' == attrvalue
[-1:]:
261 attrvalue
= attrvalue
[1:-1]
262 attrs
.append((string
.lower(attrname
), attrvalue
))
264 if rawdata
[j
] == '>':
266 self
.__starttag
_text
= rawdata
[start_pos
:j
]
267 self
.finish_starttag(tag
, attrs
)
270 # Internal -- parse endtag
271 def parse_endtag(self
, i
):
272 rawdata
= self
.rawdata
273 match
= endbracket
.search(rawdata
, i
+1)
277 tag
= string
.lower(string
.strip(rawdata
[i
+2:j
]))
278 if rawdata
[j
] == '>':
280 self
.finish_endtag(tag
)
283 # Internal -- finish parsing of <tag/data/ (same as <tag>data</tag>)
284 def finish_shorttag(self
, tag
, data
):
285 self
.finish_starttag(tag
, [])
286 self
.handle_data(data
)
287 self
.finish_endtag(tag
)
289 # Internal -- finish processing of start tag
290 # Return -1 for unknown tag, 0 for open-only tag, 1 for balanced tag
291 def finish_starttag(self
, tag
, attrs
):
293 method
= getattr(self
, 'start_' + tag
)
294 except AttributeError:
296 method
= getattr(self
, 'do_' + tag
)
297 except AttributeError:
298 self
.unknown_starttag(tag
, attrs
)
301 self
.handle_starttag(tag
, method
, attrs
)
304 self
.stack
.append(tag
)
305 self
.handle_starttag(tag
, method
, attrs
)
308 # Internal -- finish processing of end tag
309 def finish_endtag(self
, tag
):
311 found
= len(self
.stack
) - 1
313 self
.unknown_endtag(tag
)
316 if tag
not in self
.stack
:
318 method
= getattr(self
, 'end_' + tag
)
319 except AttributeError:
320 self
.unknown_endtag(tag
)
322 self
.report_unbalanced(tag
)
324 found
= len(self
.stack
)
325 for i
in range(found
):
326 if self
.stack
[i
] == tag
: found
= i
327 while len(self
.stack
) > found
:
330 method
= getattr(self
, 'end_' + tag
)
331 except AttributeError:
334 self
.handle_endtag(tag
, method
)
336 self
.unknown_endtag(tag
)
339 # Overridable -- handle start tag
340 def handle_starttag(self
, tag
, method
, attrs
):
343 # Overridable -- handle end tag
344 def handle_endtag(self
, tag
, method
):
347 # Example -- report an unbalanced </...> tag.
348 def report_unbalanced(self
, tag
):
350 print '*** Unbalanced </' + tag
+ '>'
351 print '*** Stack:', self
.stack
353 # Example -- handle character reference, no need to override
354 def handle_charref(self
, name
):
356 n
= string
.atoi(name
)
357 except string
.atoi_error
:
358 self
.unknown_charref(name
)
360 if not 0 <= n
<= 255:
361 self
.unknown_charref(name
)
363 self
.handle_data(chr(n
))
365 # Definition of entities -- derived classes may override
367 {'lt': '<', 'gt': '>', 'amp': '&', 'quot': '"', 'apos': '\''}
369 # Example -- handle entity reference, no need to override
370 def handle_entityref(self
, name
):
371 table
= self
.entitydefs
372 if table
.has_key(name
):
373 self
.handle_data(table
[name
])
375 self
.unknown_entityref(name
)
378 # Example -- handle data, should be overridden
379 def handle_data(self
, data
):
382 # Example -- handle comment, could be overridden
383 def handle_comment(self
, data
):
386 # Example -- handle processing instruction, could be overridden
387 def handle_pi(self
, data
):
390 # To be overridden -- handlers for unknown objects
391 def unknown_starttag(self
, tag
, attrs
): pass
392 def unknown_endtag(self
, tag
): pass
393 def unknown_charref(self
, ref
): pass
394 def unknown_entityref(self
, ref
): pass
397 class TestSGMLParser(SGMLParser
):
399 def __init__(self
, verbose
=0):
401 SGMLParser
.__init
__(self
, verbose
)
403 def handle_data(self
, data
):
404 self
.testdata
= self
.testdata
+ data
405 if len(`self
.testdata`
) >= 70:
412 print 'data:', `data`
414 def handle_comment(self
, data
):
418 r
= r
[:32] + '...' + r
[-32:]
421 def unknown_starttag(self
, tag
, attrs
):
424 print 'start tag: <' + tag
+ '>'
426 print 'start tag: <' + tag
,
427 for name
, value
in attrs
:
428 print name
+ '=' + '"' + value
+ '"',
431 def unknown_endtag(self
, tag
):
433 print 'end tag: </' + tag
+ '>'
435 def unknown_entityref(self
, ref
):
437 print '*** unknown entity ref: &' + ref
+ ';'
439 def unknown_charref(self
, ref
):
441 print '*** unknown char ref: &#' + ref
+ ';'
444 SGMLParser
.close(self
)
448 def test(args
= None):
454 if args
and args
[0] == '-s':
458 klass
= TestSGMLParser
475 if f
is not sys
.stdin
:
484 if __name__
== '__main__':