Class: Renshi::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/renshi/parser.rb

Overview

The Renshi parser tries to respect speed without complexity. It builds a set of instructions within the document, which are finally compiled into Ruby.

Constant Summary collapse

STRING_END =

maybe replace this with a funky unicode char

"_R_END"
STRING_START =

maybe replace this with a funky unicode char

"_R_START"
BUFFER_CONCAT_OPEN =
"@output_buffer.concat(\""
BUFFER_CONCAT_CLOSE =
"\");"
NEW_LINE =
"@output_buffer.concat('\n');"
INSTRUCTION_START =
"_R_INSTR_IDX_START_"
INSTRUCTION_END =
"_R_INSTR_IDX_END_"
XML_LT =

these symbols cannot be normally escaped, as we need to differentiate between &lt; as an escaped string, to be left in the document, and < as a boolean operator

"^R_LT^"
XML_GT =
"^R_GT^"
XML_AMP =
"^R_AMP^"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nokogiri_node) ⇒ Parser

Returns a new instance of Parser.



39
40
41
42
43
# File 'lib/renshi/parser.rb', line 39

def initialize(nokogiri_node)
  @doc = nokogiri_node
  @instructions = []
  @instr_idx = 0
end

Class Method Details

.parse(xhtml) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/renshi/parser.rb', line 22

def self.parse(xhtml)
  if xhtml.index("<head>") #better way to detect the full HTML document structure?
    doc = Nokogiri::HTML::Document.parse(xhtml)
  else
    doc = Nokogiri::HTML.fragment(xhtml)
  end
  
  parser = self.new(doc)
  out = parser.parse
  
  if ENV['RENSHI_SHOW_SRC']
    puts "Renshi src: \n#{out}"
  end
  
  return out
end

Instance Method Details

#close_of_phrase_ending_with(char, text, idx) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
# File 'lib/renshi/parser.rb', line 168

def close_of_phrase_ending_with(char, text, idx)
  phrase_end = (text[(idx + 1)..-1].index("$")) 
  
  if phrase_end.nil?
    phrase_end = text.length 
  else
    phrase_end = phrase_end + idx
  end
  closing_brace_idx = text[idx...phrase_end].rindex(char) + idx
  return closing_brace_idx
end

#compile(text) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/renshi/parser.rb', line 93

def compile(text)
  return if text.nil?
  
  idx = text.index("$")
  return text if idx.nil?
  
  bits = []
  
  if idx != 0
    before_str = text[0..(idx -1)] 
     bits << escape_quot_mark(before_str)
  end
  
  while idx != nil do
    next_char = text[(idx + 1)..(idx + 1)]

    if next_char == " "          
      raise SyntaxError, "Floating $ - use $$ to output '$': #{text[(idx +1)..-1]}", caller
    elsif next_char == "(" 
      #this may be jquery, etc. $(...) 
      end_statement_idx = (idx + 2)
      bits << text[idx..(idx + 1)]    
    elsif next_char == "$"
      #an escaped $ - i.e. '$$'
      end_statement_idx = (idx + 2)
      bits << "$"
      
      #${...}
    elsif next_char == "{"
      begin
        #scan for the next $ in this block
        closing_brace_idx = close_of_phrase_ending_with("}", text, idx)
        statement_str = text[(idx + 2)..(closing_brace_idx -1)]
        statement = Renshi::Statement.new(statement_str)
        bits << statement.compile_to_print!
        end_statement_idx = closing_brace_idx + 1
      rescue StandardError
        raise SyntaxError, "No closing brace: #{text}", caller
      end
      
      #$[...]
    elsif next_char == "["
      begin
        # closing_brace_idx = text.rindex("]")
        closing_brace_idx = close_of_phrase_ending_with("]", text, idx)
        statement_str = text[(idx + 2)..(closing_brace_idx -1)]
        statement = Renshi::Statement.new(statement_str)
        bits << statement.compile_to_expression!
        end_statement_idx = closing_brace_idx + 1
      rescue StandardError
        raise SyntaxError, "No closing bracket: #{text}", caller
      end          
    else #$foo
      #divide with a delimiter for anything which is not a name character - alpa-numeric and underscore
      words = text[(idx +1)..-1].split(/[^\w."'{}()+=*\/\-@\[\]:?!%]/)
      words[0] = "'$'" if words[0] == "$"
      statement_str = words.first
      statement = Statement.new(statement_str)
      bits << statement.compile_to_print!
      end_statement_idx = (words.first.length) + 1 + idx
    end

    next_statement_idx = text.index("$", end_statement_idx)
    
    if next_statement_idx
      gap = text[end_statement_idx..(next_statement_idx -1)]
      bits << escape_quot_mark(gap)
    else
      bits << escape_quot_mark(text[end_statement_idx..-1])
    end
    idx = next_statement_idx
  end       
  return bits.join
end

#compile_print_flags(str) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/renshi/parser.rb', line 190

def compile_print_flags(str)
  #now we parse for RENSHI::STRING_END and RENSHI::STRING_START
  #and ensure natural strings are buffered
  str.gsub!("\"", "\\\"")
  str.gsub!(XML_GT, ">")
  str.gsub!(XML_LT, "<")
  str.gsub!(XML_AMP, "&")
  
  #restore instructions in the string      
  bits = []
  str.split(INSTRUCTION_START).each do |bit|
    instr_end = bit.index(INSTRUCTION_END)
    if instr_end
      index = bit[0...instr_end] 
      instruction = @instructions[index.to_i]
      
      bit.gsub!("#{index}#{INSTRUCTION_END}", instruction)
    end
    
    bits << bit
  end
  
  str = bits.join
  
  str.gsub!(STRING_END, BUFFER_CONCAT_CLOSE)
  str.gsub!(STRING_START, BUFFER_CONCAT_OPEN)

  return str
end

#compile_to_buffer(str) ⇒ Object



184
185
186
187
188
# File 'lib/renshi/parser.rb', line 184

def compile_to_buffer(str)
  compiled = "@output_buffer ='';" << BUFFER_CONCAT_OPEN      
  str = compile_print_flags(str)    
  compiled = "#{compiled}#{str}" << BUFFER_CONCAT_CLOSE
end

#escape_quot_mark(str) ⇒ Object



180
181
182
# File 'lib/renshi/parser.rb', line 180

def escape_quot_mark(str)
  return (str == '"' ? '\"' : str)
end

#parseObject



45
46
47
48
49
50
51
52
53
# File 'lib/renshi/parser.rb', line 45

def parse
  @doc.children.each do |node|
   transform_node(node)
  end      

  inner_html = @doc.inner_html
  compiled = compile_to_buffer(inner_html) if inner_html
  return compiled
end

#store_instruction_for_buffer(compiled) ⇒ Object



86
87
88
89
90
91
# File 'lib/renshi/parser.rb', line 86

def store_instruction_for_buffer(compiled)
  @instructions << compiled
  key = "#{INSTRUCTION_START}#{@instr_idx}#{INSTRUCTION_END}"
  @instr_idx = @instr_idx + 1
  return key
end

#transform_node(node) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/renshi/parser.rb', line 55

def transform_node(node)
  if node.attributes
    expressions = node.commands
    for expression in expressions 
      AttributeExpressions.perform_expression(node, expression)
    end
  end
  
  #compile text in attribute values, e.g. <div id="foo$i>"
  if node.attributes()
    for attribute in node.attributes()
      compiled = compile(attribute[1].to_s)
      if compiled
        key = store_instruction_for_buffer(compiled)
        node[attribute[0]]= key      
      end
    end        
  end
  
  #compile text in nodes, e.g. <p>*</p>
  if node.text?
    compiled = compile(node.text)
    if compiled
      node.content = store_instruction_for_buffer(compiled)
    end
  end

  node.children.each {|child| transform_node(child)}
end