Class: Iode::Scope

Inherits:
Object
  • Object
show all
Defined in:
lib/iode/scope.rb

Overview

Lexical scope environment for iode.

Maintains a stack of execution contexts.

Instance Method Summary collapse

Constructor Details

#initialize(values = {}, parent = nil) ⇒ Scope

Create a new Scope with values as available variables.

Parameters:

  • values (Hash) (defaults to: {})

    key-values pairs of Symbol => Object

  • parent (Scope) (defaults to: nil)

    the parent scope, if any



29
30
31
32
# File 'lib/iode/scope.rb', line 29

def initialize(values = {}, parent = nil)
  @values = values
  @parent = parent
end

Instance Method Details

#[](k) ⇒ Object

Reference a variable in this scope.

Raises a RuntimeError if the variable does not exist.

Parameters:

  • k (Symbol)

    the variable name to lookup

Returns:

  • (Object)

    the object stored in this variable



43
44
45
46
47
48
49
50
51
# File 'lib/iode/scope.rb', line 43

def [](k)
  if @values.key?(k)
    @values[k]
  elsif @parent
    @parent[k]
  else
    raise "Undefined variable `#{k}`"
  end
end

#[]=(k, v) ⇒ Object

Re-assign a variable in this scope.

If the variable does not exist, it will be initialized.

Parameters:

  • k (Symbol)

    the variable name to assign

  • v (Object)

    the value to assign

Returns:

  • (Object)

    the assigned object



65
66
67
# File 'lib/iode/scope.rb', line 65

def []=(k, v)
  @values[k] = v
end

#push_scope(values = {}) ⇒ Scope

Create a new Scope with this Scope as its parent.

The new Scope will have access to all variables in this Scope, but assignments will only mask variables, not replace them.

Parameters:

  • values (Hash) (defaults to: {})

    variables to exist in the new Scope

Returns:

  • (Scope)

    a new Scope with this Scope as its parent



79
80
81
# File 'lib/iode/scope.rb', line 79

def push_scope(values = {})
  Scope.new(values, self)
end