Class: SyntaxTree::Environment

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree/visitor/environment.rb

Overview

The environment class is used to keep track of local variables and arguments inside a particular scope

Defined Under Namespace

Classes: Local

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil) ⇒ Environment

initialize: (Environment | nil parent) -> void



45
46
47
48
# File 'lib/syntax_tree/visitor/environment.rb', line 45

def initialize(parent = nil)
  @locals = {}
  @parent = parent
end

Instance Attribute Details

#localsObject (readonly)

Array

The local variables and arguments defined in this

environment



39
40
41
# File 'lib/syntax_tree/visitor/environment.rb', line 39

def locals
  @locals
end

#parentObject (readonly)

Environment | nil

The parent environment



42
43
44
# File 'lib/syntax_tree/visitor/environment.rb', line 42

def parent
  @parent
end

Instance Method Details

#add_local_definition(identifier, type) ⇒ Object

Adding a local definition will either insert a new entry in the locals hash or append a new definition location to an existing local. Notice that it’s not possible to change the type of a local after it has been registered

add_local_definition: (Ident | Label identifier, Symbol type) -> void


55
56
57
58
59
60
# File 'lib/syntax_tree/visitor/environment.rb', line 55

def add_local_definition(identifier, type)
  name = identifier.value.delete_suffix(":")

  @locals[name] ||= Local.new(type)
  @locals[name].add_definition(identifier.location)
end

#add_local_usage(identifier, type) ⇒ Object

Adding a local usage will either insert a new entry in the locals hash or append a new usage location to an existing local. Notice that it’s not possible to change the type of a local after it has been registered

add_local_usage: (Ident | Label identifier, Symbol type) -> void


67
68
69
70
71
72
# File 'lib/syntax_tree/visitor/environment.rb', line 67

def add_local_usage(identifier, type)
  name = identifier.value.delete_suffix(":")

  @locals[name] ||= Local.new(type)
  @locals[name].add_usage(identifier.location)
end

#find_local(name) ⇒ Object

Try to find the local given its name in this environment or any of its parents

find_local: (String name) -> Local | nil


77
78
79
80
81
82
# File 'lib/syntax_tree/visitor/environment.rb', line 77

def find_local(name)
  local = @locals[name]
  return local unless local.nil?

  @parent&.find_local(name)
end