Module: Cadenza::Context::Stack

Included in:
Cadenza::Context
Defined in:
lib/cadenza/context/stack.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#stackArray (readonly)

Returns the variable stack.

Returns:

  • (Array)

    the variable stack


8
9
10
# File 'lib/cadenza/context/stack.rb', line 8

def stack
   @stack ||= []
end

Instance Method Details

#assign(identifier, value) ⇒ Object

assigns the given value to the given identifier at the highest current scope of the stack.

Parameters:

  • identifier (String)

    the name of the variable to store

  • value (Object)

    the value to assign to the given name


38
39
40
# File 'lib/cadenza/context/stack.rb', line 38

def assign(identifier, value)
   stack.last[identifier.to_sym] = value
end

#lookup(identifier) ⇒ Object

retrieves the value of the given identifier by inspecting the variable stack from top to bottom. Identifiers with dots in them are separated on that dot character and looked up as a path. If no value could be found then nil is returned.

Returns:

  • (Object)

    the object matching the identifier or nil if not found


18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/cadenza/context/stack.rb', line 18

def lookup(identifier)
   sym_identifier = identifier.to_sym

   # if a function is defined matching the identifier name then return that
   return functions[sym_identifier] if functions.has_key?(sym_identifier)

   stack.reverse_each do |scope|
      value = lookup_identifier(scope, identifier)

      return value unless value.nil?
   end
   
   nil
end

#popHash

removes the highest scope from the variable stack

Returns:

  • (Hash)

    the removed scope


60
61
62
# File 'lib/cadenza/context/stack.rb', line 60

def pop
   stack.pop
end

#push(scope) ⇒ Object

creates a new scope on the variable stack and assigns the given hash to it.

Parameters:

  • scope (Hash)

    the mapping of names to values for the new scope

Returns:

  • nil


47
48
49
50
51
52
53
54
55
56
# File 'lib/cadenza/context/stack.rb', line 47

def push(scope)
   # TODO: symbolizing strings is slow so consider symbolizing here to improve
   # the speed of the lookup method (its more important than push)

   # TODO: since you can assign with the #assign method then make the scope
   # variable optional (assigns an empty hash)
   stack.push(scope)

   nil
end