Class: RBI::Type::Any
Overview
A type that is union of multiple types like ‘T.any(String, Integer)`.
Instance Attribute Summary
Attributes inherited from Composite
Instance Method Summary collapse
-
#nilable? ⇒ Boolean
: -> bool.
-
#normalize ⇒ Object
: -> Type.
-
#simplify ⇒ Object
: -> Type.
-
#to_rbi ⇒ Object
: -> String.
Methods inherited from Composite
Methods inherited from RBI::Type
#==, all, any, anything, attached_class, boolean, class_of, #eql?, generic, #hash, #initialize, #nilable, nilable, #non_nilable, noreturn, parse_node, parse_string, proc, #rbs_string, self_type, shape, simple, t_class, t_module, #to_s, tuple, type_alias, type_parameter, untyped, void
Constructor Details
This class inherits a constructor from RBI::Type::Composite
Instance Method Details
#nilable? ⇒ Boolean
: -> bool
470 471 472 |
# File 'lib/rbi/type.rb', line 470 def nilable? @types.any? { |type| type.nilable? || (type.is_a?(Simple) && type.name == "NilClass") } end |
#normalize ⇒ Object
: -> Type
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
# File 'lib/rbi/type.rb', line 476 def normalize flattened = @types.flat_map do |type| type = type.normalize case type when Any type.types.map(&:normalize) else type end end.uniq if flattened.size == 1 flattened.first #: as !nil else Any.new(flattened) end end |
#simplify ⇒ Object
: -> Type
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 |
# File 'lib/rbi/type.rb', line 496 def simplify type = normalize return type.simplify unless type.is_a?(Any) types = type.types.map(&:simplify) return Untyped.new if types.any? { |type| type.is_a?(Untyped) } has_true_class = types.any? { |type| type.is_a?(Simple) && type.name == "TrueClass" } has_false_class = types.any? { |type| type.is_a?(Simple) && type.name == "FalseClass" } if has_true_class && has_false_class types = types.reject { |type| type.is_a?(Simple) && (type.name == "TrueClass" || type.name == "FalseClass") } types << Type.boolean end is_nilable = false #: bool types = types.filter_map do |type| case type when Simple if type.name == "NilClass" is_nilable = true nil else type end when Nilable is_nilable = true type.type else type end end.uniq final_type = if types.size == 1 types.first #: as !nil else Any.new(types) end if is_nilable return Nilable.new(final_type) end final_type end |
#to_rbi ⇒ Object
: -> String
465 466 467 |
# File 'lib/rbi/type.rb', line 465 def to_rbi "::T.any(#{@types.map(&:to_rbi).join(", ")})" end |