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('--[%s]*>' % string
.whitespace
)
37 tagfind
= re
.compile('[a-zA-Z][-.a-zA-Z0-9]*')
38 attrfind
= re
.compile(
39 '[%s]*([a-zA-Z_][-.a-zA-Z_0-9]*)' % string
.whitespace
40 + ('([%s]*=[%s]*' % (string
.whitespace
, string
.whitespace
))
41 + r
'(\'[^
\']*\'|
"[^"]*"|[-a-zA-Z0-9./:;+*%?!&$\(\)_#=~]*))?')
44 # SGML parser base class -- find tags and call handler functions.
45 # Usage: p = SGMLParser(); p.feed(data); ...; p.close().
46 # The dtd is defined by deriving a class which defines methods
47 # with special names to handle tags: start_foo and end_foo to handle
48 # <foo> and </foo>, respectively, or do_foo to handle <foo> by itself.
49 # (Tags are converted to lower case for this purpose.) The data
50 # between tags is passed to the parser by calling self.handle_data()
51 # with some data as argument (the data may be split up in arbitrary
52 # chunks). Entity references are passed by calling
53 # self.handle_entityref() with the entity reference as argument.
57 # Interface -- initialize and reset this instance
58 def __init__(self, verbose=0):
59 self.verbose = verbose
62 # Interface -- reset this instance. Loses all unprocessed data
70 # For derived classes only -- enter literal mode (CDATA) till EOF
71 def setnomoretags(self):
72 self.nomoretags = self.literal = 1
74 # For derived classes only -- enter literal mode (CDATA)
75 def setliteral(self, *args):
78 # Interface -- feed some data to the parser. Call this as
79 # often as you want, with as little or as much text as you
80 # want (may include '\n'). (This just saves the text, all the
81 # processing is done by goahead().)
83 self.rawdata = self.rawdata + data
86 # Interface -- handle the remaining data
90 # Internal -- handle data as far as reasonable. May leave state
91 # and data to be processed by a subsequent call. If 'end' is
92 # true, force handling all data as if followed by EOF marker.
93 def goahead(self, end):
94 rawdata = self.rawdata
99 self.handle_data(rawdata[i:n])
102 match = interesting.search(rawdata, i)
103 if match: j = match.start(0)
105 if i < j: self.handle_data(rawdata[i:j])
108 if rawdata[i] == '<':
109 if starttagopen.match(rawdata, i):
111 self.handle_data(rawdata[i])
114 k = self.parse_starttag(i)
118 if endtagopen.match(rawdata, i):
119 k = self.parse_endtag(i)
124 if commentopen.match(rawdata, i):
126 self.handle_data(rawdata[i])
129 k = self.parse_comment(i)
133 if piopen.match(rawdata, i):
135 self.handle_data(rawdata[i])
142 match = special.match(rawdata, i)
145 self.handle_data(rawdata[i])
150 elif rawdata[i] == '&':
151 match = charref.match(rawdata, i)
153 name = match.group(1)
154 self.handle_charref(name)
156 if rawdata[i-1] != ';': i = i-1
158 match = entityref.match(rawdata, i)
160 name = match.group(1)
161 self.handle_entityref(name)
163 if rawdata[i-1] != ';': i = i-1
166 raise RuntimeError, 'neither < nor & ??'
167 # We get here only if incomplete matches but
169 match = incomplete.match(rawdata, i)
171 self.handle_data(rawdata[i])
176 break # Really incomplete
177 self.handle_data(rawdata[i:j])
181 self.handle_data(rawdata[i:n])
183 self.rawdata = rawdata[i:]
184 # XXX if end: check for empty stack
186 # Internal -- parse comment, return length or -1 if not terminated
187 def parse_comment(self, i):
188 rawdata = self.rawdata
189 if rawdata[i:i+4] != '<!--':
190 raise RuntimeError, 'unexpected call to handle_comment'
191 match = commentclose.search(rawdata, i+4)
195 self.handle_comment(rawdata[i+4: j])
199 # Internal -- parse processing instr, return length or -1 if not terminated
200 def parse_pi(self, i):
201 rawdata = self.rawdata
202 if rawdata[i:i+2] != '<?':
203 raise RuntimeError, 'unexpected call to handle_pi'
204 match = piclose.search(rawdata, i+2)
208 self.handle_pi(rawdata[i+2: j])
212 __starttag_text = None
213 def get_starttag_text(self):
214 return self.__starttag_text
216 # Internal -- handle starttag, return length or -1 if not terminated
217 def parse_starttag(self, i):
218 self.__starttag_text = None
220 rawdata = self.rawdata
221 if shorttagopen.match(rawdata, i):
222 # SGML shorthand: <tag/data/ == <tag>data</tag>
223 # XXX Can data contain &... (entity or char refs)?
224 # XXX Can data contain < or > (tag characters)?
225 # XXX Can there be whitespace before the first /?
226 match = shorttag.match(rawdata, i)
229 tag, data = match.group(1, 2)
230 self.__starttag_text = '<%s/' % tag
233 self.finish_shorttag(tag, data)
234 self.__starttag_text = rawdata[start_pos:match.end(1) + 1]
236 # XXX The following should skip matching quotes (' or ")
237 match
= endbracket
.search(rawdata
, i
+1)
241 # Now parse the data between i+1 and j into a tag and attrs
243 if rawdata
[i
:i
+2] == '<>':
244 # SGML shorthand: <> == <last open tag seen>
248 match
= tagfind
.match(rawdata
, i
+1)
250 raise RuntimeError, 'unexpected call to parse_starttag'
252 tag
= rawdata
[i
+1:k
].lower()
255 match
= attrfind
.match(rawdata
, k
)
257 attrname
, rest
, attrvalue
= match
.group(1, 2, 3)
260 elif attrvalue
[:1] == '\'' == attrvalue
[-1:] or \
261 attrvalue
[:1] == '"' == attrvalue
[-1:]:
262 attrvalue
= attrvalue
[1:-1]
263 attrs
.append((attrname
.lower(), attrvalue
))
265 if rawdata
[j
] == '>':
267 self
.__starttag
_text
= rawdata
[start_pos
:j
]
268 self
.finish_starttag(tag
, attrs
)
271 # Internal -- parse endtag
272 def parse_endtag(self
, i
):
273 rawdata
= self
.rawdata
274 match
= endbracket
.search(rawdata
, i
+1)
278 tag
= rawdata
[i
+2:j
].strip().lower()
279 if rawdata
[j
] == '>':
281 self
.finish_endtag(tag
)
284 # Internal -- finish parsing of <tag/data/ (same as <tag>data</tag>)
285 def finish_shorttag(self
, tag
, data
):
286 self
.finish_starttag(tag
, [])
287 self
.handle_data(data
)
288 self
.finish_endtag(tag
)
290 # Internal -- finish processing of start tag
291 # Return -1 for unknown tag, 0 for open-only tag, 1 for balanced tag
292 def finish_starttag(self
, tag
, attrs
):
294 method
= getattr(self
, 'start_' + tag
)
295 except AttributeError:
297 method
= getattr(self
, 'do_' + tag
)
298 except AttributeError:
299 self
.unknown_starttag(tag
, attrs
)
302 self
.handle_starttag(tag
, method
, attrs
)
305 self
.stack
.append(tag
)
306 self
.handle_starttag(tag
, method
, attrs
)
309 # Internal -- finish processing of end tag
310 def finish_endtag(self
, tag
):
312 found
= len(self
.stack
) - 1
314 self
.unknown_endtag(tag
)
317 if tag
not in self
.stack
:
319 method
= getattr(self
, 'end_' + tag
)
320 except AttributeError:
321 self
.unknown_endtag(tag
)
323 self
.report_unbalanced(tag
)
325 found
= len(self
.stack
)
326 for i
in range(found
):
327 if self
.stack
[i
] == tag
: found
= i
328 while len(self
.stack
) > found
:
331 method
= getattr(self
, 'end_' + tag
)
332 except AttributeError:
335 self
.handle_endtag(tag
, method
)
337 self
.unknown_endtag(tag
)
340 # Overridable -- handle start tag
341 def handle_starttag(self
, tag
, method
, attrs
):
344 # Overridable -- handle end tag
345 def handle_endtag(self
, tag
, method
):
348 # Example -- report an unbalanced </...> tag.
349 def report_unbalanced(self
, tag
):
351 print '*** Unbalanced </' + tag
+ '>'
352 print '*** Stack:', self
.stack
354 # Example -- handle character reference, no need to override
355 def handle_charref(self
, name
):
359 self
.unknown_charref(name
)
361 if not 0 <= n
<= 255:
362 self
.unknown_charref(name
)
364 self
.handle_data(chr(n
))
366 # Definition of entities -- derived classes may override
368 {'lt': '<', 'gt': '>', 'amp': '&', 'quot': '"', 'apos': '\''}
370 # Example -- handle entity reference, no need to override
371 def handle_entityref(self
, name
):
372 table
= self
.entitydefs
373 if table
.has_key(name
):
374 self
.handle_data(table
[name
])
376 self
.unknown_entityref(name
)
379 # Example -- handle data, should be overridden
380 def handle_data(self
, data
):
383 # Example -- handle comment, could be overridden
384 def handle_comment(self
, data
):
387 # Example -- handle processing instruction, could be overridden
388 def handle_pi(self
, data
):
391 # To be overridden -- handlers for unknown objects
392 def unknown_starttag(self
, tag
, attrs
): pass
393 def unknown_endtag(self
, tag
): pass
394 def unknown_charref(self
, ref
): pass
395 def unknown_entityref(self
, ref
): pass
398 class TestSGMLParser(SGMLParser
):
400 def __init__(self
, verbose
=0):
402 SGMLParser
.__init
__(self
, verbose
)
404 def handle_data(self
, data
):
405 self
.testdata
= self
.testdata
+ data
406 if len(`self
.testdata`
) >= 70:
413 print 'data:', `data`
415 def handle_comment(self
, data
):
419 r
= r
[:32] + '...' + r
[-32:]
422 def unknown_starttag(self
, tag
, attrs
):
425 print 'start tag: <' + tag
+ '>'
427 print 'start tag: <' + tag
,
428 for name
, value
in attrs
:
429 print name
+ '=' + '"' + value
+ '"',
432 def unknown_endtag(self
, tag
):
434 print 'end tag: </' + tag
+ '>'
436 def unknown_entityref(self
, ref
):
438 print '*** unknown entity ref: &' + ref
+ ';'
440 def unknown_charref(self
, ref
):
442 print '*** unknown char ref: &#' + ref
+ ';'
445 SGMLParser
.close(self
)
449 def test(args
= None):
455 if args
and args
[0] == '-s':
459 klass
= TestSGMLParser
476 if f
is not sys
.stdin
:
485 if __name__
== '__main__':