Class: SyntaxTree::WithScope::Scope

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

Overview

The scope 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(id, parent = nil) ⇒ Scope

Returns a new instance of Scope.



68
69
70
71
72
# File 'lib/syntax_tree/with_scope.rb', line 68

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

Instance Attribute Details

#idObject (readonly)

Integer

a unique identifier for this scope



59
60
61
# File 'lib/syntax_tree/with_scope.rb', line 59

def id
  @id
end

#localsObject (readonly)

Hash[String, Local]

The local variables and arguments defined in this

scope



66
67
68
# File 'lib/syntax_tree/with_scope.rb', line 66

def locals
  @locals
end

#parentObject (readonly)

scope | nil

The parent scope



62
63
64
# File 'lib/syntax_tree/with_scope.rb', line 62

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.



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/syntax_tree/with_scope.rb', line 78

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

  local =
    if type == :argument
      locals[name] ||= Local.new(type)
    else
      resolve_local(name, type)
    end

  local.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.



95
96
97
98
# File 'lib/syntax_tree/with_scope.rb', line 95

def add_local_usage(identifier, type)
  name = identifier.value.delete_suffix(":")
  resolve_local(name, type).add_usage(identifier.location)
end

#find_local(name) ⇒ Object

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



102
103
104
# File 'lib/syntax_tree/with_scope.rb', line 102

def find_local(name)
  locals[name] || parent&.find_local(name)
end