# Copyright, 2012, by Samuel G. D. Williams. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'utopia/tag' require 'trenni/parser' require 'trenni/strings' module Utopia module Middleware class Content class Processor def self.parse_xml(xml_data, delegate) processor = self.new(delegate) processor.parse(xml_data) end class UnbalancedTagError < StandardError def initialize(scanner, start_position, current_tag, closing_tag) @scanner = scanner @start_position = start_position @current_tag = current_tag @closing_tag = closing_tag @starting_line = @scanner.calculate_line_number(@start_pos) @ending_line = @scanner.calculate_line_number end def to_s "Unbalanced Tag #{@current_tag}. " \ "Line #{@starting_line[0]}: #{@starting_line[4]} has been closed by #{@closing_tag} on line #{@ending_line[0]}: #{@ending_line[4]}" end end def initialize(delegate) @delegate = delegate @stack = [] @parser = Trenni::Parser.new(self) end def parse(input) @parser.parse(input) end def begin_parse(scanner) @scanner = scanner end def text(text) @delegate.cdata(text) end def cdata(text) @delegate.cdata(Trenni::Strings::to_html(text)) end def comment(text) @delegate.cdata("") end def begin_tag(tag_name, begin_tag_type) if begin_tag_type == :opened @stack << [Tag.new(tag_name, {}), @scanner.pos] else current_tag, current_position = @stack.pop if (tag_name != current_tag.name) raise UnbalancedTagError.new(@scanner, current_position, current_tag.name, tag_name) end @delegate.tag_end(current_tag) end end def finish_tag(begin_tag_type, end_tag_type) if begin_tag_type == :opened # <... if end_tag_type == :closed # <.../> cur, pos = @stack.pop cur.closed = true @delegate.tag_complete(cur) elsif end_tag_type == :opened # <...> cur, pos = @stack.last @delegate.tag_begin(cur) end end end def attribute(name, value) @stack.last[0].attributes[name] = value end def instruction(content) cdata("") end end end end end