Class: KPeg::CodeGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/kpeg/code_generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, gram, debug = false) ⇒ CodeGenerator

Returns a new instance of CodeGenerator.



6
7
8
9
10
11
12
13
# File 'lib/kpeg/code_generator.rb', line 6

def initialize(name, gram, debug=false)
  @name = name
  @grammar = gram
  @debug = debug
  @saves = 0
  @output = nil
  @standalone = false
end

Instance Attribute Details

#standaloneObject

Returns the value of attribute standalone.



15
16
17
# File 'lib/kpeg/code_generator.rb', line 15

def standalone
  @standalone
end

Instance Method Details

#handle_ast(code) ⇒ Object



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
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/kpeg/code_generator.rb', line 59

def handle_ast(code)
  output_node = false

  root = @grammar.variables["ast-location"] || "AST"

  methods = []

  vars = @grammar.variables.keys.sort

  vars.each do |name|
    val = @grammar.variables[name]

    if val.index("ast ") == 0
      unless output_node
        code << "\n"
        code << "  module #{root}\n"
        code << "    class Node; end\n"
        output_node = true
      end
      if m = output_ast(name, code, val[4..-1])
        methods << m
      end
    end
  end

  if output_node
    code << "  end\n"
    code << "  module #{root}Construction\n"
    methods.each do |short, name, attrs|
      code << "    def #{short}(#{attrs.join(', ')})\n"
      code << "      #{root}::#{name}.new(#{attrs.join(', ')})\n"
      code << "    end\n"
    end
    code << "  end\n"
    code << "  include #{root}Construction\n"
  end
end

#indentify(code, indent) ⇒ Object



97
98
99
# File 'lib/kpeg/code_generator.rb', line 97

def indentify(code, indent)
  "#{"  " * indent}#{code}"
end

#make(str) ⇒ Object



472
473
474
475
476
477
478
# File 'lib/kpeg/code_generator.rb', line 472

def make(str)
  m = Module.new
  m.module_eval output, "(kpeg parser #{@name})"

  cls = m.const_get(@name)
  cls.new(str)
end

#method_name(name) ⇒ Object



17
18
19
20
# File 'lib/kpeg/code_generator.rb', line 17

def method_name(name)
  name = name.gsub("-","_hyphen_")
  "_#{name}"
end

#outputObject



335
336
337
338
339
340
341
342
343
344
345
# File 'lib/kpeg/code_generator.rb', line 335

def output
  return @output if @output

  code = []

  output_header(code)
  output_grammar(code)
  output_footer(code)

  @output = code.join
end

#output_ast(short, code, description) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/kpeg/code_generator.rb', line 37

def output_ast(short, code, description)
  parser = FormatParser.new description

  # just skip it if it's bad.
  return unless parser.parse "ast_root"

  name, attrs = parser.result

  code << "    class #{name} < Node\n"
  code << "      def initialize(#{attrs.join(', ')})\n"
  attrs.each do |at|
    code << "        @#{at} = #{at}\n"
  end
  code << "      end\n"
  attrs.each do |at|
    code << "      attr_reader :#{at}\n"
  end
  code << "    end\n"

  [short, name, attrs]
end

Output of class end and footer



350
351
352
353
354
355
356
# File 'lib/kpeg/code_generator.rb', line 350

def output_footer(code)
  code << "end\n"

  if footer = @grammar.directives['footer']
    code << footer.action
  end
end

#output_grammar(code) ⇒ Object

Output of grammar and rules



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/kpeg/code_generator.rb', line 361

def output_grammar(code)
  code << "  # :stopdoc:\n"
  handle_ast(code)

  fg = @grammar.foreign_grammars

  if fg.empty?
    if @standalone
      code << "  def setup_foreign_grammar; end\n"
    end
  else
    code << "  def setup_foreign_grammar\n"
    @grammar.foreign_grammars.each do |name, gram|
      code << "    @_grammar_#{name} = #{gram}.new(nil)\n"
    end
    code << "  end\n"
  end

  render = GrammarRenderer.new(@grammar)

  renderings = {}

  @grammar.rule_order.each do |name|
    reset_saves

    rule = @grammar.rules[name]
    io = StringIO.new
    render.render_op io, rule.op

    rend = io.string
    rend.gsub! "\n", " "

    renderings[name] = rend

    code << "\n"
    code << "  # #{name} = #{rend}\n"

    if rule.arguments
      code << "  def #{method_name name}(#{rule.arguments.join(',')})\n"
    else
      code << "  def #{method_name name}\n"
    end

    if @debug
      code << "    puts \"START #{name} @ \#{show_pos}\\n\"\n"
    end

    output_op code, rule.op
    if @debug
      code << "    if _tmp\n"
      code << "      puts \"   OK #{name} @ \#{show_pos}\\n\"\n"
      code << "    else\n"
      code << "      puts \" FAIL #{name} @ \#{show_pos}\\n\"\n"
      code << "    end\n"
    end

    code << "    set_failed_rule :#{method_name name} unless _tmp\n"
    code << "    return _tmp\n"
    code << "  end\n"
  end

  code << "\n  Rules = {}\n"
  @grammar.rule_order.each do |name|
    rend = GrammarRenderer.escape renderings[name], true
    code << "  Rules[:#{method_name name}] = rule_info(\"#{name}\", \"#{rend}\")\n"
  end

  code << "  # :startdoc:\n"
end

#output_header(code) ⇒ Object

Output up to the user-defined setup actions



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/kpeg/code_generator.rb', line 434

def output_header(code)
  if header = @grammar.directives['header']
    code << header.action.strip
    code << "\n"
  end

  pre_class = @grammar.directives['pre-class']

  if @standalone
    if pre_class
      code << pre_class.action.strip
      code << "\n"
    end
    code << "class #{@name}\n"

    cp  = standalone_region("compiled_parser.rb")
    cpi = standalone_region("compiled_parser.rb", "INITIALIZE")
    pp  = standalone_region("position.rb")

    cp.gsub!(/^\s*include Position/, pp)
    code << "  # :stopdoc:\n"
    code << cpi << "\n" unless @grammar.variables['custom_initialize']
    code << cp  << "\n"
    code << "  # :startdoc:\n"
  else
    code << "require 'kpeg/compiled_parser'\n\n"
    if pre_class
      code << pre_class.action.strip
      code << "\n"
    end
    code << "class #{@name} < KPeg::CompiledParser\n"
  end

  @grammar.setup_actions.each do |act|
    code << "\n#{act.action}\n\n"
  end
end

#output_op(code, op, indent = 2) ⇒ Object

Default indent is 4 spaces (indent=2)



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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/kpeg/code_generator.rb', line 102

def output_op(code, op, indent=2)
  case op
  when Dot
    code << indentify("_tmp = get_byte\n", indent)
  when LiteralString
    code << indentify("_tmp = match_string(#{op.string.dump})\n", indent)
  when LiteralRegexp
    if op.regexp.respond_to?(:kcode)
      lang = op.regexp.kcode.to_s[0,1]
    else
      # Let default ruby string handling figure it out
      lang = ""
    end
    code << indentify("_tmp = scan(/\\G#{op.regexp}/#{lang})\n", indent)
  when CharRange
    ss = save()
    if op.start.bytesize == 1 and op.fin.bytesize == 1
      code << indentify("#{ss} = self.pos\n", indent)
      code << indentify("_tmp = get_byte\n", indent)
      code << indentify("if _tmp\n", indent)

      if op.start.respond_to? :getbyte
        left  = op.start.getbyte 0
        right = op.fin.getbyte 0
      else
        left  = op.start[0]
        right = op.fin[0]
      end

      code << indentify("  unless _tmp >= #{left} and _tmp <= #{right}\n", indent)
      code << indentify("    self.pos = #{ss}\n", indent)
      code << indentify("    _tmp = nil\n", indent)
      code << indentify("  end\n", indent)
      code << indentify("end\n", indent)
    else
      raise "Unsupported char range - #{op.inspect}"
    end
  when Choice
    ss = save()
    code << "\n"
    code << indentify("#{ss} = self.pos\n", indent)
    code << indentify("while true # choice\n", indent)
    op.ops.each_with_index do |n,idx|
      output_op code, n, (indent+1)

      code << indentify("  break if _tmp\n", indent)
      code << indentify("  self.pos = #{ss}\n", indent)
      if idx == op.ops.size - 1
        code << indentify("  break\n", indent)
      end
    end
    code << indentify("end # end choice\n\n", indent)
  when Multiple
    ss = save()
    if op.min == 0 and op.max == 1
      code << indentify("#{ss} = self.pos\n", indent)
      output_op code, op.op, indent
      if op.save_values
        code << indentify("@result = nil unless _tmp\n", indent)
      end
      code << indentify("unless _tmp\n", indent)
      code << indentify("  _tmp = true\n", indent)
      code << indentify("  self.pos = #{ss}\n", indent)
      code << indentify("end\n", indent)
    elsif op.min == 0 and !op.max
      if op.save_values
        code << indentify("_ary = []\n", indent)
      end

      code << indentify("while true\n", indent)
      output_op code, op.op, (indent+1)
      if op.save_values
        code << indentify("  _ary << @result if _tmp\n", indent)
      end
      code << indentify("  break unless _tmp\n", indent)
      code << indentify("end\n", indent)
      code << indentify("_tmp = true\n", indent)

      if op.save_values
        code << indentify("@result = _ary\n", indent)
      end

    elsif op.min == 1 and !op.max
      code << indentify("#{ss} = self.pos\n", indent)
      if op.save_values
        code << indentify("_ary = []\n", indent)
      end
      output_op code, op.op, indent
      code << indentify("if _tmp\n", indent)
      if op.save_values
        code << indentify("  _ary << @result\n", indent)
      end
      code << indentify("  while true\n", indent)
      output_op code, op.op, (indent+2)
      if op.save_values
        code << indentify("    _ary << @result if _tmp\n", indent)
      end
      code << indentify("    break unless _tmp\n", indent)
      code << indentify("  end\n", indent)
      code << indentify("  _tmp = true\n", indent)
      if op.save_values
        code << indentify("  @result = _ary\n", indent)
      end
      code << indentify("else\n", indent)
      code << indentify("  self.pos = #{ss}\n", indent)
      code << indentify("end\n", indent)
    else
      code << indentify("#{ss} = self.pos\n", indent)
      code << indentify("_count = 0\n", indent)
      code << indentify("while true\n", indent)
      output_op code, op.op, (indent+1)
      code << indentify("  if _tmp\n", indent)
      code << indentify("    _count += 1\n", indent)
      code << indentify("    break if _count == #{op.max}\n", indent)
      code << indentify("  else\n", indent)
      code << indentify("    break\n", indent)
      code << indentify("  end\n", indent)
      code << indentify("end\n", indent)
      code << indentify("if _count >= #{op.min}\n", indent)
      code << indentify("  _tmp = true\n", indent)
      code << indentify("else\n", indent)
      code << indentify("  self.pos = #{ss}\n", indent)
      code << indentify("  _tmp = nil\n", indent)
      code << indentify("end\n", indent)
    end

  when Sequence
    ss = save()
    code << "\n"
    code << indentify("#{ss} = self.pos\n", indent)
    code << indentify("while true # sequence\n", indent)
    op.ops.each_with_index do |n, idx|
      output_op code, n, (indent+1)

      if idx == op.ops.size - 1
        code << indentify("  unless _tmp\n", indent)
        code << indentify("    self.pos = #{ss}\n", indent)
        code << indentify("  end\n", indent)
        code << indentify("  break\n", indent)
      else
        code << indentify("  unless _tmp\n", indent)
        code << indentify("    self.pos = #{ss}\n", indent)
        code << indentify("    break\n", indent)
        code << indentify("  end\n", indent)
      end
    end
    code << indentify("end # end sequence\n\n", indent)
  when AndPredicate
    ss = save()
    code << indentify("#{ss} = self.pos\n", indent)
    if op.op.kind_of? Action
      code << indentify("_tmp = begin; #{op.op.action}; end\n", indent)
    else
      output_op code, op.op, indent
    end
    code << indentify("self.pos = #{ss}\n", indent)
  when NotPredicate
    ss = save()
    code << indentify("#{ss} = self.pos\n", indent)
    if op.op.kind_of? Action
      code << indentify("_tmp = begin; #{op.op.action}; end\n", indent)
    else
      output_op code, op.op, indent
    end
    code << indentify("_tmp = _tmp ? nil : true\n", indent)
    code << indentify("self.pos = #{ss}\n", indent)
  when RuleReference
    if op.arguments
      code << indentify("_tmp = apply_with_args(:#{method_name op.rule_name}, #{op.arguments[1..-2]})\n", indent)
    else
      code << indentify("_tmp = apply(:#{method_name op.rule_name})\n", indent)
    end
  when InvokeRule
    if op.arguments
      code << indentify("_tmp = #{method_name op.rule_name}#{op.arguments}\n", indent)
    else
      code << indentify("_tmp = #{method_name op.rule_name}()\n", indent)
    end
  when ForeignInvokeRule
    if op.arguments
      code << indentify("_tmp = @_grammar_#{op.grammar_name}.external_invoke(self, :#{method_name op.rule_name}, #{op.arguments[1..-2]})\n", indent)
    else
      code << indentify("_tmp = @_grammar_#{op.grammar_name}.external_invoke(self, :#{method_name op.rule_name})\n", indent)
    end
  when Tag
    if op.tag_name and !op.tag_name.empty?
      output_op code, op.op, indent
      code << indentify("#{op.tag_name} = @result\n", indent)
    else
      output_op code, op.op, indent
    end
  when Action
    code << indentify("@result = begin; ", indent)
    code << op.action << "; end\n"
    if @debug
      code << indentify("puts \"   => \" #{op.action.dump} \" => \#{@result.inspect} \\n\"\n", indent)
    end
    code << indentify("_tmp = true\n", indent)
  when Collect
    code << indentify("_text_start = self.pos\n", indent)
    output_op code, op.op, indent
    code << indentify("if _tmp\n", indent)
    code << indentify("  text = get_text(_text_start)\n", indent)
    code << indentify("end\n", indent)
  when Bounds
    code << indentify("_bounds_start = self.pos\n", indent)
    output_op code, op.op, indent
    code << indentify("if _tmp\n", indent)
    code << indentify("  bounds = [_bounds_start, self.pos]\n", indent)
    code << indentify("end\n", indent)
  else
    raise "Unknown op - #{op.class}"
  end
end

#parse(str) ⇒ Object



480
481
482
# File 'lib/kpeg/code_generator.rb', line 480

def parse(str)
  make(str).parse
end

#reset_savesObject



33
34
35
# File 'lib/kpeg/code_generator.rb', line 33

def reset_saves
  @saves = 0
end

#saveObject



22
23
24
25
26
27
28
29
30
31
# File 'lib/kpeg/code_generator.rb', line 22

def save
  if @saves == 0
    str = "_save"
  else
    str = "_save#{@saves}"
  end

  @saves += 1
  str
end

#standalone_region(path, marker = "STANDALONE") ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/kpeg/code_generator.rb', line 317

def standalone_region(path, marker = "STANDALONE")
  expanded_path = File.expand_path("../#{path}", __FILE__)
  cp = File.read(expanded_path)

  start_marker = "# #{marker} START"
  end_marker   = /^\s*# #{Regexp.escape marker} END/

  start = cp.index(start_marker) + start_marker.length + 1 # \n
  fin   = cp.index(end_marker)

  unless start and fin
    abort("#{marker} boundaries in #{path} missing " \
          "for standalone generation")
  end

  cp[start..fin]
end