Class: Steep::TypeInference::BlockParams

Inherits:
Object
  • Object
show all
Defined in:
lib/steep/type_inference/block_params.rb

Defined Under Namespace

Classes: Param

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params:, rest:) ⇒ BlockParams

Returns a new instance of BlockParams.



31
32
33
34
# File 'lib/steep/type_inference/block_params.rb', line 31

def initialize(params:, rest:)
  @params = params
  @rest = rest
end

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



28
29
30
# File 'lib/steep/type_inference/block_params.rb', line 28

def params
  @params
end

#restObject (readonly)

Returns the value of attribute rest.



29
30
31
# File 'lib/steep/type_inference/block_params.rb', line 29

def rest
  @rest
end

Class Method Details

.from_node(node, annotations:) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/steep/type_inference/block_params.rb', line 36

def self.from_node(node, annotations:)
  params = []
  rest = nil

  node.children.each do |arg|
    var = arg.children.first
    type = annotations.lookup_var_type(var.name)

    case arg.type
    when :arg, :procarg0
      params << Param.new(var: var, type: type, value: nil, node: arg)
    when :optarg
      params << Param.new(var: var, type: type, value: arg.children.last, node: arg)
    when :restarg
      rest = Param.new(var: var, type: type, value: nil, node: arg)
    end
  end

  new(
    params: params,
    rest: rest
  )
end

Instance Method Details

#each(&block) ⇒ Object



90
91
92
93
94
95
96
97
# File 'lib/steep/type_inference/block_params.rb', line 90

def each(&block)
  if block_given?
    params.each &block
    yield rest if rest
  else
    enum_for :each
  end
end

#zip(params_type) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/steep/type_inference/block_params.rb', line 60

def zip(params_type)
  [].tap do |zip|
    types = params_type.flat_unnamed_params
    params.each do |param|
      type = types.shift&.last || params_type.rest || AST::Types::Any.new

      if type
        zip << [param, type]
      end
    end

    if rest
      if types.empty?
        array = AST::Types::Name.new_instance(
          name: :Array,
          args: [params_type.rest || AST::Types::Any.new]
        )
        zip << [rest, array]
      else
        union = AST::Types::Union.build(types: types.map(&:last) + [params_type.rest])
        array = AST::Types::Name.new_instance(
          name: :Array,
          args: [union]
        )
        zip << [rest, array]
      end
    end
  end
end