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



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

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

Instance Attribute Details

#guard_conditionsObject (readonly)

Returns the value of attribute guard_conditions.



117
118
119
# File 'lib/t_ruby/type_checker.rb', line 117

def guard_conditions
  @guard_conditions
end

#narrowed_typesObject (readonly)

Returns the value of attribute narrowed_types.



117
118
119
# File 'lib/t_ruby/type_checker.rb', line 117

def narrowed_types
  @narrowed_types
end

Instance Method Details

#branchObject



140
141
142
143
144
# File 'lib/t_ruby/type_checker.rb', line 140

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

#get_narrowed_type(variable) ⇒ Object



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

def get_narrowed_type(variable)
  @narrowed_types[variable]
end

#merge(other) ⇒ Object



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

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



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

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

#pop_guardObject



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

def pop_guard
  @guard_conditions.pop
end

#push_guard(condition) ⇒ Object



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

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