Class: Steep::TypeConstruction

Inherits:
Object
  • Object
show all
Includes:
ModuleHelper, NodeHelper
Defined in:
lib/steep/type_construction.rb

Defined Under Namespace

Classes: Pair

Constant Summary collapse

SPECIAL_LVAR_NAMES =
ANONYMOUS_BLOCK_PASSABLE_LVAR =

a synthetic variable name for anonymous block params (can’t conflict with user variables since Ruby doesn’t allow * in local variable names).

:"*block"
KNOWN_PURE_METHODS =
KERNEL_BLOCK_GIVEN =
MethodName("::Kernel#block_given?")
SPECIAL_METHOD_NAMES =
{
  array_compact: Set[
    MethodName("::Array#compact"),
    MethodName("::Enumerable#compact")
  ],
  hash_compact: Set[
    MethodName("::Hash#compact")
  ],
  lambda: Set[
    MethodName("::Kernel#lambda"),
    MethodName("::Kernel.lambda")
  ]
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ModuleHelper

#module_name_from_node, #namespace_from_node

Methods included from NodeHelper

#clone_node, #deconstruct_case_node, #deconstruct_case_node!, #deconstruct_if_node, #deconstruct_if_node!, #deconstruct_resbody_node, #deconstruct_resbody_node!, #deconstruct_rescue_node, #deconstruct_rescue_node!, #deconstruct_send_node, #deconstruct_send_node!, #deconstruct_sendish_and_block_nodes, #deconstruct_when_node, #deconstruct_when_node!, #deconstruct_whileish_node, #deconstruct_whileish_node!, #each_child_node, #each_descendant_node, #private_send?, #test_case_node, #test_if_node, #test_resbody_node, #test_rescue_node, #test_send_node, #test_when_node, #test_whileish_node, #value_node?

Constructor Details

#initialize(checker:, source:, annotations:, typing:, context:) ⇒ TypeConstruction

Returns a new instance of TypeConstruction.



87
88
89
90
91
92
93
# File 'lib/steep/type_construction.rb', line 87

def initialize(checker:, source:, annotations:, typing:, context:)
  @checker = checker
  @source = source
  @annotations = annotations
  @typing = typing
  @context = context
end

Instance Attribute Details

#annotationsObject (readonly)

Returns the value of attribute annotations.



50
51
52
# File 'lib/steep/type_construction.rb', line 50

def annotations
  @annotations
end

#checkerObject (readonly)

Returns the value of attribute checker.



48
49
50
# File 'lib/steep/type_construction.rb', line 48

def checker
  @checker
end

#contextObject (readonly)

Returns the value of attribute context.



53
54
55
# File 'lib/steep/type_construction.rb', line 53

def context
  @context
end

#sourceObject (readonly)

Returns the value of attribute source.



49
50
51
# File 'lib/steep/type_construction.rb', line 49

def source
  @source
end

#typingObject (readonly)

Returns the value of attribute typing.



51
52
53
# File 'lib/steep/type_construction.rb', line 51

def typing
  @typing
end

Instance Method Details

#absolute_name(name) ⇒ Object



4709
4710
4711
# File 'lib/steep/type_construction.rb', line 4709

def absolute_name(name)
  checker.factory.absolute_type_name(name, context: nesting)
end

#add_call(call) ⇒ Object



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/steep/type_construction.rb', line 716

def add_call(call)
  case call
  when TypeInference::MethodCall::NoMethodError
    typing.add_error(call.error)
  when TypeInference::MethodCall::Error
    call.errors.each do |error|
      typing.add_error(error)
    end
  end

  typing.add_typing(call.node, call.return_type, nil)
  typing.add_call(call.node, call)

  Pair.new(type: call.return_type, constr: self)
end

#add_typing(node, type:, constr: self) ⇒ Object



709
710
711
712
713
714
# File 'lib/steep/type_construction.rb', line 709

def add_typing(node, type:, constr: self)
  raise if constr.typing != self.typing

  typing.add_typing(node, type, nil)
  Pair.new(type: type, constr: constr)
end

#apply_solution(errors, node:, method_type:) ⇒ Object



3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
# File 'lib/steep/type_construction.rb', line 3787

def apply_solution(errors, node:, method_type:)
  subst = yield

  [
    method_type.subst(subst),
    true,
    subst
  ]

rescue Subtyping::Constraints::UnsatisfiableConstraint => exn
  errors << Diagnostic::Ruby::UnsatisfiableConstraint.new(
    node: node,
    method_type: method_type,
    var: exn.var,
    sub_type: exn.sub_type,
    super_type: exn.super_type,
    result: exn.result
  )
  [method_type, false, Interface::Substitution.empty]
end

#arrayish_type?(type, untyped_is: false) ⇒ Boolean

Returns:

  • (Boolean)


5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
# File 'lib/steep/type_construction.rb', line 5045

def arrayish_type?(type, untyped_is: false)
  case type
  when AST::Types::Any
    if untyped_is
      type
    end
  when AST::Types::Name::Instance
    if AST::Builtin::Array.instance_type?(type)
      type
    end
  when AST::Types::Tuple
    type
  when AST::Types::Name::Alias
    if t = checker.factory.deep_expand_alias(type)
      arrayish_type?(t)
    end
  end
end

#block_contextObject



67
68
69
# File 'lib/steep/type_construction.rb', line 67

def block_context
  context.block_context
end

#block_context!Object



71
72
73
# File 'lib/steep/type_construction.rb', line 71

def block_context!
  block_context or raise
end

#break_contextObject



75
76
77
# File 'lib/steep/type_construction.rb', line 75

def break_context
  context.break_context
end

#builder_configObject



3569
3570
3571
3572
3573
3574
3575
3576
# File 'lib/steep/type_construction.rb', line 3569

def builder_config
  Interface::Builder::Config.new(
    self_type: self_type,
    class_type: module_context.module_type,
    instance_type: module_context.instance_type,
    variable_bounds: context.variable_context.upper_bounds
  )
end

#bypass_splat(node) ⇒ Object

Bypass :splat and :kwsplat



3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
# File 'lib/steep/type_construction.rb', line 3775

def bypass_splat(node)
  splat = node.type == :splat || node.type == :kwsplat

  if splat
    pair = yield(node.children[0])
    pair.constr.add_typing(node, type: pair.type)
    pair
  else
    yield node
  end
end

#calculate_interface(type, method_name = nil, private:) ⇒ Object



3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
# File 'lib/steep/type_construction.rb', line 3578

def calculate_interface(type, method_name = nil, private:)
  shape = checker.builder.shape(type, builder_config)

  unless private
    shape = shape&.public_shape
  end

  if method_name
    if shape
      shape.methods[method_name]
    end
  else
    shape
  end
end

#check(node, type, constraints: Subtyping::Constraints.empty) ⇒ Object



2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
# File 'lib/steep/type_construction.rb', line 2728

def check(node, type, constraints: Subtyping::Constraints.empty)
  pair = synthesize(node, hint: type)

  result = check_relation(sub_type: pair.type, super_type: type, constraints: constraints)
  if result.failure?
    yield(type, pair.type, result)
    pair.with(type: type)
  else
    pair
  end
end

#check_deprecation_constant(name, node, location) ⇒ Object



5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
# File 'lib/steep/type_construction.rb', line 5355

def check_deprecation_constant(name, node, location)
  entry = checker.builder.factory.env.constant_entry(name)

  annotations =
    case entry
    when RBS::Environment::ModuleEntry, RBS::Environment::ClassEntry
      entry.each_decl.flat_map do |decl|
        if decl.is_a?(RBS::AST::Declarations::Base)
          decl.annotations
        else
          []
        end
      end
    when RBS::Environment::ConstantEntry, RBS::Environment::ClassAliasEntry, RBS::Environment::ModuleAliasEntry
      if entry.decl.is_a?(RBS::AST::Declarations::Base)
        entry.decl.annotations
      else
        [] #: Array[RBS::AST::Annotation]
      end
    end

  if annotations
    if (_, message = AnnotationsHelper.deprecated_annotation?(annotations))
      typing.add_error(
        Diagnostic::Ruby::DeprecatedReference.new(
          node: node,
          location: location,
          message: message
        )
      )
    end
  end
end

#check_deprecation_global(name, node, location) ⇒ Object



5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
# File 'lib/steep/type_construction.rb', line 5341

def check_deprecation_global(name, node, location)
  if global_entry = checker.factory.env.global_decls[name]
    if (_, message = AnnotationsHelper.deprecated_annotation?(global_entry.decl.annotations))
      typing.add_error(
        Diagnostic::Ruby::DeprecatedReference.new(
          node: node,
          location: location,
          message: message
        )
      )
    end
  end
end

#check_relation(sub_type:, super_type:, constraints: Subtyping::Constraints.empty) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/steep/type_construction.rb', line 135

def check_relation(sub_type:, super_type:, constraints: Subtyping::Constraints.empty)
  Steep.logger.debug { "check_relation: self:#{self_type}, instance:#{module_context.instance_type}, class:#{module_context.module_type} |- #{sub_type} <: #{super_type}" }
  relation = Subtyping::Relation.new(sub_type: sub_type, super_type: super_type)
  checker.push_variable_bounds(variable_context.upper_bounds) do
    checker.check(
      relation,
      self_type: self_type,
      instance_type: module_context.instance_type,
      class_type: module_context.module_type,
      constraints: constraints
    )
  end
end

#deep_expand_alias(type) ⇒ Object



4898
4899
4900
# File 'lib/steep/type_construction.rb', line 4898

def deep_expand_alias(type)
  checker.factory.deep_expand_alias(type)
end

#default_module_context(implement_module_name, nesting:) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/steep/type_construction.rb', line 336

def default_module_context(implement_module_name, nesting:)
  if implement_module_name
    module_name = checker.factory.absolute_type_name(implement_module_name.name, context: nesting) or raise
    module_args = implement_module_name.args.map {|name| AST::Types::Var.new(name: name) }

    instance_def = checker.factory.definition_builder.build_instance(module_name)
    module_def = checker.factory.definition_builder.build_singleton(module_name)

    instance_type = AST::Types::Name::Instance.new(name: module_name, args: module_args)
    module_type = AST::Types::Name::Singleton.new(name: module_name)

    TypeInference::Context::ModuleContext.new(
      instance_type: instance_type,
      module_type: module_type,
      implement_name: implement_module_name,
      nesting: nesting,
      class_name: module_name,
      instance_definition: instance_def,
      module_definition: module_def
    )
  else
    TypeInference::Context::ModuleContext.new(
      instance_type: AST::Builtin::Object.instance_type,
      module_type: AST::Builtin::Object.module_type,
      implement_name: nil,
      nesting: nesting,
      class_name: self.module_context.class_name,
      module_definition: nil,
      instance_definition: nil
    )
  end
end

#deprecated_send?(call) ⇒ Boolean

Returns:

  • (Boolean)


3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
# File 'lib/steep/type_construction.rb', line 3268

def deprecated_send?(call)
  return unless call.node.type == :send || call.node.type == :csend

  call.method_decls.each do |decl|
    if pair = AnnotationsHelper.deprecated_annotation?(decl.method_def.each_annotation.to_a)
      return pair
    end
  end

  nil
end

#eliminate_vars(type, variables, to: AST::Builtin.any_type) ⇒ Object



3808
3809
3810
3811
3812
3813
3814
3815
# File 'lib/steep/type_construction.rb', line 3808

def eliminate_vars(type, variables, to: AST::Builtin.any_type)
  if variables.empty?
    type
  else
    subst = Interface::Substitution.build(variables, Array.new(variables.size, to))
    type.subst(subst)
  end
end

#expand_alias(type, &block) ⇒ Object



4927
4928
4929
4930
4931
4932
4933
4934
# File 'lib/steep/type_construction.rb', line 4927

def expand_alias(type, &block)
  typ = checker.factory.expand_alias(type)
  if block
    yield(typ)
  else
    typ
  end
end

#expand_self(type) ⇒ Object



3594
3595
3596
3597
3598
3599
3600
# File 'lib/steep/type_construction.rb', line 3594

def expand_self(type)
  if type.is_a?(AST::Types::Self) && self_type
    self_type
  else
    type
  end
end

#fallback_to_any(node) ⇒ Object



4855
4856
4857
4858
4859
4860
4861
4862
4863
# File 'lib/steep/type_construction.rb', line 4855

def fallback_to_any(node)
  if block_given?
    typing.add_error yield
  else
    typing.add_error Diagnostic::Ruby::FallbackAny.new(node: node)
  end

  add_typing node, type: AST::Builtin.any_type
end

#flatten_array_elements(type) ⇒ Object



4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
# File 'lib/steep/type_construction.rb', line 4916

def flatten_array_elements(type)
  flatten_union(deep_expand_alias(type) || type).flat_map do |type|
    if AST::Builtin::Array.instance_type?(type)
      # @type var type: AST::Types::Name::Instance
      type.args
    else
      [type]
    end
  end
end

#flatten_union(type) ⇒ Object



4902
4903
4904
# File 'lib/steep/type_construction.rb', line 4902

def flatten_union(type)
  checker.factory.flatten_union(type)
end

#for_block(body_node, block_params:, block_param_hint:, block_next_type:, block_block_hint:, block_annotations:, node_type_hint:, block_self_hint:) ⇒ Object



4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
# File 'lib/steep/type_construction.rb', line 4547

def for_block(body_node, block_params:, block_param_hint:, block_next_type:, block_block_hint:, block_annotations:, node_type_hint:, block_self_hint:)
  block_param_pairs = block_param_hint && block_params.zip(block_param_hint, block_block_hint, factory: checker.factory)

  # @type var param_types_hash: Hash[Symbol?, AST::Types::t]
  param_types_hash = {}
  if block_param_pairs
    block_param_pairs.each do |param, type|
      case param
      when TypeInference::BlockParams::Param
        var_name = param.var
        param_types_hash[var_name] = type
      when TypeInference::BlockParams::MultipleParam
        set_up_block_mlhs_params_env(param.node, type, param_types_hash) do |error_node, non_array_type|
          Steep.logger.fatal { "`#{non_array_type}#to_ary` returns non-array-ish type" }
          annotation_types = param.variable_types()
          each_descendant_node(error_node) do |n|
            if n.type == :arg
              name = n.children[0]
              param_types_hash[name] = annotation_types[name] || AST::Builtin.any_type
            end
          end
        end
      end
    end
  else
    block_params.each do |param|
      case param
      when TypeInference::BlockParams::Param
        var_name = param.var
        param_types_hash[var_name] = param.type || AST::Builtin.any_type
      when TypeInference::BlockParams::MultipleParam
        param.each_param do |p|
          param_types_hash[p.var] = p.type || AST::Builtin.any_type
        end
      end
    end
  end

  param_types_hash.delete_if {|name, _| name && SPECIAL_LVAR_NAMES.include?(name) }

  param_types = param_types_hash.each.with_object({}) do |pair, hash| #$ Hash[Symbol, [AST::Types::t, AST::Types::t?]]
    name, type = pair
    # skip unnamed arguments `*`, `**` and `&`
    next if name.nil?
    hash[name] = [type, nil]
  end

  pins = context.type_env.pin_local_variables(nil)

  type_env = context.type_env
  type_env = type_env.invalidate_pure_node(Parser::AST::Node.new(:self)) if block_self_hint || block_annotations.self_type
  type_env = type_env.merge(local_variable_types: pins)
  type_env = type_env.merge(local_variable_types: param_types)
  type_env = TypeInference::TypeEnvBuilder.new(
    if self_binding = block_annotations.self_type || block_self_hint
      definition =
        case self_binding
        when AST::Types::Name::Instance
          checker.factory.definition_builder.build_instance(self_binding.name)
        when AST::Types::Name::Singleton
          checker.factory.definition_builder.build_singleton(self_binding.name)
        end

      if definition
        TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableDefinition.new(definition, checker.factory)
      end
    end,
    TypeInference::TypeEnvBuilder::Command::ImportLocalVariableAnnotations.new(block_annotations).merge!.on_duplicate! do |name, outer_type, inner_type|
      next if outer_type.is_a?(AST::Types::Var) || inner_type.is_a?(AST::Types::Var)
      next unless body_node

      if result = no_subtyping?(sub_type: outer_type, super_type: inner_type)
        typing.add_error Diagnostic::Ruby::IncompatibleAnnotation.new(
          node: body_node,
          var_name: name,
          result: result,
          relation: result.relation
        )
      end
    end
  ).build(type_env)

  break_type = if block_annotations.break_type
                 union_type(node_type_hint, block_annotations.break_type)
               else
                 node_type_hint
               end

  block_context = TypeInference::Context::BlockContext.new(
    body_type: block_annotations.block_type
  )
  break_context = TypeInference::Context::BreakContext.new(
    break_type: break_type || AST::Builtin.any_type,
    next_type: block_next_type || AST::Builtin.any_type
  )

  self_type = block_self_hint || self.self_type
  module_context = self.module_context

  if implements = block_annotations.implement_module_annotation
    module_context = default_module_context(implements.name, nesting: nesting)
    self_type = module_context.module_type
  end

  if annotation_self_type = block_annotations.self_type
    self_type = annotation_self_type
  end

  # self_type here means the top-level `self` type because of the `Interface::Builder` implementation
  if self_type
    self_type = expand_self(self_type)
  end

  self.class.new(
    checker: checker,
    source: source,
    annotations: annotations.merge_block_annotations(block_annotations),
    typing: typing,
    context: TypeInference::Context.new(
      block_context: block_context,
      method_context: method_context,
      module_context: module_context,
      break_context: break_context,
      self_type: self_type,
      type_env: type_env,
      call_context: self.context.call_context,
      variable_context: variable_context
    )
  )
end

#for_branch(node, break_context: context.break_context) ⇒ Object



685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
# File 'lib/steep/type_construction.rb', line 685

def for_branch(node, break_context: context.break_context)
  annots = source.annotations(block: node, factory: checker.factory, context: nesting)

  type_env = TypeInference::TypeEnvBuilder.new(
    TypeInference::TypeEnvBuilder::Command::ImportLocalVariableAnnotations.new(annots).merge!.on_duplicate! do |name, outer_type, annotation_type|
      relation = Subtyping::Relation.new(sub_type: annotation_type, super_type: outer_type)
      if result = no_subtyping?(sub_type: annotation_type, super_type: outer_type)
        typing.add_error(
          Diagnostic::Ruby::IncompatibleAnnotation.new(
            node: node,
            var_name: name,
            relation: relation,
            result: result
          )
        )
      end
    end
  ).build(context.type_env)

  update_context do |context|
    context.with(type_env: type_env, break_context: break_context)
  end
end

#for_class(node, new_class_name, super_class_name) ⇒ Object



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'lib/steep/type_construction.rb', line 488

def for_class(node, new_class_name, super_class_name)
  new_nesting = [nesting, new_class_name || false] #: RBS::Resolver::context
  annots = source.annotations(block: node, factory: checker.factory, context: new_nesting)

  class_const_env = TypeInference::ConstantEnv.new(
    factory: checker.factory,
    context: new_nesting,
    resolver: context.type_env.constant_env.resolver
  )

  implement_module_name = implement_module(module_name: new_class_name, super_name: super_class_name, annotations: annots)
  module_context = default_module_context(implement_module_name, nesting: new_nesting)

  if implement_module_name
    if super_class_name && implement_module_name.name == absolute_name(super_class_name)
      module_context = module_context.update(instance_definition: nil, module_definition: nil)
    end

    if !checker.factory.definition_builder.env.class_entry(implement_module_name.name, normalized: true) &&
      checker.factory.definition_builder.env.module_entry(implement_module_name.name, normalized: true)
      typing.add_error(
        Diagnostic::Ruby::ClassModuleMismatch.new(node: node, name: new_class_name)
      )
    end
  else
    module_context = module_context.update(
      instance_type: AST::Builtin::Object.instance_type,
      module_type: AST::Builtin::Object.module_type
    )
  end

  if annots.instance_type
    module_context = module_context.update(instance_type: annots.instance_type)
  end

  if annots.module_type
    module_context = module_context.update(module_type: annots.module_type)
  end

  if annots.self_type
    module_context = module_context.update(module_type: annots.self_type)
  end

  definition = checker.factory.definition_builder.build_instance(module_context.class_name)
  type_params = definition.type_params_decl.map do |type_param|
    Interface::TypeParam.new(
      name: type_param.name,
      upper_bound: type_param.upper_bound_type&.yield_self {|t| checker.factory.type(t) },
      variance: type_param.variance,
      unchecked: type_param.unchecked?,
      location: type_param.location,
      default_type: checker.factory.type_opt(type_param.default_type)
    )
  end
  variable_context = TypeInference::Context::TypeVariableContext.new(type_params)

  singleton_definition = checker.factory.definition_builder.build_singleton(module_context.class_name)
  class_type_env = TypeInference::TypeEnvBuilder.new(
    TypeInference::TypeEnvBuilder::Command::ImportGlobalDeclarations.new(checker.factory),
    TypeInference::TypeEnvBuilder::Command::ImportConstantAnnotations.new(annots),
    TypeInference::TypeEnvBuilder::Command::ImportLocalVariableAnnotations.new(annots),
    TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableDefinition.new(singleton_definition, checker.factory),
  ).build(TypeInference::TypeEnv.new(class_const_env))

  class_body_context = TypeInference::Context.new(
    method_context: nil,
    block_context: nil,
    module_context: module_context,
    break_context: nil,
    self_type: module_context.module_type,
    type_env: class_type_env,
    call_context: TypeInference::MethodCall::ModuleContext.new(type_name: module_context.class_name),
    variable_context: variable_context
  )

  self.class.new(
    checker: checker,
    source: source,
    annotations: annots,
    typing: typing,
    context: class_body_context
  )
end

#for_module(node, new_module_name) ⇒ Object



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/steep/type_construction.rb', line 369

def for_module(node, new_module_name)
  new_nesting = [nesting, new_module_name || false] #: RBS::Resolver::context

  annots = source.annotations(block: node, factory: checker.factory, context: new_nesting)

  implement_module_name = implement_module(module_name: new_module_name, annotations: annots)
  module_context = default_module_context(implement_module_name, nesting: new_nesting)

  unless implement_module_name
    module_context = module_context.update(
      module_type: AST::Builtin::Module.instance_type,
      instance_type: AST::Builtin::BasicObject.instance_type
    )
  end

  if implement_module_name
    module_entry = checker.factory.definition_builder.env.module_entry(implement_module_name.name, normalized: true)
    if module_entry
      module_context = module_context.update(
        instance_type: AST::Types::Intersection.build(
          types: [
            AST::Builtin::Object.instance_type,
            *module_entry.self_types.map {|module_self|
              type = case
                    when module_self.name.interface?
                      RBS::Types::Interface.new(
                        name: module_self.name,
                        args: module_self.args,
                        location: module_self.location
                      )
                    when module_self.name.class?
                      RBS::Types::ClassInstance.new(
                        name: module_self.name,
                        args: module_self.args,
                        location: module_self.location
                      )
                    else
                      raise
                    end
              checker.factory.type(type)
            },
            module_context.instance_type
          ].compact
        )
      )
    elsif checker.factory.definition_builder.env.class_entry(implement_module_name.name, normalized:true)
      typing.add_error(
        Diagnostic::Ruby::ClassModuleMismatch.new(node: node, name: new_module_name)
      )
    end
  end

  if annots.instance_type
    module_context = module_context.update(instance_type: annots.instance_type)
  end

  if annots.module_type
    module_context = module_context.update(module_type: annots.module_type)
  end

  if annots.self_type
    module_context = module_context.update(module_type: annots.self_type)
  end

  if implement_module_name
    definition = checker.factory.definition_builder.build_instance(implement_module_name.name)
    type_params = definition.type_params_decl.map do |param|
      Interface::TypeParam.new(
        name: param.name,
        upper_bound: checker.factory.type_opt(param.upper_bound_type),
        variance: param.variance,
        unchecked: param.unchecked?,
        default_type: checker.factory.type_opt(param.default_type)
      )
    end
    variable_context = TypeInference::Context::TypeVariableContext.new(type_params)
  else
    variable_context = TypeInference::Context::TypeVariableContext.empty
  end

  module_const_env = TypeInference::ConstantEnv.new(
    factory: checker.factory,
    context: new_nesting,
    resolver: context.type_env.constant_env.resolver
  )

  module_type_env = TypeInference::TypeEnvBuilder.new(
    TypeInference::TypeEnvBuilder::Command::ImportGlobalDeclarations.new(checker.factory),
    TypeInference::TypeEnvBuilder::Command::ImportLocalVariableAnnotations.new(annots),
    TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableDefinition.new(module_context.module_definition, checker.factory),
    TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableAnnotations.new(annots).merge!,
    TypeInference::TypeEnvBuilder::Command::ImportConstantAnnotations.new(annots)
  ).build(TypeInference::TypeEnv.new(module_const_env))

  self.class.new(
    checker: checker,
    source: source,
    annotations: annots,
    typing: typing,
    context: TypeInference::Context.new(
      method_context: nil,
      block_context: nil,
      break_context: nil,
      module_context: module_context,
      self_type: module_context.module_type,
      type_env: module_type_env,
      call_context: TypeInference::MethodCall::ModuleContext.new(type_name: module_context.class_name),
      variable_context: variable_context
    )
  )
end

#for_new_method(method_name, node, args:, self_type:, definition:) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/steep/type_construction.rb', line 156

def for_new_method(method_name, node, args:, self_type:, definition:)
  annots = source.annotations(block: node, factory: checker.factory, context: nesting)
  definition_method_type = if definition
                             definition.methods[method_name]&.yield_self do |method|
                               method.method_types
                                 .map {|method_type| checker.factory.method_type(method_type) }
                                 .inject {|t1, t2| t1 + t2}
                             end
                           end
  annotation_method_type = annotations.method_type(method_name)

  method_type = annotation_method_type || definition_method_type

  unless method_type
    if definition
      typing.add_error(
        Diagnostic::Ruby::UndeclaredMethodDefinition.new(method_name: method_name, type_name: definition.type_name, node: node)
      )
    else
      typing.add_error(
        Diagnostic::Ruby::MethodDefinitionInUndeclaredModule.new(method_name: method_name, node: node)
      )
    end
  end

  if (annotation_return_type = annots&.return_type) && (method_type_return_type = method_type&.type&.return_type)
    check_relation(sub_type: annotation_return_type, super_type: method_type_return_type).else do |result|
      typing.add_error(
        Diagnostic::Ruby::MethodReturnTypeAnnotationMismatch.new(
          node: node,
          method_type: method_type.type.return_type,
          annotation_type: annots.return_type,
          result: result
        )
      )
    end
  end

  # constructor_method = method&.attributes&.include?(:constructor)

  super_method = if definition
                   if (this_method = definition.methods[method_name])
                     if module_context&.class_name == this_method.defined_in
                       this_method.super_method
                     else
                       this_method
                     end
                   end
                 end

  if definition && method_type
    variable_context = TypeInference::Context::TypeVariableContext.new(method_type.type_params, parent_context: self.variable_context)
  else
    variable_context = self.variable_context
  end

  method_params =
    if method_type
      TypeInference::MethodParams.build(node: node, method_type: method_type)
    else
      TypeInference::MethodParams.empty(node: node)
    end

  block_param_name = nil #: Symbol?
  method_params.each_param do |param|
    if param.is_a?(TypeInference::MethodParams::BlockParameter)
      block_param_name = param.name || ANONYMOUS_BLOCK_PASSABLE_LVAR
    end
  end

  method_context = TypeInference::Context::MethodContext.new(
    name: method_name,
    method: definition && definition.methods[method_name],
    method_type: method_type,
    return_type: annots.return_type || method_type&.type&.return_type || AST::Builtin.any_type,
    super_method: super_method,
    forward_arg_type: method_params.forward_arg_type,
    block_param_name: block_param_name
  )

  local_variable_types = method_params.each_param.with_object({}) do |param, hash| #$ Hash[Symbol, AST::Types::t]
    if param.name
      unless SPECIAL_LVAR_NAMES.include?(param.name)
        hash[param.name] = param.var_type
      end
    elsif param.is_a?(TypeInference::MethodParams::BlockParameter)
      hash[ANONYMOUS_BLOCK_PASSABLE_LVAR] = param.var_type
    end
  end
  type_env = context.type_env.assign_local_variables(local_variable_types)

  type_env = TypeInference::TypeEnvBuilder.new(
    TypeInference::TypeEnvBuilder::Command::ImportLocalVariableAnnotations.new(annots).merge!.on_duplicate! do |name, original, annotated|
      if method_params.param?(name)
        param = method_params[name]
        if result = no_subtyping?(sub_type: original, super_type: annotated)
          typing.add_error Diagnostic::Ruby::IncompatibleAnnotation.new(
            node: param.node,
            var_name: name,
            result: result,
            relation: result.relation
          )
        end
      end
    end,
    TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableDefinition.new(definition, checker.factory),
    TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableAnnotations.new(annots).merge!
  ).build(type_env)

  method_params.errors.each do |error|
    typing.add_error error
  end

  call_context = case self_type
                 when nil
                   TypeInference::MethodCall::UnknownContext.new()
                 when AST::Types::Name::Singleton
                   TypeInference::MethodCall::MethodContext.new(
                     method_name: SingletonMethodName.new(type_name: module_context.class_name, method_name: method_name)
                   )
                 when AST::Types::Name::Instance, AST::Types::Intersection
                   TypeInference::MethodCall::MethodContext.new(
                     method_name: InstanceMethodName.new(type_name: module_context.class_name, method_name: method_name)
                   )
                 else
                   raise "Unexpected self_type: #{self_type}"
                 end

  self.class.new(
    checker: checker,
    source: source,
    annotations: annots,
    context: TypeInference::Context.new(
      method_context: method_context,
      module_context: module_context,
      block_context: nil,
      break_context: nil,
      self_type: annots.self_type || self_type,
      type_env: type_env,
      call_context: call_context,
      variable_context: variable_context
    ),
    typing: typing,
  )
end

#for_sclass(node, type) ⇒ Object



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
# File 'lib/steep/type_construction.rb', line 599

def for_sclass(node, type)
  annots = source.annotations(block: node, factory: checker.factory, context: nesting)

  instance_type = if type.is_a?(AST::Types::Self)
                    context.self_type
                  else
                    type
                  end

  module_type = case instance_type
                when AST::Types::Name::Singleton
                  type_name = instance_type.name

                  case checker.factory.env.constant_entry(type_name)
                  when RBS::Environment::ModuleEntry, RBS::Environment::ModuleAliasEntry
                    AST::Builtin::Module.instance_type
                  when RBS::Environment::ClassEntry, RBS::Environment::ClassAliasEntry
                    AST::Builtin::Class.instance_type
                  else
                    raise
                  end

                when AST::Types::Name::Instance
                  instance_type.to_module
                else
                  return
                end

  instance_definition = case instance_type
                        when AST::Types::Name::Singleton
                          type_name = instance_type.name
                          checker.factory.definition_builder.build_singleton(type_name)
                        when AST::Types::Name::Instance
                          type_name = instance_type.name
                          checker.factory.definition_builder.build_instance(type_name)
                        else
                          return
                        end

  module_definition = case module_type
                      when AST::Types::Name::Singleton
                        type_name = module_type.name
                        checker.factory.definition_builder.build_singleton(type_name)
                      else
                        nil
                      end

  module_context = TypeInference::Context::ModuleContext.new(
    instance_type: annots.instance_type || instance_type,
    module_type: annots.self_type || annots.module_type || module_type,
    implement_name: nil,
    nesting: nesting,
    class_name: self.module_context.class_name,
    module_definition: module_definition,
    instance_definition: instance_definition
  )

  singleton_definition = checker.factory.definition_builder.build_singleton(module_context.class_name)
  type_env =
    TypeInference::TypeEnvBuilder.new(
      TypeInference::TypeEnvBuilder::Command::ImportGlobalDeclarations.new(checker.factory),
      TypeInference::TypeEnvBuilder::Command::ImportConstantAnnotations.new(annots),
      TypeInference::TypeEnvBuilder::Command::ImportLocalVariableAnnotations.new(annots),
      TypeInference::TypeEnvBuilder::Command::ImportInstanceVariableDefinition.new(instance_definition, checker.factory)
    ).build(TypeInference::TypeEnv.new(context.type_env.constant_env))

  body_context = TypeInference::Context.new(
    method_context: nil,
    block_context: nil,
    module_context: module_context,
    break_context: nil,
    self_type: meta_type(annots.self_type || type) || AST::Builtin::Class.module_type,
    type_env: type_env,
    call_context: TypeInference::MethodCall::ModuleContext.new(type_name: module_context.class_name),
    variable_context: TypeInference::Context::TypeVariableContext.empty  # Assuming `::Class` and `::Module` don't have type params
  )

  self.class.new(
    checker: checker,
    source: source,
    annotations: annots,
    typing: typing,
    context: body_context
  )
end

#gvasgn(node, rhs_type) ⇒ Object



2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
# File 'lib/steep/type_construction.rb', line 2842

def gvasgn(node, rhs_type)
  name = node.children[0]

  lhs_type = context.type_env[name]

  if lhs_type
    if result = no_subtyping?(sub_type: rhs_type, super_type: lhs_type)
      typing.add_error(
        Diagnostic::Ruby::IncompatibleAssignment.new(node: node, lhs_type: lhs_type, rhs_type: rhs_type, result: result)
      )
    end
  else
    typing.add_error(Diagnostic::Ruby::UnknownGlobalVariable.new(node: node, name: name))
  end

  add_typing(node, type: rhs_type)
end

#implement_module(module_name:, super_name: nil, annotations:) ⇒ Object



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/steep/type_construction.rb', line 309

def implement_module(module_name:, super_name: nil, annotations:)
  if (annotation = annotations.implement_module_annotation)
    absolute_name(annotation.name.name).yield_self do |absolute_name|
      if checker.factory.class_name?(absolute_name) || checker.factory.module_name?(absolute_name)
        AST::Annotation::Implements::Module.new(
          name: absolute_name,
          args: annotation.name.args
        )
      else
        Steep.logger.error "Unknown class name given to @implements: #{annotation.name.name}"
        nil
      end
    end
  else
    name = module_name || super_name

    if name && checker.factory.env.module_name?(name)
      definition = checker.factory.definition_builder.build_instance(name)

      AST::Annotation::Implements::Module.new(
        name: name,
        args: definition.type_params
      )
    end
  end
end

#inspectObject



35
36
37
38
# File 'lib/steep/type_construction.rb', line 35

def inspect
  s = "#<%s:%#018x " % [self.class, object_id]
  s + ">"
end

#instance_type(type) ⇒ Object



5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
# File 'lib/steep/type_construction.rb', line 5324

def instance_type(type)
  case type
  when AST::Types::Union
    AST::Types::Union.build(
      types: type.types.map {|t| instance_type(t) or return }
    )
  when AST::Types::Intersection
    AST::Types::Intersection.build(
      types: type.types.map {|t| instance_type(t) or return }
    )
  else
    if name = type_name(type)
      checker.factory.instance_type(name)
    end
  end
end

#ivasgn(node, rhs_type) ⇒ Object



2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
# File 'lib/steep/type_construction.rb', line 2824

def ivasgn(node, rhs_type)
  name = node.children[0]

  lhs_type = context.type_env[name]

  if lhs_type
    if (result = check_relation(sub_type: rhs_type, super_type: lhs_type)).failure?
      typing.add_error(
        Diagnostic::Ruby::IncompatibleAssignment.new(node: node, lhs_type: lhs_type, rhs_type: rhs_type, result: result)
      )
    end
  else
    typing.add_error(Diagnostic::Ruby::UnknownInstanceVariable.new(node: node, name: name))
  end

  add_typing(node, type: rhs_type)
end

#lvasgn(node, type) ⇒ Object



2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
# File 'lib/steep/type_construction.rb', line 2798

def lvasgn(node, type)
  name = node.children[0]

  if SPECIAL_LVAR_NAMES.include?(name)
    add_typing(node, type: AST::Builtin.any_type)
  else
    if enforced_type = context.type_env.enforced_type(name)
      if result = no_subtyping?(sub_type: type, super_type: enforced_type)
        typing.add_error(
          Diagnostic::Ruby::IncompatibleAssignment.new(
            node: node,
            lhs_type: enforced_type,
            rhs_type: type,
            result: result
          )
        )

        type = enforced_type
      end
    end

    update_type_env {|env| env.assign_local_variable(name, type, enforced_type) }
      .add_typing(node, type: type)
  end
end

#masgn_lhs?(lhs) ⇒ Boolean

Returns:

  • (Boolean)


2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
# File 'lib/steep/type_construction.rb', line 2787

def masgn_lhs?(lhs)
  lhs.children.all? do |a|
    asgn_type = if a.type == :splat
                  a.children[0]&.type
                else
                  a.type
                end
    asgn_type.nil? || asgn_type == :lvasgn || asgn_type == :ivasgn || asgn_type == :gvasgn
  end
end

#meta_type(type) ⇒ Object



590
591
592
593
594
595
596
597
# File 'lib/steep/type_construction.rb', line 590

def meta_type(type)
  case type
  when AST::Types::Name::Instance
    type.to_module
  when AST::Types::Name::Singleton
    AST::Builtin::Class.instance_type
  end
end

#method_contextObject



59
60
61
# File 'lib/steep/type_construction.rb', line 59

def method_context
  context.method_context
end

#method_context!Object



63
64
65
# File 'lib/steep/type_construction.rb', line 63

def method_context!
  method_context or raise
end

#module_contextObject



55
56
57
# File 'lib/steep/type_construction.rb', line 55

def module_context
  context.module_context
end

#namespace_module?(node) ⇒ Boolean

Returns:

  • (Boolean)


4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
# File 'lib/steep/type_construction.rb', line 4865

def namespace_module?(node)
  # @type var nodes: Array[Parser::AST::Node]
  nodes =
    case node.type
    when :class, :module
      node.children.last&.yield_self {|child|
        if child.type == :begin
          child.children
        else
          [child]
        end
      } || []
    else
      return false
    end

  !nodes.empty? && nodes.all? {|child| child.type == :class || child.type == :module}
end

#nestingObject



4705
4706
4707
# File 'lib/steep/type_construction.rb', line 4705

def nesting
  module_context&.nesting
end

#no_subtyping?(sub_type:, super_type:, constraints: Subtyping::Constraints.empty) ⇒ Boolean

Returns:

  • (Boolean)


149
150
151
152
153
154
# File 'lib/steep/type_construction.rb', line 149

def no_subtyping?(sub_type:, super_type:, constraints: Subtyping::Constraints.empty)
  result = check_relation(sub_type: sub_type, super_type: super_type, constraints: constraints)
  if result.failure?
    result
  end
end

#optional_proc?(type) ⇒ Boolean

Returns:

  • (Boolean)


3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
# File 'lib/steep/type_construction.rb', line 3086

def optional_proc?(type)
  if type.is_a?(AST::Types::Union)
    if type.types.size == 2
      if type.types.find {|t| t.is_a?(AST::Types::Nil) }
        if proc_type = type.types.find {|t| t.is_a?(AST::Types::Proc) }
          proc_type #: AST::Types::Proc
        end
      end
    end
  end
end

#partition_flatten_types(type, &block) ⇒ Object



4911
4912
4913
4914
# File 'lib/steep/type_construction.rb', line 4911

def partition_flatten_types(type, &block)
  types = flatten_union(deep_expand_alias(type) || type)
  types.partition(&block)
end

#pick_one_of(types) ⇒ Object



5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
# File 'lib/steep/type_construction.rb', line 5270

def pick_one_of(types)
  types.each do |type|
    with_child_typing() do |constr|
      if (type_, constr = yield(type, constr))
        constr.check_relation(sub_type: type_, super_type: type).then do
          constr = constr.save_typing
          return Pair.new(type: type_, constr: constr)
        end
      end
    end
  end

  nil
end

#pure_send?(call, receiver, arguments) ⇒ Boolean

Returns:

  • (Boolean)


3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
# File 'lib/steep/type_construction.rb', line 3256

def pure_send?(call, receiver, arguments)
  return false unless call.node.type == :send || call.node.type == :csend
  return false unless call.pure? || KNOWN_PURE_METHODS.superset?(Set.new(call.method_decls.map(&:method_name)))

  argishes = [*arguments]
  argishes << receiver if receiver

  argishes.all? do |node|
    value_node?(node) || context.type_env[node]
  end
end

#save_typingObject



5285
5286
5287
5288
# File 'lib/steep/type_construction.rb', line 5285

def save_typing
  typing.save!
  with_new_typing(typing.parent || raise)
end

#select_flatten_types(type, &block) ⇒ Object



4906
4907
4908
4909
# File 'lib/steep/type_construction.rb', line 4906

def select_flatten_types(type, &block)
  types = flatten_union(deep_expand_alias(type) || type)
  types.select(&block)
end

#self_typeObject



79
80
81
# File 'lib/steep/type_construction.rb', line 79

def self_type
  context.self_type
end

#semantically_arrayish_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
# File 'lib/steep/type_construction.rb', line 5064

def semantically_arrayish_type?(type)
  union = AST::Types::Union.build(types: flatten_union(type))
  if union.is_a?(AST::Types::Union)
    if tuple = union_of_tuple_to_tuple_of_union(union)
      return tuple
    end
  end

  var = AST::Types::Var.fresh(:Elem)
  array = AST::Builtin::Array.instance_type(var)
  constraints = Subtyping::Constraints.new(unknowns: [])
  constraints.add_var(var.name)

  if (result = check_relation(sub_type: type, super_type: array, constraints: constraints)).success?
    context = Subtyping::Constraints::Context.new(
      variance: Subtyping::VariableVariance.from_type(union_type(type, var)),
      self_type: self_type,
      instance_type: module_context.instance_type,
      class_type: module_context.module_type
    )

    variables = (type.free_variables + [var.name]).filter_map do |name|
      case name
      when Symbol
        name
      end
    end
    subst = constraints.solution(checker, variables: variables, context: context)

    type.subst(subst)
  end
end

#set_up_block_mlhs_params_env(node, type, hash, &block) ⇒ Object



4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
# File 'lib/steep/type_construction.rb', line 4529

def set_up_block_mlhs_params_env(node, type, hash, &block)
  if arrayish = try_convert_to_array(type)
    masgn = TypeInference::MultipleAssignment.new()
    assignments = masgn.expand(node, arrayish, false) or raise "#{arrayish} is expected to be array-ish"
    assignments.leading_assignments.each do |pair|
      node, type = pair

      if node.type == :arg
        hash[node.children[0]] = type
      else
        set_up_block_mlhs_params_env(node, type, hash, &block)
      end
    end
  else
    yield node, type
  end
end

#singleton_type(type) ⇒ Object



5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
# File 'lib/steep/type_construction.rb', line 5307

def singleton_type(type)
  case type
  when AST::Types::Union
    AST::Types::Union.build(
      types: type.types.map {|t| singleton_type(t) or return }
    )
  when AST::Types::Intersection
    AST::Types::Intersection.build(
      types: type.types.map {|t| singleton_type(t) or return }
    )
  else
    if name = type_name(type)
      AST::Types::Name::Singleton.new(name: name)
    end
  end
end

#synthesize(node, hint: nil, condition: false) ⇒ Object



732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
# File 'lib/steep/type_construction.rb', line 732

def synthesize(node, hint: nil, condition: false)
  Steep.logger.tagged "synthesize:(#{node.location&.yield_self {|loc| loc.expression.to_s.split(/:/, 2).last } || "-"})" do
    Steep.logger.debug node.type
    case node.type
    when :begin, :kwbegin
      yield_self do
        end_pos = node.loc.expression.end_pos

        *mid_nodes, last_node = each_child_node(node).to_a
        if last_node
          pair = mid_nodes.inject(Pair.new(type: AST::Builtin.nil_type, constr: self)) do |pair, node|
            pair.constr.synthesize(node).yield_self {|p| pair + p }.tap do |new_pair|
              if new_pair.constr.context != pair.constr.context
                # update context
                range = node.loc.expression.end_pos..end_pos
                typing.cursor_context.set(range, new_pair.constr.context)
              end
            end
          end

          p = pair.constr.synthesize(last_node, hint: hint, condition: condition)
          last_pair = pair + p
          last_pair.constr.add_typing(node, type: last_pair.type, constr: last_pair.constr)
        else
          add_typing(node, type: AST::Builtin.nil_type)
        end
      end

    when :lvasgn
      yield_self do
        name, rhs = node.children

        case name
        when :_, :__any__
          synthesize(rhs, hint: AST::Builtin.any_type).yield_self do |pair|
            add_typing(node, type: AST::Builtin.any_type, constr: pair.constr)
          end
        when :__skip__
          add_typing(node, type: AST::Builtin.any_type)
        else
          if enforced_type = context.type_env.enforced_type(name)
            case
            when !hint
              hint = enforced_type
            when check_relation(sub_type: enforced_type, super_type: hint).success?
              # enforced_type is compatible with hint and more specific to hint.
              # This typically happens when hint is untyped, top, or void.
              hint = enforced_type
            end
          end

          if rhs
            rhs_type, rhs_constr, rhs_context = synthesize(rhs, hint: hint).to_ary

            constr = rhs_constr.update_type_env do |type_env|
              var_type = rhs_type

              if enforced_type = type_env.enforced_type(name)
                if result = no_subtyping?(sub_type: rhs_type, super_type: enforced_type)
                  typing.add_error(
                    Diagnostic::Ruby::IncompatibleAssignment.new(
                      node: node,
                      lhs_type: enforced_type,
                      rhs_type: rhs_type,
                      result: result
                    )
                  )

                  var_type = enforced_type
                end

                if rhs_type.is_a?(AST::Types::Any)
                  var_type = enforced_type
                end
              end

              type_env.assign_local_variable(name, var_type, enforced_type)
            end

            constr.add_typing(node, type: rhs_type)
          else
            add_typing(node, type: enforced_type || AST::Builtin.any_type)
          end
        end
      end

    when :lvar
      yield_self do
        var = node.children[0]

        if SPECIAL_LVAR_NAMES.include?(var)
          add_typing node, type: AST::Builtin.any_type
        else
          if (type = context.type_env[var])
            add_typing node, type: type
          else
            fallback_to_any(node)
          end
        end
      end

    when :ivasgn
      name = node.children[0]
      rhs = node.children[1]

      rhs_type, constr = synthesize(rhs, hint: context.type_env[name])

      constr.ivasgn(node, rhs_type)

    when :ivar
      yield_self do
        name = node.children[0]

        if type = context.type_env[name]
          add_typing(node, type: type)
        else
          fallback_to_any node
        end
      end

    when :match_with_lvasgn
      each_child_node(node) do |child|
        synthesize(child)
      end
      add_typing(node, type: AST::Builtin.any_type)

    when :op_asgn
      yield_self do
        lhs, op, rhs = node.children

        case lhs.type
        when :lvasgn
          var_node = lhs.updated(:lvar)
          send_node = rhs.updated(:send, [var_node, op, rhs])
          new_node = node.updated(:lvasgn, [lhs.children[0], send_node])

          type, constr = synthesize(new_node, hint: hint)

          constr.add_typing(node, type: type)

        when :ivasgn
          var_node = lhs.updated(:ivar)
          send_node = rhs.updated(:send, [var_node, op, rhs])
          new_node = node.updated(:ivasgn, [lhs.children[0], send_node])

          type, constr = synthesize(new_node, hint: hint)

          constr.add_typing(node, type: type)

        when :cvasgn
          var_node = lhs.updated(:cvar)
          send_node = rhs.updated(:send, [var_node, op, rhs])
          new_node = node.updated(:cvasgn, [lhs.children[0], send_node])

          type, constr = synthesize(new_node, hint: hint)

          constr.add_typing(node, type: type)

        when :gvasgn
          var_node = lhs.updated(:gvar)
          send_node = rhs.updated(:send, [var_node, op, rhs])
          new_node = node.updated(:gvasgn, [lhs.children[0], send_node])

          type, constr = synthesize(new_node, hint: hint)

          constr.add_typing(node, type: type)

        when :send
          new_rhs = rhs.updated(:send, [lhs, node.children[1], node.children[2]])
          new_node = lhs.updated(:send, [lhs.children[0], :"#{lhs.children[1]}=", *lhs.children.drop(2), new_rhs])

          type, constr = synthesize(new_node, hint: hint)

          constr.add_typing(node, type: type)

        else
          Steep.logger.error("Unexpected op_asgn lhs: #{lhs.type}")

          _, constr = synthesize(rhs)
          constr.add_typing(node, type: AST::Builtin.any_type)
        end
      end

    when :super
      yield_self do
        if self_type && method_context!.method
          if super_def = method_context!.super_method
            super_method = Interface::Shape::Entry.new(
              method_name: method_context!.name,
              private_method: true,
              overloads: super_def.defs.map {|type_def|
                type = checker.factory.method_type(type_def.type)
                Interface::Shape::MethodOverload.new(type, [type_def])
              }
            )

            call, constr = type_method_call(
              node,
              receiver_type: self_type,
              method_name: method_context!.name || raise("method context must have a name"),
              method: super_method,
              arguments: node.children,
              block_params: nil,
              block_body: nil,
              tapp: nil,
              hint: hint
            )

            if call && constr
              constr.add_call(call)
            else
              error = Diagnostic::Ruby::UnresolvedOverloading.new(
                node: node,
                receiver_type: self_type,
                method_name: method_context!.name,
                method_types: super_method.method_types
              )
              call = TypeInference::MethodCall::Error.new(
                node: node,
                context: context.call_context,
                method_name: method_context!.name || raise("method context must have a name"),
                receiver_type: self_type,
                errors: [error]
              )

              constr = synthesize_children(node)

              fallback_to_any(node) { error }
            end
          else
            type_check_untyped_args(node.children).fallback_to_any(node) do
              Diagnostic::Ruby::UnexpectedSuper.new(node: node, method: method_context!.name)
            end
          end
        else
          type_check_untyped_args(node.children).fallback_to_any(node)
        end
      end

    when :def
      yield_self do
        # @type var node: Parser::AST::Node & Parser::AST::_DefNode

        name, args_node, body_node = node.children

        with_method_constr(
          name,
          node,
          args: args_node.children,
          self_type: module_context&.instance_type,
          definition: module_context&.instance_definition
        ) do |new|
          # @type var new: TypeConstruction

          new.typing.cursor_context.set_node_context(node, new.context)
          new.typing.cursor_context.set_body_context(node, new.context)

          new.method_context!.tap do |method_context|
            if method_context.method
              if owner = method_context.method.implemented_in || method_context.method.defined_in
                method_name = InstanceMethodName.new(type_name: owner, method_name: name)
                new.typing.source_index.add_definition(method: method_name, definition: node)
              end
            end
          end

          new = new.synthesize_children(args_node)

          body_pair = if body_node
                        return_type = expand_alias(new.method_context!.return_type)
                        if !return_type.is_a?(AST::Types::Void)
                          new.check(body_node, return_type) do |_, actual_type, result|
                            if new.method_context!.attribute_setter?
                              typing.add_error(
                                Diagnostic::Ruby::SetterBodyTypeMismatch.new(
                                  node: node,
                                  expected: new.method_context!.return_type,
                                  actual: actual_type,
                                  result: result,
                                  method_name: new.method_context!.name
                                )
                              )
                            else
                              typing.add_error(
                                Diagnostic::Ruby::MethodBodyTypeMismatch.new(
                                  node: node,
                                  expected: new.method_context!.return_type,
                                  actual: actual_type,
                                  result: result
                                )
                              )
                            end
                          end
                        else
                          new.synthesize(body_node)
                        end
                      else
                        return_type = expand_alias(new.method_context!.return_type)
                        if !return_type.is_a?(AST::Types::Void)
                          result = check_relation(sub_type: AST::Builtin.nil_type, super_type: return_type)
                          if result.failure?
                            if new.method_context!.attribute_setter?
                              typing.add_error(
                                Diagnostic::Ruby::SetterBodyTypeMismatch.new(
                                  node: node,
                                  expected: new.method_context!.return_type,
                                  actual: AST::Builtin.nil_type,
                                  result: result,
                                  method_name: new.method_context!.name
                                )
                              )
                            else
                              typing.add_error(
                                Diagnostic::Ruby::MethodBodyTypeMismatch.new(
                                  node: node,
                                  expected: new.method_context!.return_type,
                                  actual: AST::Builtin.nil_type,
                                  result: result
                                )
                              )
                            end
                          end
                        end

                        Pair.new(type: AST::Builtin.nil_type, constr: new)
                      end

          if body_node
            # Add context to ranges from the end of the method body to the beginning of the `end` keyword
            if node.loc.end
              # Skip end-less def
              begin_pos = body_node.loc.expression.end_pos
              end_pos = node.loc.end.begin_pos
              typing.cursor_context.set(begin_pos..end_pos, body_pair.context)
            end
          end

          if module_context
            module_context.defined_instance_methods << node.children[0]
          end

          add_typing(node, type: AST::Builtin::Symbol.instance_type)
        end
      end

    when :defs
      synthesize(node.children[0]).type.tap do |self_type|
        self_type = expand_self(self_type)
        definition =
          case self_type
          when AST::Types::Name::Instance
            name = self_type.name
            checker.factory.definition_builder.build_instance(name)
          when AST::Types::Name::Singleton
            name = self_type.name
            checker.factory.definition_builder.build_singleton(name)
          end

        args_node = node.children[2]
        new = for_new_method(
          node.children[1],
          node,
          args: args_node.children,
          self_type: self_type,
          definition: definition
        )
        new.typing.cursor_context.set_node_context(node, new.context)
        new.typing.cursor_context.set_body_context(node, new.context)

        new.method_context!.tap do |method_context|
          if method_context.method
            name_ = node.children[1]

            method_name =
              case self_type
              when AST::Types::Name::Instance
                InstanceMethodName.new(type_name: method_context.method.implemented_in || raise, method_name: name_)
              when AST::Types::Name::Singleton
                SingletonMethodName.new(type_name: method_context.method.implemented_in || raise, method_name: name_)
              end

            new.typing.source_index.add_definition(method: method_name, definition: node)
          end
        end

        new = new.synthesize_children(args_node)

        each_child_node(node.children[2]) do |arg|
          new.synthesize(arg)
        end

        if node.children[3]
          return_type = expand_alias(new.method_context!.return_type)
          if !return_type.is_a?(AST::Types::Void)
            new.check(node.children[3], return_type) do |return_type, actual_type, result|
              typing.add_error(
                Diagnostic::Ruby::MethodBodyTypeMismatch.new(
                  node: node,
                  expected: return_type,
                  actual: actual_type,
                  result: result
                )
              )
            end
          else
            new.synthesize(node.children[3])
          end
        end
      end

      if node.children[0].type == :self
        module_context.defined_module_methods << node.children[1]
      end

      add_typing(node, type: AST::Builtin::Symbol.instance_type)

    when :return
      yield_self do
        method_return_type =
          if method_context
            expand_alias(method_context.return_type)
          end

        case node.children.size
        when 0
          value_type = AST::Builtin.nil_type
          constr = self
        when 1
          return_value_node = node.children[0]
          value_type, constr = synthesize(return_value_node, hint: method_return_type)
        else
          # It returns an array
          array = node.updated(:array)
          value_type, constr = synthesize(array, hint: method_return_type)
        end

        if method_return_type
          unless method_context.nil? || method_return_type.is_a?(AST::Types::Void)
            result = constr.check_relation(sub_type: value_type, super_type: method_return_type)

            if result.failure?
              if method_context.attribute_setter?
                typing.add_error(
                  Diagnostic::Ruby::SetterReturnTypeMismatch.new(
                    node: node,
                    method_name: method_context.name,
                    expected: method_return_type,
                    actual: value_type,
                    result: result
                  )
                )
              else
                typing.add_error(
                  Diagnostic::Ruby::ReturnTypeMismatch.new(
                    node: node,
                    expected: method_return_type,
                    actual: value_type,
                    result: result
                  )
                )
              end
            end
          end
        end

        constr.add_typing(node, type: AST::Builtin.bottom_type)
      end

    when :break
      value = node.children[0]

      if break_context
        break_type = break_context.break_type

        if value
          check(value, break_type) do |break_type, actual_type, result|
            typing.add_error(
              Diagnostic::Ruby::BreakTypeMismatch.new(
                node: node,
                expected: break_type,
                actual: actual_type,
                result: result
              )
            )
          end
        else
          unless break_type.is_a?(AST::Types::Bot)
            check_relation(sub_type: AST::Builtin.nil_type, super_type: break_type).else do |result|
              typing.add_error(
                Diagnostic::Ruby::ImplicitBreakValueMismatch.new(
                  node: node,
                  jump_type: break_type,
                  result: result
                )
              )
            end
          end
        end
      else
        synthesize(value) if value
        typing.add_error Diagnostic::Ruby::UnexpectedJump.new(node: node)
      end

      add_typing(node, type: AST::Builtin.bottom_type)

    when :next
      value = node.children[0]

      if break_context
        if next_type = break_context.next_type
          next_type = deep_expand_alias(next_type) || next_type

          if value
            _, constr = check(value, next_type) do |break_type, actual_type, result|
              typing.add_error(
                Diagnostic::Ruby::BreakTypeMismatch.new(
                  node: node,
                  expected: break_type,
                  actual: actual_type,
                  result: result
                )
              )
            end
          else
            check_relation(sub_type: AST::Builtin.nil_type, super_type: next_type).else do |result|
              typing.add_error(
                Diagnostic::Ruby::BreakTypeMismatch.new(
                  node: node,
                  expected: next_type,
                  actual: AST::Builtin.nil_type,
                  result: result
                )
              )
            end
          end
        else
          if value
            synthesize(value)
            typing.add_error Diagnostic::Ruby::UnexpectedJumpValue.new(node: node)
          end
        end
      else
        synthesize(value) if value
        typing.add_error Diagnostic::Ruby::UnexpectedJump.new(node: node)
      end

      add_typing(node, type: AST::Builtin.bottom_type)

    when :retry
      add_typing(node, type: AST::Builtin.bottom_type)

    when :procarg0
      yield_self do
        constr = self #: TypeConstruction

        node.children.each do |arg|
          if arg.is_a?(Symbol)
            if SPECIAL_LVAR_NAMES === arg
              _, constr = add_typing(node, type: AST::Builtin.any_type)
            else
              type = context.type_env[arg]

              if type
                _, constr = add_typing(node, type: type)
              else
                type = AST::Builtin.any_type
                _, constr = lvasgn(node, type)
              end
            end
          else
            _, constr = constr.synthesize(arg)
          end
        end

        Pair.new(constr: constr, type: AST::Builtin.any_type)
      end

    when :mlhs
      yield_self do
        constr = self #: TypeConstruction

        node.children.each do |arg|
          _, constr = constr.synthesize(arg)
        end

        Pair.new(constr: constr, type: AST::Builtin.any_type)
      end

    when :arg, :kwarg
      yield_self do
        var = node.children[0]

        if SPECIAL_LVAR_NAMES.include?(var)
          add_typing(node, type: AST::Builtin.any_type)
        else
          type = context.type_env[var]

          if type
            add_typing(node, type: type)
          else
            type = AST::Builtin.any_type
            lvasgn(node, type)
          end
        end
      end

    when :optarg, :kwoptarg
      yield_self do
        var = node.children[0]
        rhs = node.children[1]

        if SPECIAL_LVAR_NAMES.include?(var)
          synthesize(rhs)
          add_typing(node, type: AST::Builtin.any_type)
        else
          var_type = context.type_env[var]

          if var_type
            type, constr = check(rhs, var_type) do |expected_type, actual_type, result|
              typing.add_error(
                Diagnostic::Ruby::IncompatibleAssignment.new(
                  node: node,
                  lhs_type: expected_type,
                  rhs_type: actual_type,
                  result: result
                )
              )
            end
          else
            type, constr = synthesize(rhs)
          end

          constr.add_typing(node, type: type)
        end
      end

    when :restarg
      yield_self do
        var = node.children[0]

        if !var || SPECIAL_LVAR_NAMES.include?(var)
          return add_typing(node, type: AST::Builtin.any_type)
        end

        type = context.type_env[var]

        unless type
          if context.method_context&.method_type
            Steep.logger.error { "Unknown variable: #{node}" }
          end
          typing.add_error Diagnostic::Ruby::FallbackAny.new(node: node)
          type = AST::Builtin::Array.instance_type(AST::Builtin.any_type)
        end

        add_typing(node, type: type)
      end

    when :kwrestarg
      yield_self do
        var = node.children[0]

        if !var || SPECIAL_LVAR_NAMES.include?(var)
          return add_typing(node, type: AST::Builtin.any_type)
        end

        type = context.type_env[var]
        unless type
          if context.method_context&.method_type
            Steep.logger.error { "Unknown variable: #{node}" }
          end
          typing.add_error Diagnostic::Ruby::FallbackAny.new(node: node)
          type = AST::Builtin::Hash.instance_type(AST::Builtin::Symbol.instance_type, AST::Builtin.any_type)
        end

        add_typing(node, type: type)
      end

    when :float
      add_typing(node, type: AST::Builtin::Float.instance_type)

    when :rational
      add_typing(node, type: AST::Types::Name::Instance.new(name: RBS::TypeName.parse("::Rational"), args: []))

    when :complex
      add_typing(node, type: AST::Types::Name::Instance.new(name: RBS::TypeName.parse("::Complex"), args: []))

    when :nil
      add_typing(node, type: AST::Builtin.nil_type)

    when :int
      yield_self do
        literal_type = test_literal_type(node.children[0], hint)

        if literal_type
          add_typing(node, type: literal_type)
        else
          add_typing(node, type: AST::Builtin::Integer.instance_type)
        end
      end

    when :sym
      yield_self do
        literal_type = test_literal_type(node.children[0], hint)

        if literal_type
          add_typing(node, type: literal_type)
        else
          add_typing(node, type: AST::Builtin::Symbol.instance_type)
        end
      end

    when :str
      yield_self do
        literal_type = test_literal_type(node.children[0], hint)

        if literal_type
          add_typing(node, type: literal_type)
        else
          add_typing(node, type: AST::Builtin::String.instance_type)
        end
      end

    when :true, :false
      ty = node.type == :true ? AST::Types::Literal.new(value: true) : AST::Types::Literal.new(value: false)

      case
      when hint && check_relation(sub_type: ty, super_type: hint).success? && !hint.is_a?(AST::Types::Any) && !hint.is_a?(AST::Types::Top)
        add_typing(node, type: unwrap(hint))
      when condition
        add_typing(node, type: ty)
      else
        add_typing(node, type: AST::Types::Boolean.instance)
      end

    when :hash, :kwargs
      # :kwargs happens for method calls with keyword argument, but the method doesn't have keyword params.
      # Conversion from kwargs to hash happens, and this when-clause is to support it.
      type_hash(node, hint: hint).tap do |pair|
        if pair.type == AST::Builtin::Hash.instance_type(fill_untyped: true)
          case hint
          when AST::Types::Any, AST::Types::Top, AST::Types::Void
            # ok
          else
            unless hint == pair.type
              pair.constr.typing.add_error Diagnostic::Ruby::UnannotatedEmptyCollection.new(node: node)
            end
          end
        end
      end

    when :dstr, :xstr
      each_child_node(node) do |child|
        synthesize(child)
      end

      add_typing(node, type: AST::Builtin::String.instance_type)

    when :dsym
      each_child_node(node) do |child|
        synthesize(child)
      end

      add_typing(node, type: AST::Builtin::Symbol.instance_type)

    when :class
      yield_self do
        constr = self

        # @type var name_node: Parser::AST::Node
        # @type var super_node: Parser::AST::Node?

        name_node, super_node, _ = node.children

        if name_node.type == :const
          _, constr, class_name = synthesize_constant_decl(name_node, name_node.children[0], name_node.children[1]) do
            typing.add_error(
              Diagnostic::Ruby::UnknownConstant.new(node: name_node, name: name_node.children[1]).class!
            )
          end

          if class_name
            check_deprecation_constant(class_name, name_node, name_node.location.expression)
          end
        else
          _, constr = synthesize(name_node)
        end

        if class_name
          typing.source_index.add_definition(constant: class_name, definition: name_node)
        end

        if super_node
          if super_node.type == :const
            _, constr, super_name = constr.synthesize_constant(super_node, super_node.children[0], super_node.children[1]) do
              typing.add_error(
                Diagnostic::Ruby::UnknownConstant.new(node: super_node, name: super_node.children[1]).class!
              )
            end

            if super_name
              typing.source_index.add_reference(constant: super_name, ref: super_node)
            end
          else
            _, constr = synthesize(super_node, hint: nil, condition: false)
          end
        end

        with_class_constr(node, class_name, super_name) do |constructor|
          if module_type = constructor.module_context&.module_type
            _, constructor = constructor.add_typing(name_node, type: module_type)
          else
            _, constructor = constructor.fallback_to_any(name_node)
          end

          constructor.typing.cursor_context.set_node_context(node, constructor.context)
          constructor.typing.cursor_context.set_body_context(node, constructor.context)

          constructor.synthesize(node.children[2]) if node.children[2]

          if constructor.module_context&.implement_name && !namespace_module?(node)
            constructor.validate_method_definitions(node, constructor.module_context.implement_name || raise)
          end
        end

        add_typing(node, type: AST::Builtin.nil_type)
      end

    when :module
      yield_self do
        constr = self

        # @type var name_node: Parser::AST::Node
        name_node, _ = node.children

        if name_node.type == :const
          _, constr, module_name = synthesize_constant_decl(name_node, name_node.children[0], name_node.children[1]) do
            typing.add_error Diagnostic::Ruby::UnknownConstant.new(node: name_node, name: name_node.children[1]).module!
          end

          if module_name
            check_deprecation_constant(module_name, name_node, name_node.location.expression)
          end
        else
          _, constr = synthesize(name_node)
        end

        if module_name
          constr.typing.source_index.add_definition(constant: module_name, definition: name_node)
        end

        with_module_constr(node, module_name) do |constructor|
          if module_type = constructor.module_context&.module_type
            _, constructor = constructor.add_typing(name_node, type: module_type)
          else
            _, constructor = constructor.fallback_to_any(name_node)
          end

          constructor.typing.cursor_context.set_node_context(node, constructor.context)
          constructor.typing.cursor_context.set_body_context(node, constructor.context)

          constructor.synthesize(node.children[1]) if node.children[1]

          if constructor.module_context&.implement_name && !namespace_module?(node)
            constructor.validate_method_definitions(node, constructor.module_context.implement_name || raise)
          end
        end

        add_typing(node, type: AST::Builtin.nil_type)
      end

    when :sclass
      yield_self do
        type, constr = synthesize(node.children[0]).to_ary

        with_sclass_constr(node, type) do |constructor|
          unless constructor
            typing.add_error(
              Diagnostic::Ruby::UnsupportedSyntax.new(
                node: node,
                message: "sclass receiver must be instance type or singleton type, but type given `#{type}`"
              )
            )
            return constr.add_typing(node, type: AST::Builtin.nil_type)
          end

          constructor.typing.cursor_context.set_node_context(node, constructor.context)
          constructor.typing.cursor_context.set_body_context(node, constructor.context)

          constructor.synthesize(node.children[1]) if node.children[1]

          if constructor.module_context.instance_definition && module_context.module_definition
            if constructor.module_context.instance_definition.type_name == module_context.module_definition.type_name
              module_context.defined_module_methods.merge(constructor.module_context.defined_instance_methods)
            end
          end
        end

        constr.add_typing(node, type: AST::Builtin.nil_type)
      end

    when :self
      add_typing node, type: AST::Types::Self.instance

    when :cbase
      add_typing node, type: AST::Types::Void.instance

    when :const
      yield_self do
        type, constr, name = synthesize_constant(node, node.children[0], node.children[1])

        if name
          typing.source_index.add_reference(constant: name, ref: node)
          constr.check_deprecation_constant(name, node, node.location.expression)
        end

        Pair.new(type: type, constr: constr)
      end

    when :casgn
      yield_self do
        constant_type, constr, constant_name = synthesize_constant_decl(nil, node.children[0], node.children[1]) do
          typing.add_error(
            Diagnostic::Ruby::UnknownConstant.new(
              node: node,
              name: node.children[1]
            )
          )
        end

        if constant_name
          typing.source_index.add_definition(constant: constant_name, definition: node)
          location = node.location #: Parser::Source::Map & Parser::AST::_Variable
          constr.check_deprecation_constant(constant_name, node, location.name)
        end

        value_type, constr = constr.synthesize(node.children.last, hint: constant_type)

        result = check_relation(sub_type: value_type, super_type: constant_type)
        if result.failure?
          typing.add_error(
            Diagnostic::Ruby::IncompatibleAssignment.new(
              node: node,
              lhs_type: constant_type,
              rhs_type: value_type,
              result: result
            )
          )

          constr.add_typing(node, type: constant_type)
        else
          constr.add_typing(node, type: value_type)
        end
      end

    when :yield
      if method_context && (method_type = method_context.method_type)
        if block_type = method_context.block_type
          if block_type.type.params
            type = AST::Types::Proc.new(
              type: block_type.type,
              block: nil,
              self_type: block_type.self_type
            )
            args = TypeInference::SendArgs.new(
              node: node,
              arguments: node.children,
              type: type
            )

            # @type var errors: Array[Diagnostic::Ruby::Base]
            errors = []
            constr = type_check_args(
              nil,
              args,
              Subtyping::Constraints.new(unknowns: []),
              errors
            )

            errors.each do |error|
              typing.add_error(error)
            end
          else
            constr = type_check_untyped_args(node.children)
          end

          add_typing(node, type: block_type.type.return_type)
        elsif method_type.type.params
          typing.add_error(Diagnostic::Ruby::UnexpectedYield.new(node: node))
          fallback_to_any node
        else
          constr = type_check_untyped_args(node.children)
          add_typing(node, type: AST::Builtin.any_type)
        end
      else
        fallback_to_any node
      end

    when :zsuper
      yield_self do
        if method_context && method_context.method
          if method_context.super_method
            types = method_context.super_method.method_types.map {|method_type|
              checker.factory.method_type(method_type).type.return_type
            }
            add_typing(node, type: union_type(*types))
          else
            fallback_to_any(node) do
              Diagnostic::Ruby::UnexpectedSuper.new(node: node, method: method_context.name)
            end
          end
        else
          fallback_to_any node
        end
      end

    when :array
      yield_self do
        if node.children.empty?
          if hint
            array = AST::Builtin::Array.instance_type(AST::Builtin.any_type)
            if check_relation(sub_type: array, super_type: hint).success?
              add_typing node, type: unwrap(hint)
            else
              add_typing node, type: array
            end
          else
            typing.add_error Diagnostic::Ruby::UnannotatedEmptyCollection.new(node: node)
            add_typing node, type: AST::Builtin::Array.instance_type(AST::Builtin.any_type)
          end
        else
          if hint
            tuples = select_flatten_types(hint) {|type| type.is_a?(AST::Types::Tuple) } #: Array[AST::Types::Tuple]
            unless tuples.empty?
              fallback_pair = nil #: Pair?
              tuples.each do |tuple|
                typing.new_child() do |child_typing|
                  if pair = with_new_typing(child_typing).try_tuple_type(node, tuple)
                    if pair.constr.check_relation(sub_type: pair.type, super_type: tuple).success?
                      return pair.with(constr: pair.constr.save_typing)
                    end
                    fallback_pair ||= pair.with(constr: pair.constr.save_typing)
                  end
                end
              end
              return fallback_pair if fallback_pair
            end
          end

          if hint
            arrays = select_flatten_types(hint) {|type| AST::Builtin::Array.instance_type?(type) } #: Array[AST::Types::Name::Instance]
            unless arrays.empty?
              arrays.each do |array|
                typing.new_child() do |child_typing|
                  pair = with_new_typing(child_typing).try_array_type(node, array)
                  if pair.constr.check_relation(sub_type: pair.type, super_type: hint).success?
                    return pair.with(constr: pair.constr.save_typing)
                  end
                end
              end
            end
          end

          try_array_type(node, nil)
        end
      end

    when :and
      yield_self do
        left_node, right_node = node.children

        left_type, constr, left_context = synthesize(left_node, hint: hint, condition: true).to_ary

        interpreter = TypeInference::LogicTypeInterpreter.new(subtyping: checker, typing: typing, config: builder_config)
        left_truthy, left_falsy = interpreter.eval(env: left_context.type_env, node: left_node)

        if left_type.is_a?(AST::Types::Logic::Env)
          left_type = left_type.type
        end

        right_type, constr, right_context =
          constr
            .update_type_env { left_truthy.env }
            .tap {|constr| typing.cursor_context.set_node_context(right_node, constr.context) }
            .for_branch(right_node)
            .synthesize(right_node, hint: hint, condition: true).to_ary

        right_truthy, right_falsy = interpreter.eval(env: right_context.type_env, node: right_node)

        case
        when left_truthy.unreachable
          # Always left_falsy
          env = left_falsy.env
          type = left_falsy.type
        when left_falsy.unreachable
          # Always left_truthy ==> right
          env = right_context.type_env
          type = right_type
        when right_truthy.unreachable && right_falsy.unreachable
          env = left_falsy.env
          type = left_falsy.type
        else
          env = context.type_env.join(left_falsy.env, right_context.type_env)
          type = union_type(left_falsy.type, right_type)

          unless type.is_a?(AST::Types::Any)
            if check_relation(sub_type: type, super_type: AST::Types::Boolean.instance).success?
              type = AST::Types::Boolean.instance
            end
          end
        end

        if condition
          type = AST::Types::Logic::Env.new(
            truthy: right_truthy.env,
            falsy: context.type_env.join(left_falsy.env, right_falsy.env),
            type: type
          )
        end

        constr.update_type_env { env }.add_typing(node, type: type)
      end

    when :or
      yield_self do
        left_node, right_node = node.children

        if hint
          left_hint = union_type_unify(hint, AST::Builtin.nil_type, AST::Builtin.false_type)
        end
        left_type, constr, left_context = synthesize(left_node, hint: left_hint, condition: true).to_ary

        interpreter = TypeInference::LogicTypeInterpreter.new(subtyping: checker, typing: typing, config: builder_config)
        left_truthy, left_falsy = interpreter.eval(env: left_context.type_env, node: left_node)

        if left_type.is_a?(AST::Types::Logic::Env)
          left_type = left_type.type
        end

        right_type, constr, right_context =
          constr
            .update_type_env { left_falsy.env }
            .tap {|constr| typing.cursor_context.set_node_context(right_node, constr.context) }
            .for_branch(right_node)
            .synthesize(right_node, hint: left_truthy.type, condition: true).to_ary

        right_truthy, right_falsy = interpreter.eval(env: right_context.type_env, node: right_node)

        case
        when left_falsy.unreachable
          env = left_truthy.env
          type = left_truthy.type
        when left_truthy.unreachable
          # Always left_falsy ==> right
          env = right_context.type_env
          type = right_type
        when right_truthy.unreachable && right_falsy.unreachable
          env = left_truthy.env
          type = left_truthy.type
        else
          env = context.type_env.join(left_truthy.env, right_context.type_env)
          type = union_type(left_truthy.type, right_type)

          unless type.is_a?(AST::Types::Any)
            if check_relation(sub_type: type, super_type: AST::Types::Boolean.instance).success?
              type = AST::Types::Boolean.instance
            end
          end
        end

        if condition
          type = AST::Types::Logic::Env.new(
            truthy: context.type_env.join(left_truthy.env, right_truthy.env),
            falsy: right_falsy.env,
            type: type
          )
        end

        constr.update_type_env { env }.add_typing(node, type: type)
      end

    when :if
      yield_self do
        cond, true_clause, false_clause = node.children

        cond_type, constr = synthesize(cond, condition: true).to_ary
        interpreter = TypeInference::LogicTypeInterpreter.new(subtyping: checker, typing: constr.typing, config: builder_config)
        truthy, falsy = interpreter.eval(env: constr.context.type_env, node: cond)

        if true_clause
          true_pair =
            constr
              .update_type_env { truthy.env }
              .for_branch(true_clause)
              .tap {|constr| typing.cursor_context.set_node_context(true_clause, constr.context) }
              .synthesize(true_clause, hint: hint)
        end

        if false_clause
          false_pair =
            constr
              .update_type_env { falsy.env }
              .for_branch(false_clause)
              .tap {|constr| typing.cursor_context.set_node_context(false_clause, constr.context) }
              .synthesize(false_clause, hint: hint)
        end

        constr = constr.update_type_env do |env|
          envs = [] #: Array[TypeInference::TypeEnv]

          unless truthy.unreachable
            if true_pair
              unless true_pair.type.is_a?(AST::Types::Bot)
                envs << true_pair.context.type_env
              end
            else
              envs << truthy.env
            end
          end

          if false_pair
            unless falsy.unreachable
              unless false_pair.type.is_a?(AST::Types::Bot)
                envs << false_pair.context.type_env
              end
            end
          else
            envs << falsy.env
          end

          env.join(*envs)
        end

        if truthy.unreachable
          if true_clause
            _, _, _, loc = deconstruct_if_node!(node)

            if loc.respond_to?(:keyword)
              condition_loc = loc #: NodeHelper::condition_loc
              case condition_loc.keyword.source
              when "if", "elsif"
                location = condition_loc.begin || condition_loc.keyword
              when "unless"
                # `else` token always exists
                location = condition_loc.else || raise
              end
            else
              location = true_clause.loc.expression
            end

            typing.add_error(
              Diagnostic::Ruby::UnreachableBranch.new(
                node: true_clause,
                location: location || raise
              )
            )
          end
        end

        if falsy.unreachable
          if false_clause
            _, _, _, loc = deconstruct_if_node!(node)

            if loc.respond_to?(:keyword)
              condition_loc = loc #: NodeHelper::condition_loc

              case condition_loc.keyword.source
              when "if", "elsif"
                # `else` token always exists
                location = condition_loc.else || raise
              when "unless"
                location = condition_loc.begin || condition_loc.keyword
              end
            else
              location = false_clause.loc.expression
            end

            typing.add_error(
              Diagnostic::Ruby::UnreachableBranch.new(
                node: false_clause,
                location: location || raise
              )
            )
          end
        end

        node_type = union_type_unify(true_pair&.type || AST::Builtin.nil_type, false_pair&.type || AST::Builtin.nil_type)
        add_typing(node, type: node_type, constr: constr)
      end

    when :case
      yield_self do
        # @type var node: Parser::AST::Node & Parser::AST::_CaseNode

        cond, *whens, els = node.children

        constr = self #: TypeConstruction
        interpreter = TypeInference::LogicTypeInterpreter.new(subtyping: checker, typing: typing, config: builder_config)

        if cond
          types, envs = TypeInference::CaseWhen.type_check(constr, node, interpreter, hint: hint, condition: condition)
        else
          branch_results = [] #: Array[Pair]

          condition_constr = constr

          whens.each do |when_clause|
            when_clause_constr = condition_constr
            body_envs = [] #: Array[TypeInference::TypeEnv]

            # @type var tests: Array[Parser::AST::Node]
            # @type var body: Parser::AST::Node?
            *tests, body = when_clause.children

            branch_reachable = false

            tests.each do |test|
              test_type, condition_constr = condition_constr.synthesize(test, condition: true)
              truthy, falsy = interpreter.eval(env: condition_constr.context.type_env, node: test)
              truthy_env = truthy.env
              falsy_env = falsy.env

              condition_constr = condition_constr.update_type_env { falsy_env }
              body_envs << truthy_env

              branch_reachable ||= !truthy.unreachable
            end

            branch_result =
              if body
                when_clause_constr
                  .update_type_env {|env| env.join(*body_envs) }
                  .for_branch(body)
                  .tap {|constr| typing.cursor_context.set_node_context(body, constr.context) }
                  .synthesize(body, hint: hint)
              else
                Pair.new(type: AST::Builtin.nil_type, constr: when_clause_constr)
              end

            branch_results << branch_result

            unless branch_reachable
              unless branch_result.type.is_a?(AST::Types::Bot)
                typing.add_error(
                  Diagnostic::Ruby::UnreachableValueBranch.new(
                    node: when_clause,
                    type: branch_result.type,
                    location: when_clause.location.keyword || raise
                  )
                )
              end
            end
          end

          if els
            branch_results << condition_constr.synthesize(els, hint: hint)
          else
            branch_results << Pair.new(type: AST::Builtin.nil_type, constr: condition_constr)
          end

          branch_results.reject! do |result|
            result.type.is_a?(AST::Types::Bot)
          end

          types = branch_results.map(&:type)
          envs = branch_results.map {|result| result.constr.context.type_env }
        end

        constr = constr.update_type_env do |env|
          env.join(*envs)
        end

        add_typing(node, type: union_type_unify(*types), constr: constr)
      end

    when :rescue
      yield_self do
        body, *resbodies, else_node = node.children
        body_pair = synthesize(body, hint: hint) if body

        # @type var body_constr: TypeConstruction
        body_constr = if body_pair
                        update_type_env do |env|
                          env.join(env, body_pair.context.type_env)
                        end
                      else
                        self
                      end

        resbody_pairs = resbodies.map do |resbody|
          # @type var exn_classes: Parser::AST::Node
          # @type var assignment: Parser::AST::Node?
          # @type var body: Parser::AST::Node?
          exn_classes, assignment, body = resbody.children

          if exn_classes
            case exn_classes.type
            when :array
              exn_types = exn_classes.children.map {|child| synthesize(child).type }
            else
              Steep.logger.error "Unexpected exception list: #{exn_classes.type}"
            end
          end

          if assignment
            case assignment.type
            when :lvasgn
              var_name = assignment.children[0]
            else
              Steep.logger.error "Unexpected rescue variable assignment: #{assignment.type}"
            end
          end

          resbody_construction = body_constr.for_branch(resbody).update_type_env do |env|
            assignments = {} #: Hash[Symbol, AST::Types::t]

            case
            when exn_classes && var_name && exn_types
              instance_types = exn_types.map do |type|
                type = expand_alias(type)
                case
                when type.is_a?(AST::Types::Name::Singleton)
                  to_instance_type(type)
                else
                  AST::Builtin.any_type
                end
              end

              assignments[var_name] = AST::Types::Union.build(types: instance_types)
            when var_name
              assignments[var_name] = AST::Builtin.any_type
            end

            env.assign_local_variables(assignments)
          end

          if body
            resbody_construction.typing.cursor_context.set_node_context(body, resbody_construction.context)
            resbody_construction.synthesize(body, hint: hint)
          else
            Pair.new(constr: body_constr, type: AST::Builtin.nil_type)
          end
        end

        resbody_pairs.select! do |pair|
          no_subtyping?(sub_type: pair.type, super_type: AST::Types::Bot.instance)
        end

        resbody_types = resbody_pairs.map(&:type)
        resbody_envs = resbody_pairs.map {|pair| pair.context.type_env }

        else_constr = body_pair&.constr || self

        if else_node
          else_type, else_constr = else_constr.for_branch(else_node).synthesize(else_node, hint: hint)
          else_constr
            .update_type_env {|env| env.join(*resbody_envs, env) }
            .add_typing(node, type: union_type(else_type, *resbody_types))
        else
          if resbody_types.empty?
            constr = body_pair ? body_pair.constr : self
            constr.add_typing(node, type: body_pair&.type || AST::Builtin.nil_type)
          else
            update_type_env {|env| env.join(*resbody_envs, else_constr.context.type_env) }
              .add_typing(node, type: union_type(*[body_pair&.type, *resbody_types].compact))
          end
        end
      end

    when :resbody
      yield_self do
        klasses, asgn, body = node.children
        synthesize(klasses) if klasses
        synthesize(asgn) if asgn
        if body
          body_type = synthesize(body, hint: hint).type
          add_typing(node, type: body_type)
        else
          add_typing(node, type: AST::Builtin.nil_type)
        end
      end

    when :ensure
      yield_self do
        body, ensure_body = node.children
        body_type = synthesize(body).type if body
        if ensure_body
          ensure_constr = for_branch(node)
          ensure_constr.synthesize(ensure_body)
        end
        if body_type
          add_typing(node, type: body_type)
        else
          add_typing(node, type: AST::Builtin.nil_type)
        end
      end

    when :masgn
      type_masgn(node)

    when :for
      yield_self do
        asgn, collection, body = node.children

        collection_type, constr, collection_context = synthesize(collection).to_ary
        collection_type = expand_self(collection_type)

        if collection_type.is_a?(AST::Types::Any)
          var_type = AST::Builtin.any_type
        else
          if each = calculate_interface(collection_type, :each, private: true)
            method_type = (each.method_types || []).find do |type|
              if type.block
                if type.block.type.params
                  type.block.type.params.first_param
                else
                  true
                end
              end
            end
            if method_type
              if block = method_type.block
                if first_param = block.type&.params&.first_param
                  var_type = first_param.type #: AST::Types::t
                else
                  var_type = AST::Builtin.any_type
                end
              end
            end
          end
        end
        var_name = asgn.children[0] #: Symbol

        if var_type
          if body
            body_constr = constr.update_type_env do |type_env|
              type_env = type_env.assign_local_variables({ var_name => var_type })
              pins = type_env.pin_local_variables(nil)
              type_env.merge(local_variable_types: pins)
            end

            typing.cursor_context.set_body_context(node, body_constr.context)
            _, _, body_context = body_constr.synthesize(body).to_ary

            constr = constr.update_type_env do |env|
              env.join(collection_context.type_env, body_context.type_env)
            end
          else
            constr = self
          end

          add_typing(node, type: collection_type, constr: constr)
        else
          constr = synthesize_children(node, skips: [collection])

          constr.fallback_to_any(node) do
            Diagnostic::Ruby::NoMethod.new(
              node: node,
              method: :each,
              type: collection_type
            )
          end
        end
      end
    when :while, :until
      yield_self do
        cond, body = node.children
        cond_type, constr = synthesize(cond, condition: true).to_ary

        interpreter = TypeInference::LogicTypeInterpreter.new(subtyping: checker, typing: typing, config: builder_config)
        truthy, falsy = interpreter.eval(env: constr.context.type_env, node: cond)
        truthy_env = truthy.env
        falsy_env = falsy.env

        case node.type
        when :while
          body_env, exit_env = truthy_env, falsy_env
        when :until
          exit_env, body_env = truthy_env, falsy_env
        else
          raise
        end

        body_env or raise
        exit_env or raise


        if body
          pins = body_env.pin_local_variables(nil)
          body_env = body_env.merge(local_variable_types: pins)

          _, body_constr =
            constr
              .update_type_env { body_env }
              .for_branch(body, break_context: TypeInference::Context::BreakContext.new(break_type: hint || AST::Builtin.nil_type, next_type: nil))
              .tap {|constr| typing.cursor_context.set_node_context(body, constr.context) }
              .synthesize(body).to_ary

          constr = constr.update_type_env {|env| env.join(exit_env, body_constr.context.type_env) }
        else
          constr = constr.update_type_env { exit_env }
        end

        add_typing(node, type: AST::Builtin.nil_type, constr: constr)
      end

    when :while_post, :until_post
      yield_self do
        cond, body = node.children

        _, cond_constr, = synthesize(cond)

        if body
          for_loop =
            cond_constr
              .update_type_env {|env| env.merge(local_variable_types: env.pin_local_variables(nil)) }
              .for_branch(body, break_context: TypeInference::Context::BreakContext.new(break_type: hint || AST::Builtin.nil_type, next_type: nil))

          typing.cursor_context.set_node_context(body, for_loop.context)
          _, body_constr, body_context = for_loop.synthesize(body)

          constr = cond_constr.update_type_env {|env| env.join(env, body_context.type_env) }

          add_typing(node, type: AST::Builtin.nil_type, constr: constr)
        else
          add_typing(node, type: AST::Builtin.nil_type, constr: cond_constr)
        end
      end

    when :irange, :erange
      begin_node, end_node = node.children

      constr = self
      begin_type, constr = if begin_node
                             constr.synthesize(begin_node).to_ary
                           else
                             [AST::Builtin.nil_type, constr]
                           end
      end_type, constr = if end_node
                           constr.synthesize(end_node).to_ary
                         else
                           [AST::Builtin.nil_type, constr]
                         end

      type = AST::Builtin::Range.instance_type(union_type(begin_type, end_type))
      add_typing(node, type: type, constr: constr)

    when :regexp
      each_child_node(node) do |child|
        synthesize(child)
      end

      add_typing(node, type: AST::Builtin::Regexp.instance_type)

    when :regopt
      # ignore
      add_typing(node, type: AST::Builtin.any_type)

    when :nth_ref
      add_typing(node, type: union_type(AST::Builtin::String.instance_type, AST::Builtin.nil_type))

    when :back_ref
      synthesize(node.updated(:gvar), hint: hint)

    when :or_asgn, :and_asgn
      yield_self do
        asgn, rhs = node.children

        case asgn.type
        when :lvasgn
          type, constr = synthesize(rhs, hint: hint)
          constr.lvasgn(asgn, type)
        when :ivasgn
          type, constr = synthesize(rhs, hint: hint)
          constr.ivasgn(asgn, type)
        when :gvasgn
          type, constr = synthesize(rhs, hint: hint)
          constr.gvasgn(asgn, type)
        when :send
          children = asgn.children.dup
          children[1] = :"#{children[1]}="
          send_arg_nodes = [*children, rhs]
          rhs_ = node.updated(:send, send_arg_nodes)
          node_type = case node.type
                      when :or_asgn
                        :or
                      when :and_asgn
                        :and
                      end
          node_ = node.updated(node_type, [asgn, rhs_])

          synthesize(node_, hint: hint)
        else
          Steep.logger.error { "#{node.type} with #{asgn.type} lhs is not supported"}
          fallback_to_any(node)
        end
      end

    when :defined?
      type_any_rec(node, only_children: true)
      add_typing(node, type: AST::Builtin.optional(AST::Builtin::String.instance_type))

    when :gvasgn
      yield_self do
        name, rhs = node.children
        lhs_type = context.type_env[name]
        rhs_type, constr = synthesize(rhs, hint: lhs_type).to_ary

        location = node.location #: Parser::Source::Map & Parser::AST::_Variable
        constr.check_deprecation_global(name, node, location.name)

        type, constr = constr.gvasgn(node, rhs_type)

        constr.add_typing(node, type: type)
      end

    when :gvar
      yield_self do
        name = node.children.first

        check_deprecation_global(name, node, node.location.expression)

        if type = context.type_env[name]
          add_typing(node, type: type)
        else
          fallback_to_any(node) do
            Diagnostic::Ruby::UnknownGlobalVariable.new(node: node, name: name)
          end
        end
      end

    when :block_pass
      yield_self do
        value_node = node.children[0]

        constr = self #: TypeConstruction

        if value_node
          type, constr = synthesize(value_node, hint: hint)

          if hint.is_a?(AST::Types::Proc) && value_node.type == :send && value_node.children[1] == :method && AST::Builtin::Method.instance_type?(type)
            receiver_node = value_node.children[0] #: Parser::AST::Node?
            receiver_type = receiver_node ? typing.type_of(node: receiver_node) : self_type
            method_name = value_node.children[2].children[0] #: Symbol
            if method = calculate_interface(receiver_type, private: true)&.methods&.[](method_name)
              if method_type = method.method_types.find {|method_type| method_type.accept_one_arg? }
                if method_type.type_params.empty?
                  type = AST::Types::Proc.new(
                    type: method_type.type,
                    block: method_type.block,
                    self_type: nil
                  )
                end
              end
            end
          elsif hint.is_a?(AST::Types::Proc) && value_node.type == :sym
            if hint.one_arg?
              if hint.type.params
                # Assumes Symbol#to_proc implementation
                param_type = hint.type.params.required.fetch(0)
                case param_type
                when AST::Types::Any
                  type = AST::Types::Any.instance
                else
                  if method = calculate_interface(param_type, private: true)&.methods&.[](value_node.children[0])
                    return_types = method.method_types.filter_map do |method_type|
                      if method_type.type.params.nil? || method_type.type.params.optional?
                        method_type.type.return_type
                      end
                    end

                    unless return_types.empty?
                      type = AST::Types::Proc.new(
                        type: Interface::Function.new(
                          params: Interface::Function::Params.empty.with_first_param(
                            Interface::Function::Params::PositionalParams::Required.new(param_type)
                          ),
                          return_type: return_types.fetch(0),
                          location: nil
                        ),
                        block: nil,
                        self_type: nil
                      )
                    end
                  end
                end
              end
            else
              Steep.logger.error "Passing multiple args through Symbol#to_proc is not supported yet"
            end
          end

          case
          when type.is_a?(AST::Types::Proc)
            # nop
          when AST::Builtin::Proc.instance_type?(type)
            # nop
          else
            type = try_convert(type, :to_proc) || type
          end
        else
          # Anonymous block_pass only happens inside method definition
          if (type = context.type_env[ANONYMOUS_BLOCK_PASSABLE_LVAR])
            # Use type from type_env (may have been narrowed by block_given?)
          elsif block_type = method_context!.block_type
            type = AST::Types::Proc.new(
              type: block_type.type,
              block: nil,
              self_type: block_type.self_type
            )

            if block_type.optional?
              type = union_type(type, AST::Builtin.nil_type)
            end
          else
            type = AST::Builtin.nil_type
          end
        end

        add_typing node, type: type
      end

    when :blockarg
      yield_self do
        each_child_node node do |child|
          synthesize(child)
        end

        add_typing node, type: AST::Builtin.any_type
      end

    when :cvasgn
      name, rhs = node.children

      type, constr = synthesize(rhs, hint: hint)

      var_type =
        if class_vars = module_context.class_variables
          if ty = class_vars[name]
            checker.factory.type(ty)
          end
        end

      if var_type
        result = constr.check_relation(sub_type: type, super_type: var_type)

        if result.success?
          add_typing node, type: type, constr: constr
        else
          fallback_to_any node do
            Diagnostic::Ruby::IncompatibleAssignment.new(
              node: node,
              lhs_type: var_type,
              rhs_type: type,
              result: result
            )
          end
        end
      else
        fallback_to_any(node)
      end

    when :cvar
      name = node.children[0] #: Symbol
      var_type =
        if cvs = module_context.class_variables
          if ty = cvs[name]
            checker.factory.type(ty)
          end
        end

      if var_type
        add_typing node, type: var_type
      else
        fallback_to_any node
      end

    when :alias
      add_typing node, type: AST::Builtin.nil_type

    when :splat
      yield_self do
        typing.add_error(
          Diagnostic::Ruby::UnsupportedSyntax.new(
            node: node,
            message: "Unsupported splat node occurrence"
          )
        )

        each_child_node node do |child|
          synthesize(child)
        end

        add_typing node, type: AST::Builtin.any_type
      end

    when :args
      constr = self #: TypeConstruction

      each_child_node(node) do |child|
        _, constr = constr.synthesize(child)
      end

      add_typing node, type: AST::Builtin.any_type, constr: constr

    when :assertion
      yield_self do
        # @type var as_type: AST::Node::TypeAssertion
        asserted_node, as_type = node.children

        type = as_type.type(module_context.nesting, checker, [])

        case type
        when Array
          type.each do |error|
            typing.add_error(
              Diagnostic::Ruby::RBSError.new(
                error: error,
                node: node,
                location: error.location || raise
              )
            )
          end

          synthesize(asserted_node, hint: hint)

        when nil, RBS::ParsingError
          synthesize(asserted_node, hint: hint)

        else
          actual_type, constr = synthesize(asserted_node, hint: type)

          if no_subtyping?(sub_type: type, super_type: actual_type) && no_subtyping?(sub_type: actual_type, super_type: type)
            typing.add_error(
              Diagnostic::Ruby::FalseAssertion.new(
                node: node,
                assertion_type: type,
                node_type: actual_type
              )
            )
          end

          constr.add_typing(node, type: type)
        end
      end

    when :tapp
      yield_self do
        # @type var tapp: AST::Node::TypeApplication
        sendish, tapp = node.children

        if (array = tapp.types(module_context.nesting, checker, [])).is_a?(Enumerator)
          array.each do |error|
            typing.add_error(
              Diagnostic::Ruby::RBSError.new(
                error: error,
                node: node,
                location: error.location || raise
              )
            )
          end
        end

        type, constr = synthesize_sendish(sendish, hint: hint, tapp: tapp)

        constr.add_typing(node, type: type)
      end

    when :block, :numblock, :send, :csend
      synthesize_sendish(node, hint: hint, tapp: nil)

    when :forwarded_args, :forward_arg
      add_typing(node, type: AST::Builtin.any_type)

    else
      typing.add_error(Diagnostic::Ruby::UnsupportedSyntax.new(node: node))
      add_typing(node, type: AST::Builtin.any_type)

    end.tap do |pair|
      unless pair.is_a?(Pair) && !pair.type.is_a?(Pair)
        # Steep.logger.error { "result = #{pair.inspect}" }
        # Steep.logger.error { "node = #{node.type}" }
        raise "#synthesize should return an instance of Pair: #{pair.class}, node=#{node.inspect}"
      end
    end
  rescue RBS::BaseError => exn
    Steep.logger.warn { "Unexpected RBS error: #{exn.message}" }
    exn.backtrace&.each {|loc| Steep.logger.warn "  #{loc}" }
    typing.add_error(Diagnostic::Ruby::UnexpectedError.new(node: node, error: exn))
    type_any_rec(node)
  rescue StandardError => exn
    Steep.log_error exn
    typing.add_error(Diagnostic::Ruby::UnexpectedError.new(node: node, error: exn))
    type_any_rec(node)
  end
end

#synthesize_block(node:, block_type_hint:, block_body:) ⇒ Object



4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
# File 'lib/steep/type_construction.rb', line 4678

def synthesize_block(node:, block_type_hint:, block_body:)
  if block_body
    body_type, _, context = synthesize(block_body, hint: block_context&.body_type || block_type_hint)

    if annotated_body_type = block_context&.body_type
      if result = no_subtyping?(sub_type: body_type, super_type: annotated_body_type)
        typing.add_error(
          Diagnostic::Ruby::BlockBodyTypeMismatch.new(
            node: node,
            expected: annotated_body_type,
            actual: body_type,
            result: result
          )
        )
      end
      body_type = annotated_body_type
    end

    range = block_body.loc.expression.end_pos..node.loc.end.begin_pos
    typing.cursor_context.set(range, context)

    body_type
  else
    AST::Builtin.nil_type
  end
end

#synthesize_children(node, skips: []) ⇒ Object



3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
# File 'lib/steep/type_construction.rb', line 3234

def synthesize_children(node, skips: [])
  skips = Set.new.compare_by_identity.merge(skips).delete(nil)

  # @type var constr: TypeConstruction
  constr = self

  each_child_node(node) do |child|
    unless skips.include?(child)
      _, constr = constr.synthesize(child)
    end
  end

  constr
end

#synthesize_constant(node, parent_node, constant_name) ⇒ Object



3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
# File 'lib/steep/type_construction.rb', line 3009

def synthesize_constant(node, parent_node, constant_name)
  const_name = module_name_from_node(parent_node, constant_name)

  if const_name && type = context.type_env.annotated_constant(const_name)
    # const-type annotation wins
    if node
      constr = synthesize_children(node)
      type, constr = constr.add_typing(node, type: type)
      [type, constr, nil]
    else
      [type, self, nil]
    end
  else
    case
    when !parent_node
      constr = self

      if (type, name = context.type_env.constant(constant_name, false))
        if node
          _, constr = add_typing(node, type: type)
        end

        return [type, constr, name]
      end
    when parent_node.type == :cbase
      _, constr = add_typing(parent_node, type: AST::Builtin.nil_type)

      if (type, name = constr.context.type_env.constant(constant_name, true))
        if node
          _, constr = constr.add_typing(node, type: type)
        end

        return [type, constr, name]
      end
    else
      parent_type, constr = synthesize(parent_node).to_ary
      parent_type = expand_self(parent_type)
      parent_type = deep_expand_alias(parent_type)

      case parent_type
      when AST::Types::Name::Singleton
        if (type, name = constr.context.type_env.constant(parent_type.name, constant_name))
          if node
            _, constr = add_typing(node, type: type)
          end

          return [type, constr, name]
        end
      when AST::Types::Any
        # Couldn't detect the type of the parent constant
        # Skip reporting error for this node.
        if node
          _, constr = add_typing(node, type: parent_type)
        end

        return [parent_type, constr, nil]
      end
    end

    if block_given?
      yield
    else
      if node
        constr.typing.add_error(
          Diagnostic::Ruby::UnknownConstant.new(node: node, name: constant_name)
        )
      end
    end

    if node
      _, constr = add_typing(node, type: AST::Builtin.any_type)
    end

    [AST::Builtin.any_type, constr, nil]
  end
end

#synthesize_constant_decl(node, parent_node, constant_name, &block) ⇒ Object



2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
# File 'lib/steep/type_construction.rb', line 2958

def synthesize_constant_decl(node, parent_node, constant_name, &block)
  const_name = module_name_from_node(parent_node, constant_name)

  if const_name && type = context.type_env.annotated_constant(const_name)
    # const-type annotation wins
    if node
      constr = synthesize_children(node)
      type, constr = constr.add_typing(node, type: type)
      [type, constr, nil]
    else
      [type, self, nil]
    end
  else
    if parent_node
      synthesize_constant(node, parent_node, constant_name, &block)
    else
      if nesting
        if parent_nesting = nesting[1]
          if constant = context.type_env.constant_env.resolver.table.children(parent_nesting)&.fetch(constant_name, nil)
            return [checker.factory.type(constant.type), self, constant.name]
          end
        end

        if block_given?
          yield
        else
          if node
            typing.add_error(
              Diagnostic::Ruby::UnknownConstant.new(node: node, name: constant_name)
            )
          end
        end

        constr = self #: TypeConstruction
        if node
          _, constr = add_typing(node, type: AST::Builtin.any_type)
        end

        [
          AST::Builtin.any_type,
          constr,
          nil
        ]
      else
        # No nesting
        synthesize_constant(node, nil, constant_name, &block)
      end
    end
  end
end

#synthesize_sendish(node, hint:, tapp:) ⇒ Object



2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
# File 'lib/steep/type_construction.rb', line 2740

def synthesize_sendish(node, hint:, tapp:)
  case node.type
  when :send
    type_send(node, send_node: node, block_params: nil, block_body: nil, tapp: tapp, hint: hint)
  when :csend
    yield_self do
      send_type, constr =
        type_send(node, send_node: node, block_params: nil, block_body: nil, unwrap: true, tapp: tapp, hint: hint).to_ary

      constr
        .update_type_env { context.type_env.join(constr.context.type_env, context.type_env) }
        .add_typing(node, type: union_type(send_type, AST::Builtin.nil_type))
    end
  when :block
    yield_self do
      send_node, params, body = node.children
      if send_node.type == :lambda
        # @type var node: Parser::AST::Node & Parser::AST::_BlockNode
        type_lambda(node, params_node: params, body_node: body, type_hint: hint)
      else
        type_send(node, send_node: send_node, block_params: params, block_body: body, unwrap: send_node.type == :csend, tapp: tapp, hint: hint)
      end
    end
  when :numblock
    yield_self do
      send_node, max_num, body = node.children

      if max_num == 1
        arg_nodes = [Parser::AST::Node.new(:procarg0, [:_1])]
      else
        arg_nodes = max_num.times.map {|i| Parser::AST::Node.new(:arg, [:"_#{i+1}"]) }
      end

      params = Parser::AST::Node.new(:args, arg_nodes)

      if send_node.type == :lambda
        # @type var node: Parser::AST::Node & Parser::AST::_BlockNode
        type_lambda(node, params_node: params, body_node: body, type_hint: hint)
      else
        type_send(node, send_node: send_node, block_params: params, block_body: body, unwrap: send_node.type == :csend, tapp: tapp, hint: hint)
      end
    end
  else
    raise "Unexpected node is given to `#synthesize_sendish` (#{node.type}, #{node.location.first_line})"
  end
end

#test_literal_type(literal, hint) ⇒ Object



4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
# File 'lib/steep/type_construction.rb', line 4936

def test_literal_type(literal, hint)
  if hint
    case hint
    when AST::Types::Any
      nil
    else
      literal_type = AST::Types::Literal.new(value: literal)
      if check_relation(sub_type: literal_type, super_type: hint).success?
        unwrap(hint)
      end
    end
  end
end

#to_instance_type(type, args: nil) ⇒ Object



4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
# File 'lib/steep/type_construction.rb', line 4950

def to_instance_type(type, args: nil)
  args = args || case type
                 when AST::Types::Name::Singleton
                   decl = checker.factory.env.module_class_entry(type.name, normalized: true) or raise
                   decl.type_params.each.map { AST::Builtin.any_type }
                 else
                   raise "unexpected type to to_instance_type: #{type}"
                 end

  AST::Types::Name::Instance.new(name: type.name, args: args)
end

#try_array_type(node, hint) ⇒ Object



5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
# File 'lib/steep/type_construction.rb', line 5097

def try_array_type(node, hint)
  element_hint = hint ? hint.args[0] : nil

  constr = self #: TypeConstruction
  element_types = [] #: Array[AST::Types::t]

  each_child_node(node) do |child|
    case child.type
    when :splat
      type, constr = constr.synthesize(child.children[0], hint: hint)

      type = try_convert(type, :to_a) || type

      case
      when AST::Builtin::Array.instance_type?(type)
        type.is_a?(AST::Types::Name::Instance) or raise
        element_types << type.args.fetch(0)
      when type.is_a?(AST::Types::Tuple)
        element_types.push(*type.types)
      else
        element_types.push(*flatten_array_elements(type))
      end
    else
      type, constr = constr.synthesize(child, hint: element_hint)
      element_types << type
    end
  end

  element_type = AST::Types::Union.build(types: element_types)
  constr.add_typing(node, type: AST::Builtin::Array.instance_type(element_type))
end

#try_convert(type, method) ⇒ Object



5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
# File 'lib/steep/type_construction.rb', line 5019

def try_convert(type, method)
  if shape = calculate_interface(type, private: false)
    if entry = shape.methods[method]
      method_type = entry.method_types.find do |method_type|
        method_type.type.params.nil? || method_type.type.params.optional?
      end

      method_type.type.return_type if method_type
    end
  end
end

#try_convert_to_array(type) ⇒ Object



5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
# File 'lib/steep/type_construction.rb', line 5031

def try_convert_to_array(type)
  if arrayish = arrayish_type?(type, untyped_is: true) || semantically_arrayish_type?(type)
    arrayish
  else
    if converted = try_convert(type, :to_ary)
      if arrayish_type?(converted, untyped_is: true) || semantically_arrayish_type?(type)
        converted
      end
    else
      AST::Types::Tuple.new(types: [type])
    end
  end
end

#try_method_type(node, receiver_type:, method_name:, method_overload:, arguments:, block_params:, block_body:, tapp:, hint:) ⇒ Object



3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
# File 'lib/steep/type_construction.rb', line 3964

def try_method_type(node, receiver_type:, method_name:, method_overload:, arguments:, block_params:, block_body:, tapp:, hint:)
  constr = self

  method_type = method_overload.method_type
  decls = method_overload.method_decls(method_name).to_set

  if tapp && type_args = tapp.types?(module_context.nesting, checker, [])
    type_arity = method_type.type_params.size
    type_param_names = method_type.type_params.map(&:name)

    # Explicit type application
    if type_args.size == type_arity
      # @type var args_: Array[AST::Types::t]
      args_ = []

      type_args.each_with_index do |type, index|
        param = method_type.type_params.fetch(index)

        if upper_bound = param.upper_bound
          if result = no_subtyping?(sub_type: type.value, super_type: upper_bound)
            args_ << AST::Builtin.any_type
            constr.typing.add_error(
              Diagnostic::Ruby::TypeArgumentMismatchError.new(
                type_arg: type.value,
                type_param: param,
                result: result,
                location: type.location
              )
            )
          else
            args_ << type.value
          end
        else
          args_ << type.value
        end
      end

      method_type = method_type.instantiate(Interface::Substitution.build(type_param_names, args_))
    else
      if type_args.size > type_arity
        type_args.drop(type_arity).each do |type_arg|
          constr.typing.add_error(
            Diagnostic::Ruby::UnexpectedTypeArgument.new(
              type_arg: type_arg.value,
              method_type: method_type,
              location: type_arg.location
            )
          )
        end
      end

      if type_args.size < type_arity
        constr.typing.add_error(
          Diagnostic::Ruby::InsufficientTypeArgument.new(
            node: tapp.node,
            type_args: type_args.map(&:value),
            method_type: method_type
          )
        )
      end

      method_type = method_type.instantiate(
        Interface::Substitution.build(
          type_param_names,
          Array.new(type_param_names.size, AST::Builtin.any_type)
        )
      )
    end

    type_params = [] #: Array[Interface::TypeParam]
    type_param_names.clear
  else
    # Infer type application
    type_params, instantiation = Interface::TypeParam.rename(method_type.type_params)
    type_param_names = type_params.map(&:name)
    method_type = method_type.instantiate(instantiation)
  end

  constr = constr.with(
    context: context.with(
      variable_context: TypeInference::Context::TypeVariableContext.new(
        type_params,
        parent_context: context.variable_context
      )
    )
  )

  variance = Subtyping::VariableVariance.from_method_type(method_type)
  constraints = Subtyping::Constraints.new(unknowns: type_params.map(&:name))
  ccontext = Subtyping::Constraints::Context.new(
    self_type: self_type,
    instance_type: module_context.instance_type,
    class_type: module_context.module_type,
    variance: variance
  )

  upper_bounds = {} #: Hash[Symbol, AST::Types::t]

  type_params.each do |param|
    if ub = param.upper_bound
      constraints.add(param.name, super_type: ub, skip: true)
      upper_bounds[param.name] = ub
    end
  end

  checker.push_variable_bounds(upper_bounds) do
    # @type block: [TypeInference::MethodCall::t, TypeConstruction]

    # @type var errors: Array[Diagnostic::Ruby::Base]
    errors = []

    if method_type.type.params
      args = TypeInference::SendArgs.new(node: node, arguments: arguments, type: method_type)
      constr = constr.type_check_args(
        method_name,
        args,
        constraints,
        errors
      )
    else
      constr = constr.type_check_untyped_args(arguments)
    end

    if block_params
      # block is given

      # @type var node: Parser::AST::Node & Parser::AST::_BlockNode

      block_annotations = source.annotations(block: node, factory: checker.factory, context: nesting)
      block_params_ = TypeInference::BlockParams.from_node(block_params, annotations: block_annotations)

      if method_type.block
        fvs = method_type.type.return_type.free_variables.each.with_object(Set[]) do |var, fvs| #$ Set[Symbol]
          if var.is_a?(Symbol)
            fvs << var
          end
        end

        if hint && !fvs.empty?
          if hint.free_variables.subset?(self_type.free_variables)
            if check_relation(sub_type: method_type.type.return_type, super_type: hint, constraints: constraints).success?
              method_type, solved, s = apply_solution(errors, node: node, method_type: method_type) do
                constraints.solution(checker, variables: fvs, context: ccontext)
              end
            end

            method_type.block or raise
          end
        end

        # Method accepts block
        pairs = block_params_&.zip(method_type.block.type.params, nil, factory: checker.factory)

        if block_params_ && pairs
          # Block parameters are compatible with the block type
          block_constr = constr.for_block(
            block_body,
            block_params: block_params_,
            block_param_hint: method_type.block.type.params,
            block_next_type: method_type.block.type.return_type,
            block_block_hint: nil,
            block_annotations: block_annotations,
            block_self_hint: method_type.block.self_type,
            node_type_hint: method_type.type.return_type
          )

          block_constr = block_constr.with_new_typing(
            block_constr.typing.new_child()
          )

          block_constr.typing.cursor_context.set_body_context(node, block_constr.context)

          pairs.each do |param, type|
            case param
            when TypeInference::BlockParams::Param
              _, block_constr = block_constr.synthesize(param.node, hint: param.type || type)

              if param.type
                check_relation(sub_type: type, super_type: param.type, constraints: constraints).else do |result|
                  error = Diagnostic::Ruby::IncompatibleAssignment.new(
                    node: param.node,
                    lhs_type: param.type,
                    rhs_type: type,
                    result: result
                  )
                  errors << error
                end
              end
            when TypeInference::BlockParams::MultipleParam
              param.each_param do |p|
                _, block_constr = block_constr.synthesize(p.node, hint: p.type || type)

                if p.type
                  check_relation(sub_type: type, super_type: p.type, constraints: constraints).else do |result|
                    error = Diagnostic::Ruby::IncompatibleAssignment.new(
                      node: p.node,
                      lhs_type: p.type,
                      rhs_type: type,
                      result: result
                    )
                    errors << error
                  end
                end
              end

              _, block_constr = block_constr.add_typing(param.node, type: type)
            end
          end

          method_type, solved, s = apply_solution(errors, node: node, method_type: method_type) {
            fvs_ = Set[] #: Set[AST::Types::variable]

            fvs_.merge(method_type.type.params.free_variables) if method_type.type.params
            fvs_.merge(method_type.block.type.params.free_variables) if method_type.block.type.params
            (method_type.type.return_type.free_variables + method_type.block.type.return_type.free_variables).each do |var|
              if var.is_a?(Symbol)
                if constraints.unknown?(var)
                  unless constraints.has_constraint?(var)
                    fvs_.delete(var)
                  end
                end
              end
            end

            constraints.solution(checker, variables: fvs_, context: ccontext)
          }

          method_type.block or raise

          if solved
            # Ready for type check the body of the block
            block_constr = block_constr.update_type_env {|env| env.subst(s) }
            block_constr = block_constr.update_context {|context|
              context.with(
                self_type: context.self_type.subst(s),
                type_env: context.type_env.subst(s),
                block_context: context.block_context&.subst(s),
                break_context: context.break_context&.subst(s)
              )
            }

            block_body_type = block_constr.synthesize_block(
              node: node,
              block_body: block_body,
              block_type_hint: method_type.block.type.return_type
            )

            if method_type.block && method_type.block.self_type
              block_body_type = block_body_type.subst(
                Interface::Substitution.build(
                  [],
                  [],
                  self_type: method_type.block.self_type,
                  module_type: singleton_type(method_type.block.self_type) || AST::Builtin.top_type,
                  instance_type: instance_type(method_type.block.self_type) || AST::Builtin.top_type
                )
              )
            end

            result = check_relation(sub_type: block_body_type,
                                    super_type: method_type.block.type.return_type,
                                    constraints: constraints)

            if result.success?
              # Successfully type checked the body
              method_type, solved, _ = apply_solution(errors, node: node, method_type: method_type) do
                constraints.solution(checker, variables: type_param_names, context: ccontext)
              end
              method_type = eliminate_vars(method_type, type_param_names) unless solved

              return_type = method_type.type.return_type
              if break_type = block_annotations.break_type
                return_type = union_type(break_type, return_type)
              end
            else
              # The block body has incompatible type
              errors << Diagnostic::Ruby::BlockBodyTypeMismatch.new(
                node: node,
                expected: method_type.block.type.return_type,
                actual: block_body_type,
                result: result
              )

              method_type = eliminate_vars(method_type, type_param_names)
              return_type = method_type.type.return_type
            end

            block_constr.typing.save!
          else
            # Failed to infer the type of block parameters
            constr.type_block_without_hint(node: node, block_annotations: block_annotations, block_params: block_params_, block_body: block_body) do |error|
              errors << error
            end

            method_type = eliminate_vars(method_type, type_param_names)
            return_type = method_type.type.return_type
          end
        else
          # Block parameters are unsupported syntax
          errors << Diagnostic::Ruby::UnsupportedSyntax.new(
            node: block_params,
            message: "Unsupported block params pattern, probably masgn?"
          )

          method_type, solved, _ = apply_solution(errors, node: node, method_type: method_type) {
            constraints.solution(checker, variables: type_param_names, context: ccontext)
          }
          method_type = eliminate_vars(method_type, type_param_names) unless solved

          return_type = method_type.type.return_type
        end
      else
        if args
          # Block is given but method doesn't accept
          #
          constr.type_block_without_hint(node: node, block_annotations: block_annotations, block_params: block_params_, block_body: block_body) do |error|
            errors << error
          end

          case node.children[0].type
          when :super, :zsuper
            unless method_context!.super_method
              errors << Diagnostic::Ruby::UnexpectedSuper.new(
                node: node.children[0],
                method: method_name
              )
            end
          else
            errors << Diagnostic::Ruby::UnexpectedBlockGiven.new(
              node: node,
              method_type: method_type
            )
          end

          method_type = eliminate_vars(method_type, type_param_names)
          return_type = method_type.type.return_type
        else
          if block_body
            block_annotations = source.annotations(block: node, factory: checker.factory, context: nesting)
            type_block_without_hint(
              node: node,
              block_annotations: block_annotations,
              block_params: TypeInference::BlockParams.from_node(block_params, annotations: block_annotations),
              block_body: block_body
            )
          end
        end
      end
    else
      # Block syntax is not given
      if args
        arg = args.block_pass_arg

        case
        when forwarded_args_node = args.forwarded_args_node
          case forward_arg_type = method_context!.forward_arg_type
          when nil
            if method_context!.method_type
              raise "Method context must have `forwarded_arg_type` if `...` node appears in it"
            else
              # Skips type checking forwarded argument because the method type is not given
            end
          when true
            # Skip type checking because it's untyped function
          else
            _, block = forward_arg_type

            method_block_type = method_type.block&.to_proc_type || AST::Builtin.nil_type
            forwarded_block_type = block&.to_proc_type || AST::Builtin.nil_type

            if result = constr.no_subtyping?(sub_type: forwarded_block_type, super_type: method_block_type)
              errors << Diagnostic::Ruby::IncompatibleArgumentForwarding.new(
                method_name: method_name,
                node: forwarded_args_node,
                block_pair: [block, method_type.block],
                result: result
              )
            end
          end

        when arg.compatible?
          if arg.node
            # Block pass (&block) is given
            node_type, constr = constr.synthesize(arg.node, hint: arg.node_type)

            nil_given =
              constr.check_relation(sub_type: node_type, super_type: AST::Builtin.nil_type).success? &&
                !node_type.is_a?(AST::Types::Any)

            if nil_given
              # nil is given ==> no block arg node is given
              method_type, solved, _ = apply_solution(errors, node: node, method_type: method_type) {
                constraints.solution(checker, variables: method_type.free_variables, context: ccontext)
              }
              method_type = eliminate_vars(method_type, type_param_names) unless solved

              # Passing no block
              errors << Diagnostic::Ruby::RequiredBlockMissing.new(
                node: node,
                method_type: method_type
              )
            else
              # non-nil value is given
              constr.check_relation(sub_type: node_type, super_type: arg.node_type, constraints: constraints).else do |result|
                errors << Diagnostic::Ruby::BlockTypeMismatch.new(
                  node: arg.node,
                  expected: arg.node_type,
                  actual: node_type,
                  result: result
                )
              end

              method_type, solved, _ = apply_solution(errors, node: node, method_type: method_type) {
                constraints.solution(checker, variables: method_type.free_variables, context: ccontext)
              }
              method_type = eliminate_vars(method_type, type_param_names) unless solved
            end
          else
            # Block is not given
            method_type, solved, _ = apply_solution(errors, node: node, method_type: method_type) {
              constraints.solution(checker, variables: method_type.free_variables, context: ccontext)
            }
            method_type = eliminate_vars(method_type, type_param_names) unless solved
          end

          return_type = method_type.type.return_type

        when arg.block_missing?
          # Block is required but not given
          method_type, solved, _ = apply_solution(errors, node: node, method_type: method_type) {
            constraints.solution(checker, variables: method_type.free_variables, context: ccontext)
          }

          method_type = eliminate_vars(method_type, type_param_names) unless solved
          return_type = method_type.type.return_type

          errors << Diagnostic::Ruby::RequiredBlockMissing.new(
            node: node,
            method_type: method_type
          )

        when arg.unexpected_block?
          # Unexpected block pass node is given

          arg.node or raise

          method_type, solved, _ = apply_solution(errors, node: node, method_type: method_type) {
            constraints.solution(checker, variables: method_type.free_variables, context: ccontext)
          }
          method_type = eliminate_vars(method_type, type_param_names) unless solved
          return_type = method_type.type.return_type

          node_type, constr = constr.synthesize(arg.node)

          unless constr.check_relation(sub_type: node_type, super_type: AST::Builtin.nil_type).success?
            errors << Diagnostic::Ruby::UnexpectedBlockGiven.new(
              node: node,
              method_type: method_type
            )
          end
        end
      end
    end

    call = if errors.empty?
             TypeInference::MethodCall::Typed.new(
               node: node,
               context: context.call_context,
               receiver_type: receiver_type,
               method_name: method_name,
               actual_method_type: method_type,
               return_type: return_type || method_type.type.return_type,
               method_decls: decls
             )
           else
             TypeInference::MethodCall::Error.new(
               node: node,
               context: context.call_context,
               receiver_type: receiver_type,
               method_name: method_name,
               return_type: return_type || method_type.type.return_type,
               method_decls: decls,
               errors: errors
             )
           end

    constr = constr.with(
      context: constr.context.with(
        variable_context: context.variable_context
      )
    )

    [
      call,
      constr
    ]
  end
end

#try_special_method(node, receiver_type:, method_name:, method_overload:, arguments:, block_params:, block_body:, hint:) ⇒ Object



3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
# File 'lib/steep/type_construction.rb', line 3616

def try_special_method(node, receiver_type:, method_name:, method_overload:, arguments:, block_params:, block_body:, hint:)
  method_type = method_overload.method_type
  decls = method_overload.method_decls(method_name).to_set

  case
  when decl = decls.find {|decl| SPECIAL_METHOD_NAMES.fetch(:array_compact).include?(decl.method_name) }
    if arguments.empty? && !block_params
      # compact
      return_type = method_type.type.return_type
      if AST::Builtin::Array.instance_type?(return_type)
        # @type var return_type: AST::Types::Name::Instance
        elem = return_type.args.fetch(0)
        type = AST::Builtin::Array.instance_type(unwrap(elem))

        _, constr = add_typing(node, type: type)
        call = TypeInference::MethodCall::Special.new(
          node: node,
          context: constr.context.call_context,
          method_name: decl.method_name.method_name,
          receiver_type: receiver_type,
          actual_method_type: method_type.with(type: method_type.type.with(return_type: type)),
          return_type: type,
          method_decls: decls
        )

        return [call, constr]
      end
    end
  when decl = decls.find {|decl| SPECIAL_METHOD_NAMES.fetch(:hash_compact).include?(decl.method_name) }
    if arguments.empty? && !block_params
      # compact
      return_type = method_type.type.return_type
      if AST::Builtin::Hash.instance_type?(return_type)
        # @type var return_type: AST::Types::Name::Instance
        key = return_type.args.fetch(0)
        value = return_type.args.fetch(1)
        type = AST::Builtin::Hash.instance_type(key, unwrap(value))

        _, constr = add_typing(node, type: type)
        call = TypeInference::MethodCall::Special.new(
          node: node,
          context: constr.context.call_context,
          method_name: decl.method_name.method_name,
          receiver_type: receiver_type,
          actual_method_type: method_type.with(type: method_type.type.with(return_type: type)),
          return_type: type,
          method_decls: decls
        )

        return [call, constr]
      end
    end
  when decl = decls.find {|decl| SPECIAL_METHOD_NAMES.fetch(:lambda).include?(decl.method_name) }
    if block_params
      # @type var node: Parser::AST::Node & Parser::AST::_BlockNode
      type, constr = type_lambda(node, params_node: block_params, body_node: block_body, type_hint: hint)

      call = TypeInference::MethodCall::Special.new(
        node: node,
        context: context.call_context,
        method_name: decl.method_name.method_name,
        receiver_type: receiver_type,
        actual_method_type: method_type.with(type: method_type.type.with(return_type: type)),
        return_type: type,
        method_decls: decls
      )

      return [call, constr]
    end
  end

  nil
end

#try_tuple_type(array_node, hint) ⇒ Object



4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
# File 'lib/steep/type_construction.rb', line 4985

def try_tuple_type(array_node, hint)
  raise unless array_node.type == :array

  constr = self #: TypeConstruction
  element_types = [] #: Array[AST::Types::t]

  array_node.children.each_with_index do |child, index|
    if child.type == :splat
      type, constr = constr.synthesize(child.children[0])
      typing.add_typing(child, type, nil)
      if converted_type = try_convert(type, :to_a)
        if converted_type.is_a?(AST::Types::Tuple)
          element_types.push(*converted_type.types)
        else
          # The converted_type may be an array, which cannot be used to construct a tuple type
          return
        end
      else
        element_types << type
      end
    else
      child_hint =
        if hint
          hint.types[index]
        end

      type, constr = constr.synthesize(child, hint: child_hint)
      element_types << type
    end
  end

  constr.add_typing(array_node, type: AST::Types::Tuple.new(types: element_types))
end

#try_tuple_type!(node, hint: nil) ⇒ Object



4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
# File 'lib/steep/type_construction.rb', line 4962

def try_tuple_type!(node, hint: nil)
  if node.type == :array
    if node.children.size == 1 && node.children[0]&.type == :splat
      # Skip the array construct
      splat_node = node.children[0] or raise
      splat_value = splat_node.children[0] or raise

      type, constr = try_tuple_type!(splat_value, hint: hint)
      _, constr = constr.add_typing(splat_node, type: AST::Types::Any.instance)
      return constr.add_typing(node, type: type)
    end
    if hint.nil? || hint.is_a?(AST::Types::Tuple)
      typing.new_child() do |child_typing|
        if pair = with_new_typing(child_typing).try_tuple_type(node, hint)
          return pair.with(constr: pair.constr.save_typing)
        end
      end
    end
  end

  synthesize(node, hint: hint)
end

#type_any_rec(node, only_children: false) ⇒ Object



4884
4885
4886
4887
4888
4889
4890
4891
4892
# File 'lib/steep/type_construction.rb', line 4884

def type_any_rec(node, only_children: false)
  add_typing node, type: AST::Builtin.any_type unless only_children

  each_child_node(node) do |child|
    type_any_rec(child)
  end

  Pair.new(type: AST::Builtin.any_type, constr: self)
end

#type_block_without_hint(node:, block_annotations:, block_params:, block_body:) ⇒ Object



4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
# File 'lib/steep/type_construction.rb', line 4474

def type_block_without_hint(node:, block_annotations:, block_params:, block_body:)
  unless block_params
    Diagnostic::Ruby::UnsupportedSyntax.new(
      node: node.children[1],
      message: "Unsupported block params pattern, probably masgn?"
    ).tap do |error|
      if block_given?
        yield error
      else
        typing.add_error(error)
      end
    end

    block_params = TypeInference::BlockParams.new(leading_params: [], optional_params: [], rest_param: nil, trailing_params: [], block_param: nil)
  end

  block_constr = for_block(
    block_body,
    block_params: block_params,
    block_param_hint: nil,
    block_next_type: nil,
    block_block_hint: nil,
    block_annotations: block_annotations,
    block_self_hint: nil,
    node_type_hint: nil
  )

  block_constr.typing.cursor_context.set_body_context(node, block_constr.context)

  block_params.params.each do |param|
    param.each_param do |param|
      _, block_constr = block_constr.synthesize(param.node, hint: param.type)
    end
  end

  block_type = block_constr.synthesize_block(node: node, block_type_hint: nil, block_body: block_body)

  if expected_block_type = block_constr.block_context!.body_type
    block_constr.check_relation(sub_type: block_type, super_type: expected_block_type).else do |result|
      Diagnostic::Ruby::BlockBodyTypeMismatch.new(
        node: node,
        expected: expected_block_type,
        actual: block_type,
        result: result
      ).tap do |error|
        if block_given?
          yield error
        else
          block_constr.typing.add_error(error)
        end
      end
    end
  end
end

#type_check_args(method_name, args, constraints, errors) ⇒ Object



3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
# File 'lib/steep/type_construction.rb', line 3835

def type_check_args(method_name, args, constraints, errors)
  # @type var constr: TypeConstruction
  constr = self

  forwarded_args, es = args.each do |arg|
    case arg
    when TypeInference::SendArgs::PositionalArgs::NodeParamPair
      _, constr = constr.type_check_argument(
        arg.node,
        type: arg.param.type,
        constraints: constraints,
        errors: errors
      )

    when TypeInference::SendArgs::PositionalArgs::NodeTypePair
      _, constr = bypass_splat(arg.node) do |n|
        constr.type_check_argument(
          n,
          type: arg.node_type,
          constraints: constraints,
          report_node: arg.node,
          errors: errors
        )
      end

    when TypeInference::SendArgs::PositionalArgs::UnexpectedArg
      _, constr = bypass_splat(arg.node) do |n|
        constr.synthesize(n)
      end

    when TypeInference::SendArgs::PositionalArgs::SplatArg
      arg_type, _ =
        constr
          .with_child_typing()
          .try_tuple_type!(arg.node.children[0])
      arg.type = arg_type

    when TypeInference::SendArgs::PositionalArgs::MissingArg
      # ignore

    when TypeInference::SendArgs::KeywordArgs::ArgTypePairs
      arg.pairs.each do |pair|
        node, type = pair
        _, constr = bypass_splat(node) do |node|
          constr.type_check_argument(
            node,
            type: type,
            constraints: constraints,
            errors: errors
          )
        end
      end

    when TypeInference::SendArgs::KeywordArgs::UnexpectedKeyword
      if arg.node.type == :pair
        arg.node.children.each do |nn|
          _, constr = constr.synthesize(nn)
        end
      else
        _, constr = bypass_splat(arg.node) do |n|
          constr.synthesize(n)
        end
      end

    when TypeInference::SendArgs::KeywordArgs::SplatArg
      type, _ = bypass_splat(arg.node) do |sp_node|
        if sp_node.type == :hash
          pair = constr.type_hash_record(sp_node, nil) and break pair
        end

        constr.synthesize(sp_node)
      end

      arg.type = type

    when TypeInference::SendArgs::KeywordArgs::MissingKeyword
      # ignore

    else
      raise (_ = arg).inspect
    end
  end

  errors.push(*es)

  if forwarded_args
    method_name or raise "method_name cannot be nil if `forwarded_args` is given, because proc/block doesn't support `...` arg"

    method_context = context.method_context or raise
    forward_arg_type = method_context.forward_arg_type

    case forward_arg_type
    when nil
      if context.method_context.method_type
        raise "Method context must have `forwarded_arg_type` if `...` node appears in it"
      else
        # Skips type checking forwarded argument because the method type is not given
      end
    when true
      # Skip type checking forwarded argument because the method is untyped function
    else
      params, _block = forward_arg_type

      checker.with_context(self_type: self_type, instance_type: context.module_context.instance_type, class_type: context.module_context.module_type, constraints: constraints) do
        result = checker.check_method_params(
          :"... (argument forwarding)",
          Subtyping::Relation.new(
            sub_type: forwarded_args.params,
            super_type: params
          )
        )

        if result.failure?
          errors.push(
            Diagnostic::Ruby::IncompatibleArgumentForwarding.new(
              method_name: method_name,
              node: forwarded_args.node,
              params_pair: [params, forwarded_args.params],
              result: result
            )
          )
        end
      end
    end
  end

  constr
end

#type_check_argument(node, type:, constraints:, report_node: node, errors:) ⇒ Object



4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
# File 'lib/steep/type_construction.rb', line 4463

def type_check_argument(node, type:, constraints:, report_node: node, errors:)
  check(node, type, constraints: constraints) do |expected, actual, result|
    errors << Diagnostic::Ruby::ArgumentTypeMismatch.new(
        node: report_node,
        expected: expected,
        actual: actual,
        result: result
      )
  end
end

#type_check_untyped_args(arguments) ⇒ Object



3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
# File 'lib/steep/type_construction.rb', line 3817

def type_check_untyped_args(arguments)
  constr = self #: TypeConstruction

  arguments.each do |arg|
    case arg.type
    when :splat
      type, constr = constr.synthesize(arg.children[0])
      _, constr = constr.add_typing(arg, type: type)
    when :kwargs
      _, constr = constr.type_hash_record(arg, nil) || constr.type_hash(arg, hint: nil)
    else
      _, constr = constr.synthesize(arg)
    end
  end

  constr
end

#type_hash(hash_node, hint:) ⇒ Object



5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
# File 'lib/steep/type_construction.rb', line 5190

def type_hash(hash_node, hint:)
  if hint
    hint = deep_expand_alias(hint)
  end

  case hint
  when AST::Types::Record
    with_child_typing() do |constr|
      pair = constr.type_hash_record(hash_node, hint)
      if pair
        return pair.with(constr: pair.constr.save_typing)
      end
    end
  when AST::Types::Union
    pair = pick_one_of(hint.types) do |type, constr|
      constr.type_hash(hash_node, hint: type)
    end

    if pair
      return pair
    end
  end

  key_types = [] #: Array[AST::Types::t]
  value_types = [] #: Array[AST::Types::t]

  if hint && AST::Builtin::Hash.instance_type?(hint)
    # @type var hint: AST::Types::Name::Instance
    key_hint, value_hint = hint.args
  end

  hint_hash = AST::Builtin::Hash.instance_type(
    key_hint || AST::Builtin.any_type,
    value_hint || AST::Builtin.any_type
  )

  constr = self #: TypeConstruction

  if hash_node.children.empty?
    key_types << key_hint if key_hint
    value_types << value_hint if value_hint
  else
    hash_node.children.each do |elem|
      case elem.type
      when :pair
        key_node, value_node = elem.children
        key_type, constr = constr.synthesize(key_node, hint: key_hint)
        value_type, constr = constr.synthesize(value_node, hint: value_hint)

        key_types << key_type
        value_types << value_type
      when :kwsplat
        bypass_splat(elem) do |elem_|
          constr.synthesize(elem_, hint: hint_hash).tap do |(type, _)|
            if AST::Builtin::Hash.instance_type?(type)
              # @type var type: AST::Types::Name::Instance
              key_types << type.args.fetch(0)
              value_types << type.args.fetch(1)
            end
          end
        end
      else
        raise
      end
    end
  end

  key_types.reject! {|ty| ty.is_a?(AST::Types::Any) }
  value_types.reject! {|ty| ty.is_a?(AST::Types::Any) }

  key_types << AST::Builtin.any_type if key_types.empty?
  value_types << AST::Builtin.any_type if value_types.empty?

  hash_type = AST::Builtin::Hash.instance_type(
    AST::Types::Union.build(types: key_types),
    AST::Types::Union.build(types: value_types)
  )
  constr.add_typing(hash_node, type: hash_type)
end

#type_hash_record(hash_node, record_type) ⇒ Object



5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
# File 'lib/steep/type_construction.rb', line 5129

def type_hash_record(hash_node, record_type)
  raise unless hash_node.type == :hash || hash_node.type == :kwargs

  constr = self #: TypeConstruction

  if record_type
    hints = record_type.elements.dup
  else
    hints = {} #: Hash[AST::Types::Record::key, AST::Types::t]
  end

  elems = {} #: Hash[AST::Types::Record::key, AST::Types::t]

  each_child_node(hash_node) do |child|
    if child.type == :pair
      case child.children[0].type
      when :sym, :int, :str, :true, :false
        key_node = child.children[0] #: Parser::AST::Node
        value_node = child.children[1] #: Parser::AST::Node

        key =
          case key_node.type
          when :sym, :int, :str
            key_node.children[0]
          when :true
            true
          when :false
            false
          end #: AST::Types::Record::key

        _, constr = constr.synthesize(key_node, hint: AST::Types::Literal.new(value: key))

        value_type, constr = constr.synthesize(value_node, hint: hints[key])

        if hints.key?(key)
          hint_type = hints.fetch(key)
          case
          when value_type.is_a?(AST::Types::Any)
            value_type = hints.fetch(key)
          when hint_type.is_a?(AST::Types::Var)
            value_type = value_type
          end
        else
          typing.add_error(
            Diagnostic::Ruby::UnknownRecordKey.new(key: key, node: key_node)
          )
        end

        elems[key] = value_type
      else
        return
      end
    else
      return
    end
  end

  type = AST::Types::Record.new(elements: elems, required_keys: record_type&.required_keys || Set.new(elems.keys))
  constr.add_typing(hash_node, type: type)
end

#type_lambda(node, params_node:, body_node:, type_hint:) ⇒ Object



3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
# File 'lib/steep/type_construction.rb', line 3098

def type_lambda(node, params_node:, body_node:, type_hint:)
  block_annotations = source.annotations(block: node, factory: checker.factory, context: nesting)
  params = TypeInference::BlockParams.from_node(params_node, annotations: block_annotations)

  if type_hint
    original_hint = type_hint

    type_hint = deep_expand_alias(type_hint) || type_hint

    unless type_hint.is_a?(AST::Types::Any)
      procs = flatten_union(type_hint).select do |type|
        check_relation(sub_type: type, super_type: AST::Builtin::Proc.instance_type).success? &&
          !type.is_a?(AST::Types::Any)
      end

      proc_instances, proc_types = procs.partition {|type| AST::Builtin::Proc.instance_type?(type) }

      case
      when !proc_instances.empty? && proc_types.empty?
        # `::Proc` is given as a hint
      when proc_types.size == 1
        # Proc type is given as a hint
        hint_proc = proc_types[0]  #: AST::Types::Proc
        params_hint = hint_proc.type.params
        return_hint = hint_proc.type.return_type
        block_hint = hint_proc.block
        self_hint = hint_proc.self_type
      else
        typing.add_error(
          Diagnostic::Ruby::ProcHintIgnored.new(hint_type: original_hint, node: node)
        )
      end
    end
  end

  block_constr = for_block(
    body_node,
    block_params: params,
    block_param_hint: params_hint,
    block_next_type: return_hint,
    block_block_hint: block_hint,
    block_annotations: block_annotations,
    block_self_hint: self_hint,
    node_type_hint: nil
  )

  block_constr.typing.cursor_context.set_body_context(node, block_constr.context)

  params.each_single_param do |param|
    _, block_constr = block_constr.synthesize(param.node, hint: param.type)
  end

  block =
    if block_param = params.block_param
      if block_param_type = block_param.type
        case block_param_type
        when AST::Types::Proc
          Interface::Block.new(type: block_param_type.type, optional: false, self_type: block_param_type.self_type)
        else
          if proc_type = optional_proc?(block_param_type)
            Interface::Block.new(type: proc_type.type, optional: true, self_type: proc_type.self_type)
          else
            block_constr.typing.add_error(
              Diagnostic::Ruby::ProcTypeExpected.new(
                node: block_param.node,
                type: block_param_type
              )
            )

            Interface::Block.new(
              type: Interface::Function.new(
                params: Interface::Function::Params.empty,
                return_type: AST::Builtin.any_type,
                location: nil
              ),
              optional: false,
              self_type: nil
            )
          end
        end
      else
        block_hint
      end
    end

  if body_node
    return_type = block_constr.synthesize_block(
      node: node,
      block_body: body_node,
      block_type_hint: return_hint
    )

    return_type = return_type.subst(
      Interface::Substitution.build([], [], self_type: block_constr.self_type)
    )

    if expected_block_type = block_constr.block_context!.body_type
      type_vars = expected_block_type.free_variables.filter_map do |var|
        case var
        when Symbol
          var
        end
      end
      subst = Interface::Substitution.build(type_vars, type_vars.map { AST::Builtin.any_type })
      expected_block_type = expected_block_type.subst(subst)

      check_relation(sub_type: return_type, super_type: expected_block_type).else do |result|
        block_constr.typing.add_error(
          Diagnostic::Ruby::BlockBodyTypeMismatch.new(
            node: node,
            expected: expected_block_type,
            actual: return_type,
            result: result
          )
        )

        return_type = expected_block_type
      end
    end
  else
    return_type = AST::Builtin.any_type
  end

  block_type = AST::Types::Proc.new(
    type: Interface::Function.new(
      params: params_hint || params.params_type,
      return_type: return_type,
      location: nil
    ),
    block: block,
    self_type: block_annotations.self_type || self_hint
  )

  add_typing node, type: block_type
end

#type_masgn(node) ⇒ Object



2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
# File 'lib/steep/type_construction.rb', line 2903

def type_masgn(node)
  lhs, rhs = node.children

  masgn = TypeInference::MultipleAssignment.new()
  hint = masgn.hint_for_mlhs(lhs, context.type_env)

  rhs_type, lhs_constr = try_tuple_type!(rhs, hint: hint).to_ary
  rhs_type = deep_expand_alias(rhs_type) || rhs_type

  falsys, truthys = partition_flatten_types(rhs_type) do |type|
    type.is_a?(AST::Types::Nil) || (type.is_a?(AST::Types::Literal) && type.value == false)
  end

  truthy_rhs_type = union_type_unify(*truthys)
  if truthy_rhs_type.is_a?(AST::Types::Union)
    tup = union_of_tuple_to_tuple_of_union(truthy_rhs_type)
    truthy_rhs_type = tup if tup
  end
  optional = !falsys.empty?

  if truthy_rhs_type.is_a?(AST::Types::Tuple) || AST::Builtin::Array.instance_type?(truthy_rhs_type) || truthy_rhs_type.is_a?(AST::Types::Any)
    constr = lhs_constr.type_masgn_type(lhs, truthy_rhs_type, masgn: masgn, optional: optional)
  else
    ary_type = try_convert(truthy_rhs_type, :to_ary) || try_convert(truthy_rhs_type, :to_a) || AST::Types::Tuple.new(types: [truthy_rhs_type])
    constr = lhs_constr.type_masgn_type(lhs, ary_type, masgn: masgn, optional: optional)
  end

  unless constr
    typing.add_error(
      Diagnostic::Ruby::MultipleAssignmentConversionError.new(
        node: rhs,
        original_type: rhs_type,
        returned_type: ary_type || AST::Builtin.bottom_type
      )
    )

    constr = lhs_constr

    each_descendant_node(lhs) do |node|
      case node.type
      when :lvasgn
        _, constr = constr.lvasgn(node, AST::Builtin.any_type)
      when :ivasgn
        _, constr = constr.ivasgn(node, AST::Builtin.any_type)
      when :gvasgn
        _, constr = constr.gvasgn(node, AST::Builtin.any_type)
      else
        _, constr = constr.add_typing(node, type: AST::Builtin.any_type).to_ary
      end
    end
  end

  constr.add_typing(node, type: truthy_rhs_type)
end

#type_masgn_type(mlhs_node, rhs_type, masgn:, optional:) ⇒ Object



2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
# File 'lib/steep/type_construction.rb', line 2860

def type_masgn_type(mlhs_node, rhs_type, masgn:, optional:)
  # @type var constr: TypeConstruction
  constr = self

  if assignments = masgn.expand(mlhs_node, rhs_type || AST::Builtin.any_type, optional)
    assignments.each do |pair|
      node, type = pair

      if assignments.optional
        type = AST::Builtin.optional(type)
      end

      if node.type == :splat
        asgn_node = node.children[0]
        next unless asgn_node
        var_type = asgn_node.type
      else
        asgn_node = node
        var_type = type
      end

      case asgn_node.type
      when :lvasgn
        _, constr = constr.lvasgn(asgn_node, type)
      when :ivasgn
        _, constr = constr.ivasgn(asgn_node, type)
      when :gvasgn
        _, constr = constr.gvasgn(asgn_node, type)
      when :mlhs
        constr = (constr.type_masgn_type(asgn_node, type, masgn: masgn, optional: optional) or return)
      else
        _, constr = constr.synthesize_children(asgn_node).add_typing(asgn_node, type: AST::Builtin.any_type)
      end

      if node.type == :splat
        _, constr = constr.add_typing(node, type: type)
      end
    end

    constr
  end
end

#type_method_call(node, method_name:, receiver_type:, method:, arguments:, block_params:, block_body:, tapp:, hint:) ⇒ Object



3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
# File 'lib/steep/type_construction.rb', line 3690

def type_method_call(node, method_name:, receiver_type:, method:, arguments:, block_params:, block_body:, tapp:, hint:)
  # @type var fails: Array[[TypeInference::MethodCall::t, TypeConstruction]]
  fails = []

  method.overloads.each do |overload|
    Steep.logger.tagged overload.method_type.to_s do
      typing.new_child() do |child_typing|
        constr = self.with_new_typing(child_typing)

        call, constr = constr.try_special_method(
          node,
          receiver_type: receiver_type,
          method_name: method_name,
          method_overload: overload,
          arguments: arguments,
          block_params: block_params,
          block_body: block_body,
          hint: hint
        ) || constr.try_method_type(
          node,
          receiver_type: receiver_type,
          method_name: method_name,
          method_overload: overload,
          arguments: arguments,
          block_params: block_params,
          block_body: block_body,
          tapp: tapp,
          hint: hint
        )

        if call.is_a?(TypeInference::MethodCall::Typed)
          constr.typing.save!
          return [
            call,
            update_type_env { constr.context.type_env }
          ]
        else
          fails << [call, constr]
        end
      end
    end
  end

  non_arity_errors = fails.reject do |call, _|
    if call.is_a?(TypeInference::MethodCall::Error)
      call.errors.any? do |error|
        error.is_a?(Diagnostic::Ruby::UnexpectedBlockGiven) ||
          error.is_a?(Diagnostic::Ruby::RequiredBlockMissing) ||
          error.is_a?(Diagnostic::Ruby::UnexpectedPositionalArgument) ||
          error.is_a?(Diagnostic::Ruby::InsufficientPositionalArguments) ||
          error.is_a?(Diagnostic::Ruby::UnexpectedKeywordArgument) ||
          error.is_a?(Diagnostic::Ruby::InsufficientKeywordArguments)
      end
    end
  end

  unless non_arity_errors.empty?
    fails = non_arity_errors
  end

  if fails.one?
    call, constr = fails.fetch(0)

    constr.typing.save!

    [
      call,
      update_type_env { constr.context.type_env }
    ]
  else
    nil
  end
end

#type_name(type) ⇒ Object



5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
# File 'lib/steep/type_construction.rb', line 5290

def type_name(type)
  case type
  when AST::Types::Name::Instance, AST::Types::Name::Singleton
    type.name
  when AST::Types::Literal
    type_name(type.back_type)
  when AST::Types::Tuple
    AST::Builtin::Array.module_name
  when AST::Types::Record
    AST::Builtin::Hash.module_name
  when AST::Types::Proc
    AST::Builtin::Proc.module_name
  when AST::Types::Boolean, AST::Types::Logic::Base
    nil
  end
end

#type_send(node, send_node:, block_params:, block_body:, unwrap: false, tapp:, hint:) ⇒ Object



3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
# File 'lib/steep/type_construction.rb', line 3467

def type_send(node, send_node:, block_params:, block_body:, unwrap: false, tapp:, hint:)
  # @type var constr: TypeConstruction
  # @type var receiver: Parser::AST::Node?

  case send_node.type
  when :super, :zsuper
    receiver = nil
    method_name = method_context!.name
    arguments = send_node.children

    if method_name.nil? || method_context!.super_method.nil?
      return fallback_to_any(send_node) do
        Diagnostic::Ruby::UnexpectedSuper.new(
          node: send_node,
          method: method_context&.name
        )
      end
    end

    recv_type = AST::Types::Self.instance
    constr = self
  else
    receiver, method_name, *arguments = send_node.children
    if receiver
      recv_type, constr = synthesize(receiver)
    else
      recv_type = AST::Types::Self.instance
      constr = self
    end
  end

  if unwrap
    recv_type = unwrap(recv_type)
  end

  receiver_type = checker.factory.deep_expand_alias(recv_type)
  private = receiver.nil? || receiver.type == :self

  type, constr =
    case receiver_type
    when nil
      raise

    when AST::Types::Any
      case node.type
      when :block, :numblock
        # @type var node: Parser::AST::Node & Parser::AST::_BlockNode
        block_annotations = source.annotations(block: node, factory: checker.factory, context: nesting)
        block_params or raise

        constr = constr.synthesize_children(node.children[0], skips: [receiver])

        constr.type_block_without_hint(
          node: node,
          block_params: TypeInference::BlockParams.from_node(block_params, annotations: block_annotations),
          block_annotations: block_annotations,
          block_body: block_body
        ) do |error|
          constr.typing.errors << error
        end
      else
        constr = constr.synthesize_children(node, skips: [receiver])
      end

      constr.add_call(
        TypeInference::MethodCall::Untyped.new(
          node: node,
          context: context.call_context,
          method_name: method_name
        )
      )
    else
      if interface = calculate_interface(receiver_type, private: private)
        constr.type_send_interface(
          node,
          interface: interface,
          receiver: receiver,
          receiver_type: receiver_type,
          method_name: method_name,
          arguments: arguments,
          block_params: block_params,
          block_body: block_body,
          tapp: tapp,
          hint: hint
        )
      else
        constr = constr.synthesize_children(node, skips: [receiver])
        constr.add_call(
          TypeInference::MethodCall::NoMethodError.new(
            node: node,
            context: context.call_context,
            method_name: method_name,
            receiver_type: receiver_type,
            error: Diagnostic::Ruby::NoMethod.new(node: node, method: method_name, type: receiver_type)
          )
        )
      end
    end

  Pair.new(type: type, constr: constr)
end

#type_send_interface(node, interface:, receiver:, receiver_type:, method_name:, arguments:, block_params:, block_body:, tapp:, hint:) ⇒ Object



3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
# File 'lib/steep/type_construction.rb', line 3280

def type_send_interface(node, interface:, receiver:, receiver_type:, method_name:, arguments:, block_params:, block_body:, tapp:, hint:)
  method = interface.methods[method_name]

  if method
    call, constr = type_method_call(
      node,
      method: method,
      method_name: method_name,
      arguments: arguments,
      block_params: block_params,
      block_body: block_body,
      receiver_type: receiver_type,
      tapp: tapp,
      hint: hint
    )

    if call && constr
      case method_name.to_s
      when "[]="
        if test_send_node(node) {|_, _, _, loc| !loc.dot }
          last_arg = arguments.last or raise
          if typing.has_type?(last_arg)
            call = call.with_return_type(typing.type_of(node: last_arg))
          end
        end
      when /\w=\Z/
        last_arg = arguments.last or raise
        if typing.has_type?(last_arg)
          call = call.with_return_type(typing.type_of(node: last_arg))
        end
      end

      if call.is_a?(TypeInference::MethodCall::Typed)
        if (pure_call, type = constr.context.type_env.pure_method_calls.fetch(node, nil))
          if type
            call = pure_call.update(node: node, return_type: type)
            constr.add_typing(node, type: call.return_type)
          end
        else
          if pure_send?(call, receiver, arguments)
            constr = constr.update_type_env do |env|
              env.add_pure_call(node, call, call.return_type)
            end
          else
            constr = constr.update_type_env do |env|
              if receiver
                env.invalidate_pure_node(receiver)
              else
                env
              end
            end
          end
        end

        if (_, message = deprecated_send?(call))
          send_node, _ = deconstruct_sendish_and_block_nodes(node)
          send_node or raise
          _, _, _, loc = deconstruct_send_node!(send_node)

          constr.typing.add_error(
            Diagnostic::Ruby::DeprecatedReference.new(
              node: node,
              location: loc.selector,
              message: message
            )
          )
        end
      end

      if node.type == :csend || ((node.type == :block || node.type == :numblock) && node.children[0].type == :csend)
        optional_type = AST::Types::Union.build(types: [call.return_type, AST::Builtin.nil_type])
        call = call.with_return_type(optional_type)
      end
    else
      errors = [] #: Array[Diagnostic::Ruby::Base]

      skips = [receiver]
      skips << node.children[0] if node.type == :block

      constr = synthesize_children(node, skips: skips)
      if block_params
        # @type var node: Parser::AST::Node & Parser::AST::_BlockNode
        block_annotations = source.annotations(block: node, factory: checker.factory, context: nesting)

        constr.type_block_without_hint(
          node: node,
          block_params: TypeInference::BlockParams.from_node(block_params, annotations: block_annotations),
          block_annotations: block_annotations,
          block_body: block_body
        ) do |error|
          errors << error
        end
      end

      errors << Diagnostic::Ruby::UnresolvedOverloading.new(
        node: node,
        receiver_type: interface.type,
        method_name: method_name,
        method_types: method.method_types
      )

      decls =  method.overloads.flat_map do |method_overload|
        method_overload.method_decls(method_name)
      end.to_set

      call = TypeInference::MethodCall::Error.new(
        node: node,
        context: context.call_context,
        method_name: method_name,
        receiver_type: receiver_type,
        errors: errors,
        method_decls: decls
      )
    end

    # Handle block_given? type narrowing
    if method_name == :block_given? && call.is_a?(TypeInference::MethodCall::Typed)
      if call.method_decls.all? { _1.method_name == KERNEL_BLOCK_GIVEN }
        if (block_var = constr.method_context&.block_param_name)
          if (var_type = constr.context.type_env[block_var])
            unwrapped = constr.checker.factory.unwrap_optional(var_type)

            if unwrapped
              truthy_env = constr.context.type_env.refine_types(
                local_variable_types: { block_var => unwrapped }
              )
              falsy_env = constr.context.type_env.refine_types(
                local_variable_types: { block_var => AST::Builtin.nil_type }
              )

              env_type = AST::Types::Logic::Env.new(
                truthy: truthy_env,
                falsy: falsy_env,
                type: call.return_type
              )

              call = call.with_return_type(env_type)
            end
          end
        end
      end
    end

    constr.add_call(call)
  else
    skips = [] #: Array[Parser::AST::Node?]
    skips << receiver if receiver
    skips << node.children[0] if node.type == :block
    skips << block_params if block_params
    skips << block_body if block_body

    constr = synthesize_children(node, skips: skips)
    if block_params
      # @type var node: Parser::AST::Node & Parser::AST::_BlockNode
      block_annotations = source.annotations(block: node, factory: checker.factory, context: nesting)

      constr.type_block_without_hint(
        node: node,
        block_params: TypeInference::BlockParams.from_node(block_params, annotations: block_annotations),
        block_annotations: block_annotations,
        block_body: block_body
      )
    end

    if node.type == :block
      send_node = node.children[0]
      case send_node.type
      when :super, :zsuper
        method_name = method_context!.name or raise
        return fallback_to_any(send_node) do
          Diagnostic::Ruby::UnexpectedSuper.new(node: send_node, method: method_name)
        end
      end
    end

    constr.add_call(
      TypeInference::MethodCall::NoMethodError.new(
        node: node,
        context: context.call_context,
        method_name: method_name,
        receiver_type: receiver_type,
        error: Diagnostic::Ruby::NoMethod.new(node: node, method: method_name, type: interface&.type || receiver_type)
      )
    )
  end
end

#union_of_tuple_to_tuple_of_union(type) ⇒ Object



4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
# File 'lib/steep/type_construction.rb', line 4743

def union_of_tuple_to_tuple_of_union(type)
  if type.types.all? {|ty| ty.is_a?(AST::Types::Tuple) }
    # @type var tuples: Array[AST::Types::Tuple]
    tuples = _ = type.types

    max = tuples.map {|tup| tup.types.size }.max or raise

    # @type var tuple_types_array: Array[Array[AST::Types::t]]
    tuple_types_array = tuples.map do |tup|
      if tup.types.size == max
        tup.types
      else
        tup.types + Array.new(max - tup.types.size, AST::Builtin.nil_type)
      end
    end

    # @type var tuple_elems_array: Array[Array[AST::Types::t]]
    tuple_elems_array = tuple_types_array.transpose
    AST::Types::Tuple.new(
      types: tuple_elems_array.map {|types| union_type_unify(*types) }
    )
  end
end

#union_type(*types) ⇒ Object



4713
4714
4715
4716
# File 'lib/steep/type_construction.rb', line 4713

def union_type(*types)
  raise if types.empty?
  AST::Types::Union.build(types: types.compact)
end

#union_type_unify(*types) ⇒ Object



4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
# File 'lib/steep/type_construction.rb', line 4718

def union_type_unify(*types)
  types = types.reject {|t| t.is_a?(AST::Types::Bot) }

  if types.empty?
    AST::Types::Bot.instance
  else
    types.inject do |type1, type2|
      next type2 if type1.is_a?(AST::Types::Any)
      next type1 if type2.is_a?(AST::Types::Any)

      unless no_subtyping?(sub_type: type1, super_type: type2)
        # type1 <: type2
        next type2
      end

      unless no_subtyping?(sub_type: type2, super_type: type1)
        # type2 <: type1
        next type1
      end

      union_type(type1, type2)
    end
  end
end

#unwrap(type) ⇒ Object



4894
4895
4896
# File 'lib/steep/type_construction.rb', line 4894

def unwrap(type)
  checker.factory.unwrap_optional(type) || AST::Types::Bot.instance
end

#update_contextObject



127
128
129
# File 'lib/steep/type_construction.rb', line 127

def update_context()
  with(context: yield(self.context))
end

#update_type_envObject



131
132
133
# File 'lib/steep/type_construction.rb', line 131

def update_type_env
  with_updated_context(type_env: yield(context.type_env))
end

#validate_method_definitions(node, module_name) ⇒ Object



4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
# File 'lib/steep/type_construction.rb', line 4767

def validate_method_definitions(node, module_name)
  module_name_1 = module_name.name
  module_entry = checker.factory.env.module_class_entry(module_name_1, normalized: true) or raise
  member_decl_count = module_entry.each_decl.count do |decl|
    case decl
    when RBS::AST::Declarations::Base
      decl.each_member.count > 0
    else
      false
    end
  end

  return unless member_decl_count == 1

  expected_instance_method_names = (module_context.instance_definition&.methods || {}).each.with_object(Set[]) do |(name, method), set|
    if method.implemented_in
      if method.implemented_in == module_context.instance_definition&.type_name
        set << name
      end
    end
  end
  expected_module_method_names = (module_context.module_definition&.methods || {}).each.with_object(Set[]) do |(name, method), set|
    if name != :new
      if method.implemented_in
        if method.implemented_in == module_context.module_definition&.type_name
          set << name
        end
      end
    end
  end

  expected_instance_method_names.each do |method_name|
    case
    when module_context.defined_instance_methods.include?(method_name)
      # ok
    when annotations.instance_dynamics.include?(method_name)
      # ok
    else
      if module_name.name == module_context&.class_name
        typing.add_error(
          Diagnostic::Ruby::MethodDefinitionMissing.new(
            node: node,
            module_name: module_name.name,
            kind: :instance,
            missing_method: method_name
          )
        )
      end
    end
  end
  expected_module_method_names.each do |method_name|
    case
    when module_context.defined_module_methods.include?(method_name)
      # ok
    when annotations.module_dynamics.include?(method_name)
      # ok
    else
      if module_name.name == module_context&.class_name
        typing.add_error(
          Diagnostic::Ruby::MethodDefinitionMissing.new(node: node,
                                                        module_name: module_name.name,
                                                        kind: :module,
                                                        missing_method: method_name)
        )
      end
    end
  end

  annotations.instance_dynamics.each do |method_name|
    unless expected_instance_method_names.member?(method_name)
      typing.add_error(
        Diagnostic::Ruby::UnexpectedDynamicMethod.new(node: node,
                                                      module_name: module_name.name,
                                                      method_name: method_name)
      )
    end
  end
  annotations.module_dynamics.each do |method_name|
    unless expected_module_method_names.member?(method_name)
      typing.add_error(
        Diagnostic::Ruby::UnexpectedDynamicMethod.new(node: node,
                                                      module_name: module_name.name,
                                                      method_name: method_name)
      )
    end
  end
end

#variable_contextObject



83
84
85
# File 'lib/steep/type_construction.rb', line 83

def variable_context
  context.variable_context
end

#with(annotations: self.annotations, context: self.context, typing: self.typing) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/steep/type_construction.rb', line 113

def with(annotations: self.annotations, context: self.context, typing: self.typing)
  if context != self.context || typing != self.typing
    self.class.new(
      checker: checker,
      source: source,
      annotations: annotations,
      typing: typing,
      context: context
    )
  else
    self
  end
end

#with_child_typingObject



3764
3765
3766
3767
3768
3769
3770
3771
3772
# File 'lib/steep/type_construction.rb', line 3764

def with_child_typing()
  constr = with_new_typing(typing.new_child())

  if block_given?
    yield constr
  else
    constr
  end
end

#with_class_constr(node, new_class_name, super_class_name) ⇒ Object



572
573
574
575
576
577
578
# File 'lib/steep/type_construction.rb', line 572

def with_class_constr(node, new_class_name, super_class_name)
  constr = for_class(node, new_class_name, super_class_name)

  constr.checker.push_variable_bounds(constr.variable_context.upper_bounds) do
    yield constr
  end
end

#with_method_constr(method_name, node, args:, self_type:, definition:) ⇒ Object



302
303
304
305
306
307
# File 'lib/steep/type_construction.rb', line 302

def with_method_constr(method_name, node, args:, self_type:, definition:)
  constr = for_new_method(method_name, node, args: args, self_type: self_type, definition: definition)
  constr.checker.push_variable_bounds(constr.variable_context.upper_bounds) do
    yield constr
  end
end

#with_module_constr(node, module_name) ⇒ Object



481
482
483
484
485
486
# File 'lib/steep/type_construction.rb', line 481

def with_module_constr(node, module_name)
  constr = for_module(node, module_name)
  constr.checker.push_variable_bounds(constr.variable_context.upper_bounds) do
    yield constr
  end
end

#with_new_typing(typing) ⇒ Object



95
96
97
98
99
100
101
102
103
# File 'lib/steep/type_construction.rb', line 95

def with_new_typing(typing)
  self.class.new(
    checker: checker,
    source: source,
    annotations: annotations,
    typing: typing,
    context: context
  )
end

#with_sclass_constr(node, type) ⇒ Object



580
581
582
583
584
585
586
587
588
# File 'lib/steep/type_construction.rb', line 580

def with_sclass_constr(node, type)
  if constr = for_sclass(node, type)
    constr.checker.push_variable_bounds(constr.variable_context.upper_bounds) do
      yield constr
    end
  else
    yield nil
  end
end

#with_updated_context(type_env: self.context.type_env) ⇒ Object



105
106
107
108
109
110
111
# File 'lib/steep/type_construction.rb', line 105

def with_updated_context(type_env: self.context.type_env)
  unless type_env.equal?(self.context.type_env)
    with(context: self.context.with(type_env: type_env))
  else
    self
  end
end