Class: NCPP::Interpreter

Inherits:
Object
  • Object
show all
Defined in:
lib/ncpp/interpreter.rb

Overview

NCPP language interpreter

Instance Method Summary collapse

Constructor Details

#initialize(cmd_prefix = COMMAND_PREFIX, extra_cmds = {}, extra_vars = {}, safe: false, puritan: false, no_cache: false, cmd_cache: {}) ⇒ Interpreter

Returns a new instance of Interpreter.



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/ncpp/interpreter.rb', line 190

def initialize(cmd_prefix = COMMAND_PREFIX, extra_cmds = {}, extra_vars = {}, safe: false, puritan: false, 
               no_cache: false, cmd_cache: {})

  @parser = Parser.new(cmd_prefix: cmd_prefix)
  @transformer = Transformer.new

  @COMMAND_PREFIX = cmd_prefix

  @safe_mode = safe
  @puritan_mode = puritan

  @commands = commands.merge(CORE_COMMANDS).merge(extra_cmds)

  @variables = {}
  @variables.merge!(variables) unless $rom.nil?
  @variables.merge!(CORE_VARIABLES).merge!(extra_vars)

  @added_commands = extra_cmds.keys.to_set
  @added_variables = extra_vars.keys.to_set

  @out_stack = []
  @command_cache = no_cache ? nil : cmd_cache
end

Instance Method Details

#call(cmd_name, block_or_proc, *args) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
# File 'lib/ncpp/interpreter.rb', line 259

def call(cmd_name, block_or_proc, *args)
  if !block_or_proc.return_type.nil? && !@command_cache.nil? && block_or_proc.pure?
    return @command_cache[cmd_name][args] if @command_cache.has_key?(cmd_name) && @command_cache[cmd_name].has_key?(args)
    result = block_or_proc.call(*args)
    @command_cache[cmd_name] ||= {}
    @command_cache[cmd_name][args] = result
    result
  else
    block_or_proc.call(*args)
  end
end

#commandsObject

Interpreter environment-specific commands



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
84
85
86
87
88
89
90
91
92
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
167
168
169
170
171
172
173
174
175
176
# File 'lib/ncpp/interpreter.rb', line 13

def commands
  CommandRegistry.new({
    put: ->(x, on_new_line=true) {
      if on_new_line
        @out_stack << x.to_s
      else
        @out_stack[-1] << x.to_s
      end
    }.impure
      .describe(
      "Puts the value of the given argument as a String on the end of the out-stack; but if 'on_new_line' is true "\
      "(it's false by default), it's added to the end of the last stack entry."
    ),

    get_out_stack: -> { @out_stack }.returns(Array).impure
      .describe('Gets the out-stack.'),

    clear_out_stack: -> { @out_stack.clear }.impure
      .describe('Clears the out-stack.'),

    ruby: ->(code_str) {
      raise "The 'ruby' command can't be run in safe mode" if @safe_mode
      eval(code_str, get_binding)
    }.returns(Object).impure
      .describe('Evaluates the given String as Ruby code.'),

    eval: ->(expr_str) { eval_str(expr_str) }.returns(Object).impure
      .describe('Evaluates the given String as an NCPP expression.'),

    do_command: ->(cmd_str, *args) { call(cmd_str,get_command(cmd_str),*args) }.returns(Object)
      .describe('Calls the command named in the given String.'),

    map_to_command: ->(arr, cmd_str, *args) {
      Utils.array_check(arr,'map_to_command')
      cmd = get_command(cmd_str)
      arr.map {|element| args.nil? ? call(cmd_str,cmd,element) : call(cmd_str,cmd,element,*args) }
    }.returns(Array)
      .describe('Calls the command named in the String given on each element in the provided Array.'),

    inject_in_command: ->(arr, init_val, cmd_str) {
      Utils.array_check(arr, 'inject_in_command')
      cmd = get_command(cmd_str)
      arr.inject(init_val) {|acc,n| call(cmd_str,cmd,acc,n) }
    }.returns(Object),

    define_command: ->(name, block) { def_command(name, block) }
      .describe('Defines a command with the name given and a Block or a Ruby Proc.'),

    alias_command: ->(new_name, name) {
      Utils.valid_identifier_check(name)
      raise "Alias name '#{new_name}' is occupied" if @commands.has_key?(new_name.to_sym)
      @commands[new_name.to_sym] = @commands[name.to_sym]
    }.describe('Adds an alias for an existing command.'),

    define_variable: ->(var_name, val = nil) { def_variable(var_name, val) }
      .describe('Defines a variable with the name and value given. If no value is given, it is set to nil.'),

    define: ->(name, val = nil) {
      if val.is_a?(Block) || val.is_a?(Proc)
        def_command(name, val)
      else
        def_variable(name, val)
      end
    }.describe(
      "Defines a variable or command with the name and value given. A command is defined if the value is a Block "\
      "or a Ruby Proc, otherwise it is a variable."
    ),

    delete_variable: ->(var_str, panic_if_missing = true) {
      unknown_variable_error(var_str) if panic_if_missing && !@variables.has_key?(var_str.to_sym)
      @variables.delete(var_str.to_sym)
    }.impure
     .describe('Deletes the variable corresponding to the given name.'),

    describe: ->(cmd_str) {
      cmd = @commands[cmd_str.to_sym]
      unknown_command_error(cmd_str) if cmd.nil?
      out = ''
      if cmd.is_a?(Proc)
        out << (cmd.description or '')
        params = cmd.parameters.map {|type,arg| "#{arg} (#{type})" }
        out << "#{"\n" if !out.empty?}Param#{'s' if params.length != 1}: #{params.join(', ')}" unless params.empty?
        out << "#{"\n" if !out.empty?}Returns: #{cmd.return_type}" unless cmd.return_type.nil?
        unless cmd.pure? && cmd.ignore_unk_var_args.empty?
          out << "#{"\n" if !out.empty?}Notes:\n"
          out << "* Impure" unless cmd.pure?
          unless cmd.ignore_unk_var_args.empty?
            out << "* Unknown variables ignored at args #{cmd.ignore_unk_var_args.join(', ')}"
          end
        end
      elsif !cmd.pure?
        out << "Notes:\n* Impure"
      end
      aliases = @commands.select {|k,v| k.to_s != cmd_str && v == cmd }.keys
      out << "#{"\n" if !out.empty?}Alias#{'es' if aliases.length != 1}: #{aliases.join(', ')}" if !aliases.empty?
      out
    }.returns(String)
      .describe(
        'Describes a given command if a description is present and lists its parameters, return type, and aliases.'
    ),

    get_command_names: -> { @commands.keys.map { it.to_s } }
      .returns(Array)
      .describe('Gets an array containing each command name.'),

    get_variable_names: -> { @variables.keys.map { it.to_s } }
      .returns(Array)
      .describe('Gets an array containing each variables name.'),

    benchmark: ->(block_or_cmd, repeats, *args) {
      thing = block_or_cmd.is_a?(String) ? get_command(block_or_cmd) : block_or_cmd
      start_time = Time.now
      if args.nil?
        repeats.times { thing.call }
      else
        repeats.times { thing.call(*args) }
      end
      Time.now - start_time
    }.returns(Float).impure
      .describe('Times how long it takes to do the given Block or Command the amount of times given.'),

    is_pure: ->(block_proc_or_cmd) {
      if block_proc_or_cmd.is_a? String
        get_command(block_proc_or_cmd).pure?
      else
        block_proc_or_cmd.pure?
      end
    }.returns(Object)
      .describe('Gets whether the given Block, Ruby Proc, or command is pure.'),

    vow_purity: -> { @puritan_mode = true }.impure
      .describe('Activates puritan mode, disallowing the use of impure commands.'),
    vow_safety: -> { @safe_mode = true }.impure
      .describe('Activates safe mode, disallowing the use of inline Ruby commands.'),
    break_purity_vow: -> { @puritan_mode = false } # impure
      .describe('Deactivates puritan mode, allowing the use of impure commands.'),
    break_safety_vow: -> { @safe_mode = false }.impure
      .describe('Deactivates puritan mode, allpwing the use of impure commands.'),
    break_vows: -> { @puritan_mode = false; @safe_mode = false } # impure
      .describe('Breaks all vows.'),

    invalidate_cache: -> { @command_cache&.clear }.impure
      .describe('Clears command cache.')
  },

  aliases: {
    out:           :put,
    do_cmd:        :do_command,
    map_to_cmd:    :map_to_command,
    inject_in_cmd: :inject_in_command,
    define_cmd:    :define_command,
    def_cmd:       :define_command,
    alias_cmd:     :alias_command,
    def_var:       :define_variable,
    set_var:       :define_variable,
    delete_var:    :delete_variable,
    del_var:       :delete_variable,
    def:           :define,
    desc:          :describe,
    get_cmd_names: :get_command_names,
    get_var_names: :get_variable_names,
    clear_cache:   :invalidate_cache
  }).freeze
end

#def_command(cmd_name, block) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
# File 'lib/ncpp/interpreter.rb', line 241

def def_command(cmd_name, block)
  Utils.valid_identifier_check(cmd_name)
  raise 'commands must be either Blocks or Ruby Procs' unless block.is_a?(Block) || block.is_a?(Proc)
  cmd_sym = cmd_name.to_sym
  redef = @commands.has_key?(cmd_sym)
  raise 'Redefining commands is not allowed in puritan mode' if @puritan_mode && redef
  @command_cache.clear if !@command_cache.nil? && redef # command cache must be cleared if any command is redefined
  block.name = cmd_name if block.is_a? Block
  @commands[cmd_sym] = block
  @added_commands.add(cmd_sym)
end

#def_variable(var_name, val) ⇒ Object



271
272
273
274
275
276
277
278
279
# File 'lib/ncpp/interpreter.rb', line 271

def def_variable(var_name, val)
  Utils.valid_identifier_check(var_name)
  var_sym = var_name.to_sym
  redef = @variables.has_key?(var_sym)
  raise 'Redefining variables is not allowed in puritan mode' if @puritan_mode && redef
  @command_cache.clear if !@command_cache.nil? && redef # command cache must be cleared if any variable is redefined
  @variables[var_sym] = val
  @added_variables.add(var_sym)
end

#eval_expr(node, subs = nil) ⇒ Object

Evaluates the given AST



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
# File 'lib/ncpp/interpreter.rb', line 296

def eval_expr(node, subs = nil)
  case node
  when Numeric, String, Array, TrueClass, FalseClass, NilClass
    node

  when Hash
    if node[:infix] # binary operation
      lhs = eval_expr(node[:lhs], subs)
      rhs = eval_expr(node[:rhs], subs)
      op = node[:op]
      if op == '&&'
        lhs && rhs
      elsif op == '||'
        lhs || rhs
      else
        lhs.send(op, rhs)
      end

    elsif node[:cond] # ternary operation
      eval_expr(node[:cond], subs) ? eval_expr(node[:e1], subs) : eval_expr(node[:e2], subs)

    elsif node[:op] # unary operation
      op = node[:op]
      # if node[]
      eval_expr(node[:e], subs).send(op == '-' || op == '+' ? op+'@' : op)

    elsif node[:cmd_name] # normal command call
      cmd_name = node[:cmd_name].to_s
      cmd = get_command(cmd_name)
      raise "Cannot use impure command '#{cmd_name}' in puritan mode." if @puritan_mode && !cmd.pure?
      args = Array(node[:args]).map.with_index do |a,i|
        if cmd.is_a?(Proc) && cmd.ignore_unk_var_args.include?(i) &&
            a[:base].is_a?(Hash) && a[:base][:var_name] && !@variables.include?(a[:base][:var_name].to_sym)
          a[:base][:var_name].to_s
        else
          eval_expr(a, subs)
        end
      end
      ret = call(cmd_name,cmd,*args)
      cmd.return_type.nil? ? nil : (node[:subscript_idx].nil? ? ret : ret[eval_expr(node[:subscript_idx], subs)])

    elsif node[:base] && node[:chain] # chained command call
      acc = eval_expr(node[:base], subs)
      no_ret = false
      node[:chain].each do |link|
        next_cmd = link[:next]
        cmd_name = next_cmd[:cmd_name].to_s
        cmd = get_command(cmd_name)
        raise "Cannot use impure command '#{cmd_name}' in puritan mode." if @puritan_mode && !cmd.pure?
        args = Array(next_cmd[:args]).map.with_index do |a,i|
          if !cmd.is_a?(Block) && cmd.ignore_unk_var_args.include?(i) &&
              a[:base].is_a?(Hash) && a[:base][:var_name] && !@variables.include?(a[:base][:var_name].to_sym)
            a[:base][:var_name].to_s
          else
            eval_expr(a, subs)
          end
        end
        acc = call(cmd_name,cmd, acc,*args)
        no_ret = cmd.return_type.nil?
      end
      no_ret ? nil : acc

    elsif node[:var_name]
      unless subs.nil?
        var_name = node[:var_name].to_s
        if subs.has_key?(var_name)
          ret = subs[var_name]
          return (node[:subscript_idx].nil? ? ret : ret[eval_expr(node[:subscript_idx], subs)])
        end
      end
      var_name = node[:var_name].to_s
      ret = get_variable(var_name)
      node[:subscript_idx].nil? ? ret : ret[eval_expr(node[:subscript_idx], subs)]

    elsif node[:block]
      Block.new(node[:block], node[:args], self, subs)

    elsif node[:array]
      arr = Array(node[:array]).map { |a| eval_expr(a, subs) }
      if node[:subscript_idx].nil?
        arr
      else
        arr[eval_expr(node[:subscript_idx], subs)]
      end

    elsif node[:string]
      node[:string].to_s[eval_expr(node[:subscript_idx], subs)]

    elsif node[:bool]
      node[:bool].to_s == 'true' ? true : false

    elsif node[:nil]
      nil

    else
      raise "Unknown node type: #{node.inspect}"
    end

  else
    raise "Unexpected node: #{node.inspect}"
  end
end

#eval_str(expr_str) ⇒ Object

Parses the given String of NCPP code, transforms it, then evaluates resulting AST



288
289
290
291
292
293
# File 'lib/ncpp/interpreter.rb', line 288

def eval_str(expr_str)
  return nil if expr_str.empty?
  parsed_tree = @parser.parse(expr_str, root: :expression)
  ast = @transformer.apply(parsed_tree)
  eval_expr(ast)
end

#get_bindingObject



214
215
216
# File 'lib/ncpp/interpreter.rb', line 214

def get_binding
  binding
end

#get_cacheable_cacheObject

get cached commands that can be saved



227
228
229
# File 'lib/ncpp/interpreter.rb', line 227

def get_cacheable_cache
  @command_cache.delete_if {|k,v| @added_commands.include?(k.to_sym) }
end

#get_command(cmd_name) ⇒ Object



253
254
255
256
257
# File 'lib/ncpp/interpreter.rb', line 253

def get_command(cmd_name)
  cmd = @commands[cmd_name.to_sym]
  unknown_command_error(cmd_name) if cmd.nil?
  cmd
end

#get_new_commandsObject



218
219
220
# File 'lib/ncpp/interpreter.rb', line 218

def get_new_commands
  @added_commands.to_h {|cmd| [cmd, @commands[cmd]] }
end

#get_new_variablesObject



222
223
224
# File 'lib/ncpp/interpreter.rb', line 222

def get_new_variables
  @added_variables.to_h {|var| [var, @variables[var]] }
end

#get_variable(var_name) ⇒ Object



281
282
283
284
285
# File 'lib/ncpp/interpreter.rb', line 281

def get_variable(var_name)
  unknown_variable_error(var_name) unless @variables.has_key?(var_name.to_sym)
  var = @variables[var_name.to_sym]
  var
end

#node_impure?(node, self_name = nil) ⇒ Boolean

AST purity checking - if a call to an impure command or Block is found, return true

Returns:



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
430
431
432
433
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
471
# File 'lib/ncpp/interpreter.rb', line 400

def node_impure?(node, self_name = nil)
  case node
  when Numeric, String, Array, TrueClass, FalseClass, NilClass
    return false

  when Hash
    if node[:infix] # binary operation
      return node_impure?(node[:lhs], self_name) || node_impure?(node[:rhs], self_name)

    elsif node[:cond] # ternary operation
      return node_impure?(node[:cond], self_name) ||
             node_impure?(node[:e1], self_name) ||
             node_impure?(node[:e2], self_name)

    elsif node[:op] # unary operation
      return node_impure?(node[:e], self_name)

    elsif node[:cmd_name] # command call
      name = node[:cmd_name].to_s

      cmd = get_command(name)
      return true unless name == self_name || cmd.pure?

      # check args
      Array(node[:args]).each do |a|
        return true if node_impure?(a, self_name)
      end

      return false

    elsif node[:base] && node[:chain] # chained command call
      return true if node_impure?(node[:base], self_name)

      node[:chain].each do |link|
        next_cmd = link[:next]
        name = next_cmd[:cmd_name].to_s

        cmd = get_command(name)
        return true unless name == self_name || cmd.pure?

        Array(next_cmd[:args]).each do |a|
          return true if node_impure?(a, self_name)
        end
      end

      return false

    elsif node[:var_name]
      return false # not impure unless a variable is mutated (cache is cleared on variable mutation)

    elsif node[:block] # a nested Block
      nested_block = Block.new(node[:block], node[:args], self, nil, self_name)
      return !nested_block.pure?

    elsif node[:array]
      return Array(node[:array]).any? { |a| node_impure?(a, self_name) } ||
             (node[:subscript_idx] && node_impure?(node[:subscript_idx], self_name))

    elsif node[:string]
      return node[:subscript_idx] && node_impure?(node[:subscript_idx], self_name)

    elsif node[:bool] || node[:nil]
      return false

    else
      raise "Unknown node type: #{node.inspect}"
    end

  else
    raise "Unexpected node: #{node.inspect}"
  end
end

#unknown_command_error(cmd_name) ⇒ Object



231
232
233
234
# File 'lib/ncpp/interpreter.rb', line 231

def unknown_command_error(cmd_name)
  alt = @commands.suggest_similar_key(cmd_name)
  raise "Unknown command '#{cmd_name}'#{"\nDid you mean '#{alt}'?" unless alt.nil?}"
end

#unknown_variable_error(var_name) ⇒ Object



236
237
238
239
# File 'lib/ncpp/interpreter.rb', line 236

def unknown_variable_error(var_name)
  alt = @variables.suggest_similar_key(var_name)
  raise "Unknown variable '#{var_name}'#{"\nDid you mean '#{alt}'?" unless alt.nil?}"
end

#variablesObject



178
179
180
181
182
183
184
185
186
187
188
# File 'lib/ncpp/interpreter.rb', line 178

def variables
  {
    SYMBOL_COUNT: Unarm.symbols.count,
    SYMBOL_NAMES: Unarm.symbols.map.keys, # TODO: how should I handle ARM7 ??
    DEMANGLED_SYMBOL_NAMES: Unarm.symbols.demangled_map.keys,
    OVERLAY_COUNT: $rom.overlay_count,
    GAME_TITLE: $rom.header.game_title,
    NITRO_SDK_VERSION: $rom.nitro_sdk_version
    # OVERLAY_OFFSETS: Array.new($rom.overlay_count, 0)
  }
end