1 require 'rexml/parseexception'
2 require 'rexml/undefinednamespaceexception'
8 # = Using the Pull Parser
9 # <em>This API is experimental, and subject to change.</em>
10 # parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
11 # while parser.has_next?
13 # puts res[1]['att'] if res.start_tag? and res[0] == 'b'
15 # See the PullEvent class for information on the content of the results.
16 # The data is identical to the arguments passed for the various events to
17 # the StreamListener API.
20 # parser = PullParser.new( "<a>BAD DOCUMENT" )
21 # while parser.has_next?
23 # raise res[1] if res.error?
26 # Nat Price gave me some good ideas for the API.
28 NCNAME_STR= '[\w:][\-\w\d.]*'
29 NAME_STR= "(?:(#{NCNAME_STR}):)?(#{NCNAME_STR})"
30 UNAME_STR= "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
32 NAMECHAR = '[\-\w\d\.:]'
33 NAME = "([\\w:]#{NAMECHAR}*)"
34 NMTOKEN = "(?:#{NAMECHAR})+"
35 NMTOKENS = "#{NMTOKEN}(\\s+#{NMTOKEN})*"
36 REFERENCE = "(?:&#{NAME};|&#\\d+;|&#x[0-9a-fA-F]+;)"
37 REFERENCE_RE = /#{REFERENCE}/
39 DOCTYPE_START = /\A\s*<!DOCTYPE\s/um
40 DOCTYPE_PATTERN = /\s*<!DOCTYPE\s+(.*?)(\[|>)/um
41 ATTRIBUTE_PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\4/um
42 COMMENT_START = /\A<!--/u
43 COMMENT_PATTERN = /<!--(.*?)-->/um
44 CDATA_START = /\A<!\[CDATA\[/u
45 CDATA_END = /^\s*\]\s*>/um
46 CDATA_PATTERN = /<!\[CDATA\[(.*?)\]\]>/um
47 XMLDECL_START = /\A<\?xml\s/u;
48 XMLDECL_PATTERN = /<\?xml\s+(.*?)\?>/um
49 INSTRUCTION_START = /\A<\?/u
50 INSTRUCTION_PATTERN = /<\?(.*?)(\s+.*?)?\?>/um
51 TAG_MATCH = /^<((?>#{NAME_STR}))\s*((?>\s+#{UNAME_STR}\s*=\s*(["']).*?\5)*)\s*(\/)?>/um
52 CLOSE_MATCH = /^\s*<\/(#{NAME_STR})\s*>/um
54 VERSION = /\bversion\s*=\s*["'](.*?)['"]/um
55 ENCODING = /\bencoding\s*=\s*["'](.*?)['"]/um
56 STANDALONE = /\bstandalone\s*=\s["'](.*?)['"]/um
58 ENTITY_START = /^\s*<!ENTITY/
59 IDENTITY = /^([!\*\w\-]+)(\s+#{NCNAME_STR})?(\s+["'](.*?)['"])?(\s+['"](.*?)["'])?/u
60 ELEMENTDECL_START = /^\s*<!ELEMENT/um
61 ELEMENTDECL_PATTERN = /^\s*(<!ELEMENT.*?)>/um
62 SYSTEMENTITY = /^\s*(%.*?;)\s*$/um
63 ENUMERATION = "\\(\\s*#{NMTOKEN}(?:\\s*\\|\\s*#{NMTOKEN})*\\s*\\)"
64 NOTATIONTYPE = "NOTATION\\s+\\(\\s*#{NAME}(?:\\s*\\|\\s*#{NAME})*\\s*\\)"
65 ENUMERATEDTYPE = "(?:(?:#{NOTATIONTYPE})|(?:#{ENUMERATION}))"
66 ATTTYPE = "(CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|#{ENUMERATEDTYPE})"
67 ATTVALUE = "(?:\"((?:[^<&\"]|#{REFERENCE})*)\")|(?:'((?:[^<&']|#{REFERENCE})*)')"
68 DEFAULTDECL = "(#REQUIRED|#IMPLIED|(?:(#FIXED\\s+)?#{ATTVALUE}))"
69 ATTDEF = "\\s+#{NAME}\\s+#{ATTTYPE}\\s+#{DEFAULTDECL}"
70 ATTDEF_RE = /#{ATTDEF}/
71 ATTLISTDECL_START = /^\s*<!ATTLIST/um
72 ATTLISTDECL_PATTERN = /^\s*<!ATTLIST\s+#{NAME}(?:#{ATTDEF})*\s*>/um
73 NOTATIONDECL_START = /^\s*<!NOTATION/um
74 PUBLIC = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(PUBLIC)\s+(["'])(.*?)\3(?:\s+(["'])(.*?)\5)?\s*>/um
75 SYSTEM = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(SYSTEM)\s+(["'])(.*?)\3\s*>/um
77 TEXT_PATTERN = /\A([^<]*)/um
80 PUBIDCHAR = "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#"
81 SYSTEMLITERAL = %Q{((?:"[^"]*")|(?:'[^']*'))}
82 PUBIDLITERAL = %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
83 EXTERNALID = "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
84 NDATADECL = "\\s+NDATA\\s+#{NAME}"
85 PEREFERENCE = "%#{NAME};"
86 ENTITYVALUE = %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
87 PEDEF = "(?:#{ENTITYVALUE}|#{EXTERNALID})"
88 ENTITYDEF = "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
89 PEDECL = "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
90 GEDECL = "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
91 ENTITYDECL = /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
93 EREFERENCE = /&(?!#{NAME};)/
96 'gt' => [/>/, '>', '>', />/],
97 'lt' => [/</, '<', '<', /</],
98 'quot' => [/"/, '"', '"', /"/],
99 "apos" => [/'/, "'", "'", /'/]
103 ######################################################################
104 # These are patterns to identify common markup errors, to make the
105 # error messages more informative.
106 ######################################################################
107 MISSING_ATTRIBUTE_QUOTES = /^<#{NAME_STR}\s+#{NAME_STR}\s*=\s*[^"']/um
109 def initialize( source )
113 def add_listener( listener )
114 if !defined?(@listeners) or !@listeners
117 alias :_old_pull :pull
120 @listeners.each do |listener|
121 listener.receive event
127 @listeners << listener
132 def stream=( source )
133 @source = SourceFactory.create_from( source )
135 @document_status = nil
143 if @source.respond_to? :position
151 # Returns true if there are no more events
153 return (@source.empty? and @stack.empty?)
156 # Returns true if there are more events. Synonymous with !empty?
158 return !(@source.empty? and @stack.empty?)
161 # Push an event back on the head of the stream. This method
162 # has (theoretically) infinite depth.
164 @stack.unshift(token)
167 # Peek at the +depth+ event in the stack. The first element on the stack
168 # is at depth 0. If +depth+ is -1, will parse to the end of the input
169 # stream and return the last event, which is always :end_document.
170 # Be aware that this causes the stream to be parsed up to the +depth+
171 # event, so you can effectively pre-parse the entire document (pull the
172 # entire thing into memory) using this method.
174 raise %Q[Illegal argument "#{depth}"] if depth < -1
177 temp.push(pull()) until empty?
179 while @stack.size+temp.size < depth+1
183 @stack += temp if temp.size > 0
187 # Returns the next event. This is a +PullEvent+ object.
190 x, @closed = @closed, nil
191 return [ :end_element, x ]
193 return [ :end_document ] if empty?
194 return @stack.shift if @stack.size > 0
195 #STDERR.puts @source.encoding
196 @source.read if @source.buffer.size<2
197 #STDERR.puts "BUFFER = #{@source.buffer.inspect}"
198 if @document_status == nil
199 #@source.consume( /^\s*/um )
200 word = @source.match( /^((?:\s+)|(?:<[^>]*>))/um )
201 word = word[1] unless word.nil?
202 #STDERR.puts "WORD = #{word.inspect}"
205 return [ :comment, @source.match( COMMENT_PATTERN, true )[1] ]
207 #STDERR.puts "XMLDECL"
208 results = @source.match( XMLDECL_PATTERN, true )[1]
209 version = VERSION.match( results )
210 version = version[1] unless version.nil?
211 encoding = ENCODING.match(results)
212 encoding = encoding[1] unless encoding.nil?
213 @source.encoding = encoding
214 standalone = STANDALONE.match(results)
215 standalone = standalone[1] unless standalone.nil?
216 return [ :xmldecl, version, encoding, standalone ]
217 when INSTRUCTION_START
218 return [ :processing_instruction, *@source.match(INSTRUCTION_PATTERN, true)[1,2] ]
220 md = @source.match( DOCTYPE_PATTERN, true )
221 @nsstack.unshift(curr_ns=Set.new)
226 raise REXML::ParseException.new("DOCTYPE is missing a name") if name.nil?
227 pub_sys = $2.nil? ? nil : $2.strip
228 long_name = $4.nil? ? nil : $4.strip
229 uri = $6.nil? ? nil : $6.strip
230 args = [ :start_doctype, name, pub_sys, long_name, uri ]
232 @document_status = :after_doctype
233 @source.read if @source.buffer.size<2
234 md = @source.match(/^\s*/um, true)
235 @stack << [ :end_doctype ]
237 @document_status = :in_doctype
242 @document_status = :after_doctype
243 @source.read if @source.buffer.size<2
244 md = @source.match(/\s*/um, true)
247 if @document_status == :in_doctype
248 md = @source.match(/\s*(.*?>)/um)
251 match = @source.match( SYSTEMENTITY, true )[1]
252 return [ :externalentity, match ]
254 when ELEMENTDECL_START
255 return [ :elementdecl, @source.match( ELEMENTDECL_PATTERN, true )[1] ]
258 match = @source.match( ENTITYDECL, true ).to_a.compact
259 match[0] = :entitydecl
265 # Now we have to sort out what kind of entity reference this is
266 if match[2] == 'SYSTEM'
268 match[3] = match[3][1..-2] # PUBID
269 match.delete_at(4) if match.size > 4 # Chop out NDATA decl
270 # match is [ :entity, name, SYSTEM, pubid(, ndata)? ]
271 elsif match[2] == 'PUBLIC'
273 match[3] = match[3][1..-2] # PUBID
274 match[4] = match[4][1..-2] # HREF
275 # match is [ :entity, name, PUBLIC, pubid, href ]
277 match[2] = match[2][1..-2]
278 match.pop if match.size == 4
279 # match is [ :entity, name, value ]
283 when ATTLISTDECL_START
284 md = @source.match( ATTLISTDECL_PATTERN, true )
285 raise REXML::ParseException.new( "Bad ATTLIST declaration!", @source ) if md.nil?
290 values = md[0].scan( ATTDEF_RE )
291 values.each do |attdef|
292 unless attdef[3] == "#IMPLIED"
295 val = attdef[4] if val == "#FIXED "
296 pairs[attdef[0]] = val
297 if attdef[0] =~ /^xmlns:(.*)/
302 return [ :attlistdecl, element, pairs, contents ]
303 when NOTATIONDECL_START
305 if @source.match( PUBLIC )
306 md = @source.match( PUBLIC, true )
307 vals = [md[1],md[2],md[4],md[6]]
308 elsif @source.match( SYSTEM )
309 md = @source.match( SYSTEM, true )
310 vals = [md[1],md[2],nil,md[4]]
312 raise REXML::ParseException.new( "error parsing notation: no matching pattern", @source )
314 return [ :notationdecl, *vals ]
316 @document_status = :after_doctype
317 @source.match( CDATA_END, true )
318 return [ :end_doctype ]
322 if @source.buffer[0] == ?<
323 if @source.buffer[1] == ?/
326 #md = @source.match_to_consume( '>', CLOSE_MATCH)
327 md = @source.match( CLOSE_MATCH, true )
328 raise REXML::ParseException.new( "Missing end tag for "+
329 "'#{last_tag}' (got \"#{md[1]}\")",
330 @source) unless last_tag == md[1]
331 return [ :end_element, last_tag ]
332 elsif @source.buffer[1] == ?!
333 md = @source.match(/\A(\s*[^>]*>)/um)
334 #STDERR.puts "SOURCE BUFFER = #{source.buffer}, #{source.buffer.size}"
335 raise REXML::ParseException.new("Malformed node", @source) unless md
337 md = @source.match( COMMENT_PATTERN, true )
338 return [ :comment, md[1] ] if md
340 md = @source.match( CDATA_PATTERN, true )
341 return [ :cdata, md[1] ] if md
343 raise REXML::ParseException.new( "Declarations can only occur "+
344 "in the doctype declaration.", @source)
345 elsif @source.buffer[1] == ??
346 md = @source.match( INSTRUCTION_PATTERN, true )
347 return [ :processing_instruction, md[1], md[2] ] if md
348 raise REXML::ParseException.new( "Bad instruction declaration",
352 md = @source.match(TAG_MATCH, true)
354 # Check for missing attribute quotes
355 raise REXML::ParseException.new("missing attribute quote", @source) if @source.match(MISSING_ATTRIBUTE_QUOTES )
356 raise REXML::ParseException.new("malformed XML: missing tag start", @source)
360 prefixes << md[2] if md[2]
361 @nsstack.unshift(curr_ns=Set.new)
363 attrs = md[4].scan( ATTRIBUTE_PATTERN )
364 raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0
365 attrs.each { |a,b,c,d,e|
368 if d != "http://www.w3.org/XML/1998/namespace"
369 msg = "The 'xml' prefix must not be bound to any other namespace "+
370 "(http://www.w3.org/TR/REC-xml-names/#ns-decl)"
371 raise REXML::ParseException.new( msg, @source, self )
374 msg = "The 'xmlns' prefix must not be declared "+
375 "(http://www.w3.org/TR/REC-xml-names/#ns-decl)"
376 raise REXML::ParseException.new( msg, @source, self)
380 prefixes << b unless b == "xml"
386 # Verify that all of the prefixes have been defined
387 for prefix in prefixes
388 unless @nsstack.find{|k| k.member?(prefix)}
389 raise UndefinedNamespaceException.new(prefix,@source,self)
399 return [ :start_element, md[1], attributes ]
402 md = @source.match( TEXT_PATTERN, true )
404 @source.match( /(\s+)/, true )
406 #STDERR.puts "GOT #{md[1].inspect}" unless md[0].length == 0
407 #return [ :text, "" ] if md[0].length == 0
408 # unnormalized = Text::unnormalize( md[1], self )
409 # return PullEvent.new( :text, md[1], unnormalized )
410 return [ :text, md[1] ]
412 rescue REXML::UndefinedNamespaceException
414 rescue REXML::ParseException
416 rescue Exception, NameError => error
417 raise REXML::ParseException.new( "Exception parsing",
418 @source, self, (error ? error : $!) )
423 def entity( reference, entities )
425 value = entities[ reference ] if entities
427 value = DEFAULT_ENTITIES[ reference ]
428 value = value[2] if value
430 unnormalize( value, entities ) if value
433 # Escapes all possible entities
434 def normalize( input, entities=nil, entity_filter=nil )
436 # Doing it like this rather than in a loop improves the speed
437 copy.gsub!( EREFERENCE, '&' )
438 entities.each do |key, value|
439 copy.gsub!( value, "&#{key};" ) unless entity_filter and
440 entity_filter.include?(entity)
442 copy.gsub!( EREFERENCE, '&' )
443 DEFAULT_ENTITIES.each do |key, value|
444 copy.gsub!( value[3], value[1] )
449 # Unescapes all possible entities
450 def unnormalize( string, entities=nil, filter=nil )
452 rv.gsub!( /\r\n?/, "\n" )
453 matches = rv.scan( REFERENCE_RE )
454 return rv if matches.size == 0
455 rv.gsub!( /�*((?:\d+)|(?:x[a-fA-F0-9]+));/ ) {|m|
457 m = "0#{m}" if m[0] == ?x
458 [Integer(m)].pack('U*')
460 matches.collect!{|x|x[0]}.compact!
462 matches.each do |entity_reference|
463 unless filter and filter.include?(entity_reference)
464 entity_value = entity( entity_reference, entities )
466 re = /&#{entity_reference};/
467 rv.gsub!( re, entity_value )
471 matches.each do |entity_reference|
472 unless filter and filter.include?(entity_reference)
473 er = DEFAULT_ENTITIES[entity_reference]
474 rv.gsub!( er[0], er[2] ) if er
477 rv.gsub!( /&/, '&' )
490 when :processing_instruction