Class: TRuby::FlowContext

Inherits:
Object
  • Object
show all
Defined in:
lib/t_ruby/type_checker.rb

Overview

Flow-sensitive type tracking

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFlowContext

Returns a new instance of FlowContext.



122
123
124
125
# File 'lib/t_ruby/type_checker.rb', line 122

def initialize
  @narrowed_types = {}
  @guard_conditions = []
end

Instance Attribute Details

#guard_conditionsObject (readonly)

Returns the value of attribute guard_conditions.



120
121
122
# File 'lib/t_ruby/type_checker.rb', line 120

def guard_conditions
  @guard_conditions
end

#narrowed_typesObject (readonly)

Returns the value of attribute narrowed_types.



120
121
122
# File 'lib/t_ruby/type_checker.rb', line 120

def narrowed_types
  @narrowed_types
end

Instance Method Details

#branchObject



143
144
145
146
147
# File 'lib/t_ruby/type_checker.rb', line 143

def branch
  new_context = FlowContext.new
  @narrowed_types.each { |k, v| new_context.narrow(k, v) }
  new_context
end

#get_narrowed_type(variable) ⇒ Object



131
132
133
# File 'lib/t_ruby/type_checker.rb', line 131

def get_narrowed_type(variable)
  @narrowed_types[variable]
end

#merge(other) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/t_ruby/type_checker.rb', line 149

def merge(other)
  # Merge two branches - types that are narrowed in both become union
  merged = FlowContext.new
  all_vars = @narrowed_types.keys | other.narrowed_types.keys

  all_vars.each do |var|
    type_a = @narrowed_types[var]
    type_b = other.narrowed_types[var]

    if type_a && type_b
      if type_a == type_b
        merged.narrow(var, type_a)
      else
        merged.narrow(var, "#{type_a} | #{type_b}")
      end
    elsif type_a || type_b
      merged.narrow(var, type_a || type_b)
    end
  end

  merged
end

#narrow(variable, new_type) ⇒ Object



127
128
129
# File 'lib/t_ruby/type_checker.rb', line 127

def narrow(variable, new_type)
  @narrowed_types[variable] = new_type
end

#pop_guardObject



139
140
141
# File 'lib/t_ruby/type_checker.rb', line 139

def pop_guard
  @guard_conditions.pop
end

#push_guard(condition) ⇒ Object



135
136
137
# File 'lib/t_ruby/type_checker.rb', line 135

def push_guard(condition)
  @guard_conditions.push(condition)
end