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, #to_s, tuple, type_parameter, untyped, void
Constructor Details
This class inherits a constructor from RBI::Type::Composite
Instance Method Details
#nilable? ⇒ Boolean
: -> bool
434 435 436 |
# File 'lib/rbi/type.rb', line 434 def nilable? @types.any? { |type| type.nilable? || (type.is_a?(Simple) && type.name == "NilClass") } end |
#normalize ⇒ Object
: -> Type
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 |
# File 'lib/rbi/type.rb', line 440 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
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 |
# File 'lib/rbi/type.rb', line 460 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
429 430 431 |
# File 'lib/rbi/type.rb', line 429 def to_rbi "T.any(#{@types.map(&:to_rbi).join(", ")})" end |