Class: Steep::Subtyping::Check

Inherits:
Object
  • Object
show all
Includes:
Result::Helper
Defined in:
lib/steep/subtyping/check.rb

Constant Summary collapse

ABORT_LIMIT =
ENV.fetch("STEEP_SUBTYPING_ABORT_LIMIT", 50).to_i

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Result::Helper

#All, #Any, #Expand, #Failure, #Skip, #Success

Constructor Details

#initialize(builder:) ⇒ Check

Returns a new instance of Check.



9
10
11
12
13
# File 'lib/steep/subtyping/check.rb', line 9

def initialize(builder:)
  @builder = builder
  @cache = Cache.new()
  @bounds = []
end

Instance Attribute Details

#builderObject (readonly)

Returns the value of attribute builder.



6
7
8
# File 'lib/steep/subtyping/check.rb', line 6

def builder
  @builder
end

#cacheObject (readonly)

Returns the value of attribute cache.



7
8
9
# File 'lib/steep/subtyping/check.rb', line 7

def cache
  @cache
end

Instance Method Details

#alias?(type) ⇒ Boolean

Returns:

  • (Boolean)


223
224
225
# File 'lib/steep/subtyping/check.rb', line 223

def alias?(type)
  type.is_a?(AST::Types::Name::Alias)
end

#arg_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


629
630
631
632
633
634
635
636
# File 'lib/steep/subtyping/check.rb', line 629

def arg_type?(type)
  case type
  when AST::Types::Name::Instance, AST::Types::Name::Interface
    type.args.size > 0
  else
    false
  end
end

#assumptionsObject



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

def assumptions
  @assumptions || raise
end

#cache_bounds(relation) ⇒ Object



213
214
215
216
217
218
219
220
221
# File 'lib/steep/subtyping/check.rb', line 213

def cache_bounds(relation)
  vars = relation.sub_type.free_variables + relation.super_type.free_variables
  vars.each.with_object({}) do |var, hash| #$ Hash[Symbol, AST::Types::t]
    next unless var.is_a?(Symbol)
    if upper_bound = variable_upper_bound(var)
      hash[var] = upper_bound
    end
  end
end

#cacheable?(relation) ⇒ Boolean

Returns:

  • (Boolean)


227
228
229
# File 'lib/steep/subtyping/check.rb', line 227

def cacheable?(relation)
  relation.sub_type.free_variables.empty? && relation.super_type.free_variables.empty?
end

#check(relation, constraints:, self_type:, instance_type:, class_type:) ⇒ Object



179
180
181
182
183
# File 'lib/steep/subtyping/check.rb', line 179

def check(relation, constraints:, self_type:, instance_type:, class_type:)
  with_context(self_type: self_type, instance_type: instance_type, class_type: class_type, constraints: constraints) do
    check_type(relation)
  end
end

#check_constraints(relation, variables:, variance:) ⇒ Object



839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
# File 'lib/steep/subtyping/check.rb', line 839

def check_constraints(relation, variables:, variance:)
  checker = Check.new(builder: builder)

  constraints.solution(
    checker,
    variance: variance,
    variables: variables,
    self_type: self_type,
    instance_type: instance_type,
    class_type: class_type
  )

  Success(relation)
rescue Constraints::UnsatisfiableConstraint => error
  Failure(relation, Result::Failure::UnsatisfiedConstraints.new(error))
end

#check_function(name, relation) ⇒ Object



909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
# File 'lib/steep/subtyping/check.rb', line 909

def check_function(name, relation)
  relation.function!

  All(relation) do |result|
    if relation.sub_type.params && relation.super_type.params
      result.add(relation.map {|fun| _ = fun.params }) do |rel|
        check_method_params(name, rel)
      end
    end

    result.add(relation.map {|fun| fun.return_type }) do |rel|
      check_type(rel)
    end
  end
end

#check_generic_method_type(name, relation) ⇒ Object



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
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
# File 'lib/steep/subtyping/check.rb', line 716

def check_generic_method_type(name, relation)
  relation.method!

  sub_type, super_type = relation

  case
  when sub_type.type_params.empty? && super_type.type_params.empty?
    check_method_type(name, relation)

  when !sub_type.type_params.empty? && super_type.type_params.empty?
    # Check if super_type is an instance of sub_type.
    Expand(relation) do
      sub_args = sub_type.type_params.map {|param| AST::Types::Var.fresh(param.name) }
      sub_type_ = sub_type.instantiate(Interface::Substitution.build(sub_type.type_params.map(&:name), sub_args))

      sub_args.each do |s|
        constraints.unknown!(s.name)
      end

      relation = Relation.new(sub_type: sub_type_, super_type: super_type)
      All(relation) do |result|
        sub_args.zip(sub_type.type_params).each do |arg, param|
          param or raise

          if ub = param.upper_bound
            result.add(Relation.new(sub_type: arg, super_type: ub)) do |rel|
              check_type(rel)
            end
          end
        end

        if failure = match_method_type_fails?(name, sub_type_, super_type)
          result.add_result(failure)
        else
          result.add_result(check_method_type(name, Relation(sub_type_, super_type)))
        end

        result.add(relation) do |rel|
          check_constraints(
            relation,
            variables: sub_args.map(&:name),
            variance: VariableVariance.from_method_type(sub_type_)
          )
        end
      end
    end

  when sub_type.type_params.empty? && !super_type.type_params.empty?
    # Check if sub_type is an instance of super_type && no constraints on type variables (any).
    All(relation) do |result|
      super_args = super_type.type_params.map {|param| AST::Types::Var.fresh(param.name) }
      super_type_ = super_type.instantiate(Interface::Substitution.build(super_type.type_params.map(&:name), super_args))

      if failure = match_method_type_fails?(name, sub_type, super_type_)
        result.add_result(failure)
      else
        super_args.each do |arg|
          constraints.unknown!(arg.name)
        end

        result.add(Relation(sub_type, super_type_)) do |rel_|
          ret = check_method_type(name, rel_)

          if ret.success? && super_args.map(&:name).none? {|var| constraints.has_constraint?(var) }
            ret
          else
            Failure(rel_, Result::Failure::PolyMethodSubtyping.new(name: name))
          end
        end
      end
    end

  when super_type.type_params.size == sub_type.type_params.size
    # If they have the same arity, run the normal F-sub subtyping checking.
    All(relation) do |result|
      args = sub_type.type_params.map {|type_param| AST::Types::Var.fresh(type_param.name) }
      args.each {|arg| constraints.unknown!(arg.name) }

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

      args.zip(sub_type.type_params, super_type.type_params).each do |arg, sub_param, sup_param|
        # @type var arg: AST::Types::Var
        # @type var sub_param: Interface::TypeParam?
        # @type var super_param: Interface::TypeParam?

        sub_param or raise
        sup_param or raise

        sub_ub = sub_param.upper_bound
        sup_ub = sup_param.upper_bound

        case
        when sub_ub && sup_ub
          upper_bounds[arg.name] = sub_ub
          relations << Relation.new(sub_type: sub_ub, super_type: sup_ub)
        when sub_ub && !sup_ub
          upper_bounds[arg.name] = sub_ub
        when !sub_ub && sup_ub
          result.add(Relation.new(sub_type: AST::Types::Var.new(name: sub_param.name), super_type: sub_ub)) do |rel|
            Failure(rel, Result::Failure::PolyMethodSubtyping.new(name: name))
          end
        when !sub_ub && !sup_ub
          # no constraints
        end
      end

      push_variable_bounds(upper_bounds) do
        sub_type_ = sub_type.instantiate(Interface::Substitution.build(sub_type.type_params.map(&:name), args))
        super_type_ = super_type.instantiate(Interface::Substitution.build(super_type.type_params.map(&:name), args))

        result.add(*relations) {|rel| check_type(rel) }
        result.add(Relation.new(sub_type: sub_type_, super_type: super_type_)) do |rel|
          check_method_type(name, rel)
        end
      end
    end

  else
    Failure(relation, Result::Failure::PolyMethodSubtyping.new(name: name))
  end
end

#check_interface(relation) ⇒ Object



674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# File 'lib/steep/subtyping/check.rb', line 674

def check_interface(relation)
  relation.interface!

  sub_interface, super_interface = relation

  method_pairs = super_interface.methods.each_with_object({}) do |(method_name, sup_method), hash| #$ Hash[Symbol, Relation[Interface::Shape::Entry]]
    if sub_method = sub_interface.methods[method_name]
      hash[method_name] = Relation.new(sub_type: sub_method, super_type: sup_method)
    else
      return Failure(relation) { Result::Failure::MethodMissingError.new(name: method_name) }
    end
  end

  All(relation) do |result|
    method_pairs.each do |method_name, method_relation|
      result.add(method_relation) do
        check_method(method_name, method_relation)
      end
    end
  end
end

#check_method(name, relation) ⇒ Object



696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
# File 'lib/steep/subtyping/check.rb', line 696

def check_method(name, relation)
  relation.method!

  sub_method, super_method = relation

  All(relation) do |all|
    super_method.method_types.each do |super_type|
      all.add(Relation.new(sub_type: sub_method, super_type: super_type)) do |rel|
        Any(rel) do |any|
          sub_method.method_types.each do |sub_type|
            any.add(Relation.new(sub_type: sub_type, super_type: super_type)) do |rel|
              check_generic_method_type(name, rel)
            end
          end
        end
      end
    end
  end
end

#check_method_params(name, relation) ⇒ Object



942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
# File 'lib/steep/subtyping/check.rb', line 942

def check_method_params(name, relation)
  relation.params!
  pairs = match_params(name, relation)

  case pairs
  when Array
    unless pairs.empty?
      All(relation) do |result|
        pairs.each do |sub_type, super_type|
          result.add(Relation.new(sub_type: super_type, super_type: sub_type)) do |rel|
            check_type(rel)
          end
        end

        result
      end
    else
      Success(relation)
    end
  else
    pairs
  end
end

#check_method_type(name, relation) ⇒ Object



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
# File 'lib/steep/subtyping/check.rb', line 856

def check_method_type(name, relation)
  Steep.logger.tagged "#{name} : #{relation.sub_type} <: #{relation.super_type}" do
    relation.method!

    sub_type, super_type = relation

    sub_type.type_params.empty? or raise "Expected monomorphic method type: #{sub_type}"
    super_type.type_params.empty? or raise "Expected monomorphic method type: #{super_type}"

    All(relation) do |result|
      type_relation = Relation.new(sub_type: sub_type.type, super_type: super_type.type)

      ret = expand_block_given(name, Relation.new(sub_type: sub_type.block, super_type: super_type.block))

      case ret
      when true
        result.add(type_relation) { check_function(name, type_relation) }
      when Relation
        result.add(type_relation) { check_function(name, type_relation) }
        result.add(ret) do
          All(ret) do |result|
            result.add_result(check_self_type_binding(ret, ret.super_type.self_type, ret.sub_type.self_type))
            result.add(Relation(ret.super_type.type, ret.sub_type.type)) do |block_relation|
              check_function(name, block_relation)
            end
          end
        end
      when Result::Failure
        result.add(ret.relation) { ret }
      end.tap do |ret|
        Steep.logger.debug "result=#{ret.class}"
      end
    end
  end
end

#check_self_type_binding(relation, sub_self, super_self) ⇒ Object



925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
# File 'lib/steep/subtyping/check.rb', line 925

def check_self_type_binding(relation, sub_self, super_self)
  case
  when sub_self.nil? && super_self.nil?
    nil
  when sub_self && super_self
    # ^() [self: T] -> void <: ^() [self: S] -> void                              ==> S <: T
    # () { () [self: S] -> void } -> void <: () { () [self: T] -> void } -> void  ==> S <: T
    check_type(Relation(super_self, sub_self))
  when sub_self.is_a?(AST::Types::Top) && super_self.nil?
    # ^() [self: top] -> void <: ^() -> void                              ==> OK
    # () { () -> void } -> void <: () { () [self: top] -> void } -> void  ==> OK
    nil
  else
    Failure(relation, Result::Failure::SelfBindingMismatch.new)
  end
end

#check_type(relation) ⇒ Object



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
# File 'lib/steep/subtyping/check.rb', line 185

def check_type(relation)
  if assumptions.size > ABORT_LIMIT
    return Failure(relation, Result::Failure::LoopAbort.new)
  end

  relation.type!

  Steep.logger.tagged "#{relation.sub_type} <: #{relation.super_type}" do
    bounds = cache_bounds(relation)
    fvs = relation.sub_type.free_variables + relation.super_type.free_variables
    cached = cache[relation, @self_type, @instance_type, @class_type, bounds]
    if cached && fvs.none? {|var| var.is_a?(Symbol) && constraints.unknown?(var) }
      cached
    else
      if assumptions.member?(relation)
        success(relation)
      else
        push_assumption(relation) do
          check_type0(relation).tap do |result|
            Steep.logger.debug "result=#{result.class}"
            cache[relation, @self_type, @instance_type, @class_type, bounds] = result
          end
        end
      end
    end
  end
end

#check_type0(relation) ⇒ Object



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
301
302
303
304
305
306
307
308
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
335
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
368
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
480
481
482
483
484
485
486
487
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'lib/steep/subtyping/check.rb', line 251

def check_type0(relation)
  case
  when same_type?(relation)
    success(relation)

  when relation.sub_type.is_a?(AST::Types::Any) || relation.super_type.is_a?(AST::Types::Any)
    success(relation)

  when relation.super_type.is_a?(AST::Types::Void)
    success(relation)

  when relation.super_type.is_a?(AST::Types::Top)
    success(relation)

  when relation.sub_type.is_a?(AST::Types::Bot)
    success(relation)

  when relation.super_type.is_a?(AST::Types::Boolean)
    Expand(relation) do
      check_type(
        Relation.new(
          sub_type: relation.sub_type,
          super_type: AST::Types::Union.build(types: [AST::Builtin.true_type, AST::Builtin.false_type])
        )
      )
    end

  when relation.sub_type.is_a?(AST::Types::Boolean) || relation.sub_type.is_a?(AST::Types::Logic::Base)
    Expand(relation) do
      check_type(
        Relation.new(
          sub_type: AST::Types::Union.build(types: [AST::Builtin.true_type, AST::Builtin.false_type]),
          super_type: relation.super_type
        )
      )
    end

  when relation.sub_type.is_a?(AST::Types::Instance) && !instance_type.is_a?(AST::Types::Instance)
    Expand(relation) do
      check_type(Relation.new(sub_type: instance_type, super_type: relation.super_type))
    end

  when relation.super_type.is_a?(AST::Types::Instance) && !instance_type.is_a?(AST::Types::Instance)
    All(relation) do |result|
      rel = Relation.new(sub_type: relation.sub_type, super_type: instance_type)
      result.add(rel, rel.flip) do |r|
        check_type(r)
      end
    end.tap do
      Steep.logger.error { "`T <: instance` doesn't hold generally, but testing it with `#{relation} && #{relation.flip}` for compatibility"}
    end

  when relation.sub_type.is_a?(AST::Types::Class) && !instance_type.is_a?(AST::Types::Class)
    Expand(relation) do
      check_type(Relation.new(sub_type: class_type, super_type: relation.super_type))
    end

  when relation.super_type.is_a?(AST::Types::Class) && !instance_type.is_a?(AST::Types::Class)
    All(relation) do |result|
      rel = Relation.new(sub_type: relation.sub_type, super_type: class_type)
      result.add(rel, rel.flip) do |r|
        check_type(r)
      end
    end.tap do
      Steep.logger.error { "`T <: class` doesn't hold generally, but testing with `#{relation} && |- #{relation.flip}` for compatibility"}
    end

  when alias?(relation.sub_type)
    Expand(relation) do
      check_type(Relation.new(sub_type: expand_alias(relation.sub_type), super_type: relation.super_type))
    end

  when alias?(relation.super_type)
    Expand(relation) do
      check_type(Relation.new(super_type: expand_alias(relation.super_type), sub_type: relation.sub_type))
    end

  when relation.super_type.is_a?(AST::Types::Var) && constraints.unknown?(relation.super_type.name)
    if ub = variable_upper_bound(relation.super_type.name)
      Expand(relation) do
        check_type(Relation.new(sub_type: relation.sub_type, super_type: ub))
      end.tap do |result|
        if result.success?
          constraints.add(relation.super_type.name, sub_type: relation.sub_type)
        end
      end
    else
      constraints.add(relation.super_type.name, sub_type: relation.sub_type)
      Success(relation)
    end

  when relation.sub_type.is_a?(AST::Types::Var) && constraints.unknown?(relation.sub_type.name)
    constraints.add(relation.sub_type.name, super_type: relation.super_type)
    Success(relation)

  when relation.sub_type.is_a?(AST::Types::Var) && ub = variable_upper_bound(relation.sub_type.name)
    Expand(relation) do
      check_type(Relation.new(sub_type: ub, super_type: relation.super_type))
    end

  when relation.sub_type.is_a?(AST::Types::Intersection) && relation.super_type.is_a?(AST::Types::Union)
    Any(relation) do |base_result|
      # Expand the super_type first
      base_result.add(relation) do
        Any(relation) do |result|
          relation.super_type.types.sort_by {|ty| (path = hole_path(ty)) ? -path.size : -Float::INFINITY }.each do |super_type|
            rel = Relation.new(sub_type: relation.sub_type, super_type: super_type)
            result.add(rel) do
              check_type(rel)
            end
          end
        end
      end

      # Expand the sub_type if it fails
      base_result.add(relation) do
        Any(relation) do |result|
          relation.sub_type.types.sort_by {|ty| (path = hole_path(ty)) ? -path.size : -Float::INFINITY }.each do |sub_type|
            rel = Relation.new(sub_type: sub_type, super_type: relation.super_type)
            result.add(rel) do
              check_type(rel)
            end
          end
        end
      end
    end

  when relation.super_type.is_a?(AST::Types::Intersection)
    All(relation) do |result|
      relation.super_type.types.each do |super_type|
        result.add(Relation.new(sub_type: relation.sub_type, super_type: super_type)) do |rel|
          check_type(rel)
        end
      end
    end

  when relation.sub_type.is_a?(AST::Types::Union)
    All(relation) do |result|
      relation.sub_type.types.each do |sub_type|
        rel = Relation.new(sub_type: sub_type, super_type: relation.super_type)
        result.add(rel) do
          check_type(rel)
        end
      end
    end

  when relation.sub_type.is_a?(AST::Types::Intersection)
    Any(relation) do |result|
      relation.sub_type.types.sort_by {|ty| (path = hole_path(ty)) ? -path.size : -Float::INFINITY }.each do |sub_type|
        rel = Relation.new(sub_type: sub_type, super_type: relation.super_type)
        result.add(rel) do
          check_type(rel)
        end
      end
    end

  when relation.super_type.is_a?(AST::Types::Union)
    Any(relation) do |result|
      relation.super_type.types.sort_by {|ty| (path = hole_path(ty)) ? -path.size : -Float::INFINITY }.each do |super_type|
        rel = Relation.new(sub_type: relation.sub_type, super_type: super_type)
        result.add(rel) do
          check_type(rel)
        end
      end
    end

  when relation.sub_type.is_a?(AST::Types::Self) && !self_type.is_a?(AST::Types::Self)
    Expand(relation) do
      check_type(Relation.new(sub_type: self_type, super_type: relation.super_type))
    end

  when relation.super_type.is_a?(AST::Types::Name::Interface)
    Expand(relation) do
      check_interface(
        relation.map {|type|
          builder.shape(
            type,
            Interface::Builder::Config.new(self_type: type, variable_bounds: variable_upper_bounds)
          )&.public_shape() or return Failure(relation, Result::Failure::UnknownPairError.new(relation: relation))
        }
      )
    end

  when relation.sub_type.is_a?(AST::Types::Name::Base) && relation.super_type.is_a?(AST::Types::Name::Base)
    if relation.sub_type.name == relation.super_type.name && relation.sub_type.class == relation.super_type.class
      if arg_type?(relation.sub_type) && arg_type?(relation.super_type)
        check_type_arg(_ = relation)
      else
        Success(relation)
      end
    else
      possible_sub_types =
        case relation.sub_type
        when AST::Types::Name::Instance
          instance_super_types(relation.sub_type.name, args: relation.sub_type.args)
        when AST::Types::Name::Singleton
          singleton_super_types(relation.sub_type.name)
        else
          [] #: Array[super_type]
        end

      unless possible_sub_types.empty?
        Any(relation) do |result|
          possible_sub_types.each do |sub_type|
            result.add(Relation.new(sub_type: sub_type, super_type: relation.super_type)) do |rel|
              check_type(rel)
            end
          end
        end
      else
        Failure(relation, Result::Failure::UnknownPairError.new(relation: relation))
      end
    end

  when relation.sub_type.is_a?(AST::Types::Proc) && relation.super_type.is_a?(AST::Types::Proc)
    yield_self do
      name = :__proc__

      sub_type = relation.sub_type
      super_type = relation.super_type

      All(relation) do |result|
        result.add(Relation(sub_type.type, super_type.type)) do |rel|
          check_function(name, rel)
        end

        result.add_result check_self_type_binding(relation, sub_type.self_type, super_type.self_type)

        result.add(Relation(sub_type.block, super_type.block)) do |rel|
          case ret = expand_block_given(name, rel)
          when Relation
            All(ret) do |result|
              result.add_result check_self_type_binding(ret, ret.super_type.self_type, ret.sub_type.self_type)
              result.add(ret.map {|b| b.type }) {|r| check_function(name, r.flip) }
            end
          when Result::Base
            ret
          when true
            nil
          end
        end
      end
    end

  when relation.sub_type.is_a?(AST::Types::Tuple) && relation.super_type.is_a?(AST::Types::Tuple)
    if relation.sub_type.types.size == relation.super_type.types.size
      pairs = relation.sub_type.types.take(relation.super_type.types.size).zip(relation.super_type.types)

      All(relation) do |result|
        pairs.each do |t1, t2|
          t2 or raise
          result.add(Relation.new(sub_type: t1, super_type: t2)) do |rel|
            check_type(rel)
          end
        end
      end
    else
      Failure(relation, Result::Failure::UnknownPairError.new(relation: relation))
    end

  when relation.sub_type.is_a?(AST::Types::Tuple) && (super_type = AST::Builtin::Array.instance_type?(relation.super_type))
    Expand(relation) do
      tuple_element_type =
        AST::Types::Union.build(
          types: relation.sub_type.types
        )

      check_type(Relation.new(sub_type: tuple_element_type, super_type: super_type.args.fetch(0)))
    end

  when relation.sub_type.is_a?(AST::Types::Tuple)
    Any(relation) do |result|
      # Check by converting the tuple to array
      tuple_element_type = AST::Types::Union.build(types: relation.sub_type.types)
      array_type = AST::Builtin::Array.instance_type(tuple_element_type)
      result.add(Relation.new(sub_type: array_type, super_type: relation.super_type)) do
        check_type(_1)
      end

      # Check by shapes
      shape_relation = relation.map {|type|
        # @type break: nil
        builder.shape(
          type, Interface::Builder::Config.new(self_type: type, variable_bounds: variable_upper_bounds)
        )&.public_shape or break
      }
      if shape_relation
        result.add(shape_relation) { check_interface(_1) }
      end
    end

  when relation.sub_type.is_a?(AST::Types::Record) && relation.super_type.is_a?(AST::Types::Record)
    All(relation) do |result|
      unchecked_keys = Set.new(relation.sub_type.elements.each_key)

      relation.super_type.elements.each_key do |key|
        super_element_type = relation.super_type.elements.fetch(key) #: AST::Types::t
        sub_element_type = relation.sub_type.elements.fetch(key, nil) #: AST::Types::t?

        if relation.super_type.required?(key)
          rel = Relation.new(sub_type: sub_element_type || AST::Builtin.nil_type, super_type: super_element_type)
          result.add(rel) { check_type(rel) }
        else
          # If the key is optional, it's okay to not have the key
          if sub_element_type
            rel = Relation.new(sub_type: sub_element_type, super_type: super_element_type)
            result.add(rel) { check_type(rel) }
          end
        end

        unchecked_keys.delete(key)
      end

      unless unchecked_keys.empty?
        return Failure(relation, Result::Failure::UnknownPairError.new(relation: relation))
      end
    end

  when relation.sub_type.is_a?(AST::Types::Record)
    Any(relation) do |result|
      # Check by converting the record to hash
      key_type = AST::Types::Union.build(types: relation.sub_type.elements.each_key.map {|key| AST::Types::Literal.new(value: key) })
      value_type = AST::Types::Union.build(types: relation.sub_type.elements.each_value.map {|key| key })
      hash_type = AST::Builtin::Hash.instance_type(key_type, value_type)
      result.add(Relation.new(sub_type: hash_type, super_type: relation.super_type)) { check_type(_1) }

      # Check by the shapes
      shape_relation = relation.map do |type|
        # @type break: nil
        builder.shape(
          type,
          Interface::Builder::Config.new(self_type: type, variable_bounds: variable_upper_bounds)
        )&.public_shape or break
      end
      if shape_relation
        result.add(shape_relation) { check_interface(_1) }
      end
    end

  when relation.sub_type.is_a?(AST::Types::Proc) && AST::Builtin::Proc.instance_type?(relation.super_type)
    Success(relation)

  when relation.super_type.is_a?(AST::Types::Literal)
    case
    when relation.super_type.value == true && AST::Builtin::TrueClass.instance_type?(relation.sub_type)
      Success(relation)
    when relation.super_type.value == false && AST::Builtin::FalseClass.instance_type?(relation.sub_type)
      Success(relation)
    else
      Failure(relation, Result::Failure::UnknownPairError.new(relation: relation))
    end

  when relation.super_type.is_a?(AST::Types::Nil) && AST::Builtin::NilClass.instance_type?(relation.sub_type)
    # NilClass <: nil
    Success(relation)

  when relation.sub_type.is_a?(AST::Types::Literal)
    Expand(relation) do
      check_type(Relation.new(sub_type: relation.sub_type.back_type, super_type: relation.super_type))
    end
  else
    Failure(relation, Result::Failure::UnknownPairError.new(relation: relation))
  end
end

#check_type_arg(relation) ⇒ Object



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
# File 'lib/steep/subtyping/check.rb', line 638

def check_type_arg(relation)
  sub_args = relation.sub_type.args
  sup_args = relation.super_type.args

  sup_def = definition_for_type(relation.super_type)
  sup_params = sup_def.type_params_decl

  All(relation) do |result|
    sub_args.zip(sup_args, sup_params.each).each do |sub_arg, sup_arg, sup_param|
      case sup_param.variance
      when :covariant
        result.add(Relation.new(sub_type: sub_arg, super_type: sup_arg)) do |rel|
          check_type(rel)
        end
      when :contravariant
        result.add(Relation.new(sub_type: sup_arg, super_type: sub_arg)) do |rel|
          check_type(rel)
        end
      when :invariant
        rel = Relation.new(sub_type: sub_arg, super_type: sup_arg)
        result.add(rel, rel.flip) do |rel|
          check_type(rel)
        end
      end
    end
  end
end

#class_typeObject



87
88
89
# File 'lib/steep/subtyping/check.rb', line 87

def class_type
  @class_type || AST::Types::Class.instance
end

#constraintsObject



91
92
93
# File 'lib/steep/subtyping/check.rb', line 91

def constraints
  @constraints || raise
end

#definition_for_type(type) ⇒ Object



616
617
618
619
620
621
622
623
624
625
626
627
# File 'lib/steep/subtyping/check.rb', line 616

def definition_for_type(type)
  case type
  when AST::Types::Name::Instance
    factory.definition_builder.build_instance(type.name)
  when AST::Types::Name::Singleton
    factory.definition_builder.build_singleton(type.name)
  when AST::Types::Name::Interface
    factory.definition_builder.build_interface(type.name)
  else
    raise
  end
end

#each_ancestor(ancestors, &block) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/steep/subtyping/check.rb', line 95

def each_ancestor(ancestors, &block)
  if block
    if ancestors.super_class
      yield ancestors.super_class
    end
    ancestors.each_included_module(&block)
    ancestors.each_included_interface(&block)
    ancestors.each_prepended_module(&block)
    ancestors.each_extended_module(&block)
    ancestors.each_extended_interface(&block)
  else
    enum_for :each_ancestor, ancestors
  end
end

#expand_alias(type, &block) ⇒ Object



1089
1090
1091
# File 'lib/steep/subtyping/check.rb', line 1089

def expand_alias(type, &block)
  factory.expand_alias(type, &block)
end

#expand_block_given(name, relation, &block) ⇒ Object



892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
# File 'lib/steep/subtyping/check.rb', line 892

def expand_block_given(name, relation, &block)
  relation.block!

  sub_block, super_block = relation

  case
  when !super_block && !sub_block
    true
  when super_block && sub_block && super_block.optional? == sub_block.optional?
    Relation.new(sub_type: sub_block, super_type: super_block)
  when sub_block&.optional?
    true
  else
    Failure(relation, Result::Failure::BlockMismatchError.new(name: name))
  end
end

#factoryObject



15
16
17
# File 'lib/steep/subtyping/check.rb', line 15

def factory
  builder.factory
end

#false_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


240
241
242
243
244
245
246
247
# File 'lib/steep/subtyping/check.rb', line 240

def false_type?(type)
  case type
  when AST::Types::Literal
    type.value == false
  else
    AST::Builtin::FalseClass.instance_type?(type) ? true : false
  end
end

#hole_path(type, path = []) ⇒ Object

Returns the shortest type paths for one of the unknown type variables. Returns nil if there is no path.



1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
# File 'lib/steep/subtyping/check.rb', line 1095

def hole_path(type, path = [])
  case type
  when AST::Types::Var
    if constraints.unknown?(type.name)
      [type]
    else
      nil
    end
  else
    paths = type.each_child.map do |ty|
      hole_path(ty, path)&.unshift(ty)
    end
    paths.compact.min_by(&:size)
  end
end

#instance_super_types(type_name, args:) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/steep/subtyping/check.rb', line 110

def instance_super_types(type_name, args:)
  ancestors = factory.definition_builder.ancestor_builder.one_instance_ancestors(type_name)

  subst = unless args.empty?
            args_ = args.map {|type| factory.type_1(type) }
            params = ancestors.params or raise
            RBS::Substitution.build(params, args_)
          end

  each_ancestor(ancestors).map do |ancestor|
    name = ancestor.name

    case ancestor
    when RBS::Definition::Ancestor::Instance
      args = ancestor.args.map do |type|
        type = type.sub(subst) if subst
        factory.type(type)
      end

      if ancestor.name.class?
        AST::Types::Name::Instance.new(
          name: name,
          args: args
        )
      else
        AST::Types::Name::Interface.new(
          name: name,
          args: args
        )
      end
    when RBS::Definition::Ancestor::Singleton
      AST::Types::Name::Singleton.new(
        name: name
      )
    end
  end
end

#instance_typeObject



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

def instance_type
  @instance_type || AST::Types::Instance.instance
end

#match_method_type_fails?(name, type1, type2) ⇒ Boolean

Returns:

  • (Boolean)


970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
# File 'lib/steep/subtyping/check.rb', line 970

def match_method_type_fails?(name, type1, type2)
  if type1.type.params && type2.type.params
    match_params(name, Relation(type1.type.params, type2.type.params)).tap do |param_pairs|
      return param_pairs unless param_pairs.is_a?(Array)
    end
  end

  case result = expand_block_given(name, Relation(type1.block, type2.block))
  when Result::Base
    return result
  when Relation
    type1.block or raise
    type2.block or raise

    if type1.block.type.params && type2.block.type.params
      match_params(name, result.map {|m| _ = m.type.params }).tap do |param_pairs|
        return param_pairs unless param_pairs.is_a?(Array)
      end
    end
  end

  nil
end

#match_params(name, relation) ⇒ Object



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
# File 'lib/steep/subtyping/check.rb', line 994

def match_params(name, relation)
  relation.params!

  sub_params, super_params = relation

  pairs = [] #: Array[[AST::Types::t, AST::Types::t]]

  sub_flat = sub_params.flat_unnamed_params
  sup_flat = super_params.flat_unnamed_params

  failure = Failure(relation, Result::Failure::ParameterMismatchError.new(name: name))

  case
  when super_params.rest
    return failure unless sub_params.rest

    while sub_flat.size > 0
      sub_type = sub_flat.shift or raise
      sup_type = sup_flat.shift

      if sup_type
        pairs << [sub_type.last, sup_type.last]
      else
        pairs << [sub_type.last, super_params.rest]
      end
    end

    if sub_params.rest
      pairs << [sub_params.rest, super_params.rest]
    end

  when sub_params.rest
    while sub_flat.size > 0
      sub_type = sub_flat.shift or raise
      sup_type = sup_flat.shift

      if sup_type
        pairs << [sub_type.last, sup_type.last]
      else
        break
      end
    end

    if sub_params.rest && !sup_flat.empty?
      sup_flat.each do |sup_type|
        pairs << [sub_params.rest, sup_type.last]
      end
    end
  when sub_params.required.size + sub_params.optional.size >= super_params.required.size + super_params.optional.size
    while sub_flat.size > 0
      sub_type = sub_flat.shift or raise
      sup_type = sup_flat.shift

      if sup_type
        pairs << [sub_type.last, sup_type.last]
      else
        if sub_type.first == :required
          return failure
        else
          break
        end
      end
    end
  else
    return failure
  end

  sub_flat_kws = sub_params.flat_keywords
  sup_flat_kws = super_params.flat_keywords

  sup_flat_kws.each do |name, _|
    if sub_flat_kws.key?(name)
      pairs << [sub_flat_kws.fetch(name), sup_flat_kws.fetch(name)]
    else
      if sub_params.rest_keywords
        pairs << [sub_params.rest_keywords, sup_flat_kws.fetch(name)]
      else
        return failure
      end
    end
  end

  sub_params.required_keywords.each do |name, _|
    unless super_params.required_keywords.key?(name)
      return failure
    end
  end

  if sub_params.rest_keywords && super_params.rest_keywords
    pairs << [sub_params.rest_keywords, super_params.rest_keywords]
  end

  pairs
end

#push_assumption(relation) ⇒ Object



35
36
37
38
39
40
# File 'lib/steep/subtyping/check.rb', line 35

def push_assumption(relation)
  assumptions << relation
  yield
ensure
  assumptions.delete(relation)
end

#push_variable_bounds(params) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/steep/subtyping/check.rb', line 42

def push_variable_bounds(params)
  case params
  when Array
    b = params.each.with_object({}) do |param, hash| #$ Hash[Symbol, AST::Types::t?]
      hash[param.name] = param.upper_bound
    end
  when Hash
    b = params
  end

  @bounds.push(b)
  yield

ensure
  @bounds.pop
end

#Relation(sub, sup) ⇒ Object



966
967
968
# File 'lib/steep/subtyping/check.rb', line 966

def Relation(sub, sup)
  Relation.new(sub_type: sub, super_type: sup)
end

#same_type?(relation) ⇒ Boolean

Returns:

  • (Boolean)


666
667
668
669
670
671
672
# File 'lib/steep/subtyping/check.rb', line 666

def same_type?(relation)
  if assumptions.include?(relation) && assumptions.include?(relation.flip)
    return true
  end

  builder.factory.normalize_type(relation.sub_type) == builder.factory.normalize_type(relation.super_type)
end

#self_typeObject



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

def self_type
  @self_type || raise
end

#singleton_super_types(type_name) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/steep/subtyping/check.rb', line 148

def singleton_super_types(type_name)
  ancestors = factory.definition_builder.ancestor_builder.one_singleton_ancestors(type_name)

  ancestors.each_ancestor.map do |ancestor|
    name = ancestor.name

    case ancestor
    when RBS::Definition::Ancestor::Instance
      args = ancestor.args.map do |type|
        factory.type(type)
      end

      if ancestor.name.class?
        AST::Types::Name::Instance.new(
          name: name,
          args: args
        )
      else
        AST::Types::Name::Interface.new(
          name: name,
          args: args
        )
      end
    when RBS::Definition::Ancestor::Singleton
      AST::Types::Name::Singleton.new(
        name: name
      )
    end
  end
end

#true_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


231
232
233
234
235
236
237
238
# File 'lib/steep/subtyping/check.rb', line 231

def true_type?(type)
  case type
  when AST::Types::Literal
    type.value == true
  else
    AST::Builtin::TrueClass.instance_type?(type) ? true : false
  end
end

#variable_upper_bound(name) ⇒ Object



59
60
61
62
63
64
65
66
67
# File 'lib/steep/subtyping/check.rb', line 59

def variable_upper_bound(name)
  @bounds.reverse_each do |hash|
    if hash.key?(name)
      return hash.fetch(name)
    end
  end

  nil
end

#variable_upper_boundsObject



69
70
71
72
73
# File 'lib/steep/subtyping/check.rb', line 69

def variable_upper_bounds
  @bounds.each_with_object({}) do |bounds, hash| #$ Hash[Symbol, AST::Types::t?]
    hash.merge!(bounds)
  end
end

#with_context(self_type:, instance_type:, class_type:, constraints:) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/steep/subtyping/check.rb', line 19

def with_context(self_type:, instance_type:, class_type:, constraints:)
  @self_type = self_type
  @instance_type = instance_type
  @class_type = class_type
  @constraints = constraints
  @assumptions = Set[]

  yield
ensure
  @self_type = nil
  @instance_type = nil
  @class_type = nil
  @constraints = nil
  @assumptions = nil
end