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 = nil, parent = nil) ⇒ Scope

Create a new Scope with values as available variables.

Parameters:

  • values (Hash) (defaults to: nil)

    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 = nil, parent = nil)
  @values = values || Core.definitions
  @parent = parent
end

Instance Method Details

#[](k) ⇒ Object

Reference a variable in this Scope or any parent Scopes.

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



57
58
59
60
61
62
63
64
65
# File 'lib/iode/scope.rb', line 57

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

#[]=(k, v) ⇒ Object

Re-assign a variable in this Scope, or any parent Scope.

Raises a RuntimeError if the variable does not exist.

Parameters:

  • k (Symbol)

    the variable name to assign

  • v (Object)

    the value to assign

Returns:

  • (Object)

    the assigned object



79
80
81
82
83
84
85
86
87
# File 'lib/iode/scope.rb', line 79

def []=(k, v)
  if @values.key?(k)
    @values[k] = v
  elsif @parent
    @parent[k] = v
  else
    raise "Reference to undefined variable `#{k}`"
  end
end

#define(k, v) ⇒ Object

Define a new variable.

Parameters:

  • k (Symbol)

    the name of the variable to define

  • v (Object)

    the value to set

Returns:

  • (Object)

    the newly defined value



44
45
46
# File 'lib/iode/scope.rb', line 44

def define(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.

Parameters:

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

    variables to exist in the new Scope

Returns:

  • (Scope)

    a new Scope with this Scope as its parent



98
99
100
# File 'lib/iode/scope.rb', line 98

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