Class: RVM::Interpreter::FunctionDefinition

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

Overview

The FunctionDefinition can be used to define functions in the current scope, it can either be methods belonging to a object when called within object scope or good old functions.

Instance Attribute Summary

Attributes inherited from Element

#pos

Instance Method Summary collapse

Constructor Details

#initialize(name, body, override = true, pos = nil) ⇒ FunctionDefinition

Initializes a new function definition

name

is the name of the function to define, if it is not unique it will overwrite earlyer definitions (unless override is false)

body

is the body of the cuntion. this will be executed when the defined function is called.

override

when true (default) earlyer definitions are replaced when it is called a second time. When false a exception is thrown

pos

The position within the source code of the definition - for deugging purpose.



221
222
223
224
225
226
# File 'lib/rvm/interpreter.rb', line 221

def initialize name, body, override = true, pos = nil
  super(pos)
  @name = name
  @body = body
  @override = override
end

Instance Method Details

#execute(env) ⇒ Object

When executed the FunctionDefinition first checks if a function with the same name is already defined. If it is and override wasn’t set to ture it trows a Exception. Otherwise it defines the function, deleting the old definition when still repsent.

It returns the body of the newly defined function.



246
247
248
249
250
251
252
# File 'lib/rvm/interpreter.rb', line 246

def execute env
  if (not @override) and env.function(@name)
    raise RuntimeError.new("Function #{@name} already defined", @pos[0], @pos[1], @pos[2])
  end
  env.def_function(@name.execute(env),@body)
  @body
end

#optimizeObject



254
255
256
257
258
# File 'lib/rvm/interpreter.rb', line 254

def optimize
  @body = @body.optimize
  @name = @name.optimize
  super
end

#pretty_print(q) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
# File 'lib/rvm/interpreter.rb', line 228

def pretty_print(q)
  first = true
  q.text "function "
  if @name.is_a? Constant
    q.text @name.value
  else
    q.pp @name
  end
  q.text "()"
  q.pp @body
end