Class: RuboCop::Cop::Gusto::Sorbet::PredicateBooleanReturn

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/gusto/sorbet/predicate_boolean_return.rb

Overview

Checks that predicate methods (methods ending with ?) in Sorbet-typed files return boolean values (T::Boolean or true/false literals).

This cop categorizes offenses into:

  • Methods returning nil
  • Methods returning other non-boolean values

A sig { void } predicate is left alone. void is an explicit declaration that the return value is not meaningful, which is how validator-style methods that only call errors.add are annotated.

It also provides an unsafe autocorrect feature to change the signature to returns(T::Boolean) and coerce the return value to a boolean.

Examples:

# bad (returns nil)
sig { returns(T.nilable(String)) }
def valid?
  nil
end

# bad (returns non-boolean)
sig { returns(String) }
def valid?
  'yes'
end

# good
sig { returns(T::Boolean) }
def valid?
  true
end

# good (also acceptable)
sig { returns(T.any(TrueClass, FalseClass)) }
def valid?
  true
end

# good (void declares the return value meaningless)
sig { void }
def valid_state?
  errors.add(:state, 'is invalid') unless state_ok?
end

Constant Summary collapse

MSG_RETURNS_NIL =
"Predicate method `%{method}` may return nil instead of boolean."
MSG_RETURNS_NON_BOOLEAN =
"Predicate method `%{method}` returns %{type} instead of boolean."
TYPED_SIGIL =
/\A\s*#\s*typed:\s*(true|strict|strong)\b/
NEGATION_PREFIX =

Starts with ! or !! but not != / !==

/\A!(!|[^=])/
MAX_SIBLING_LOOKBACK =

Guards find_sig_node's left-sibling walk against a pathological node list

10

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object Also known as: on_defs



68
69
70
71
72
73
# File 'lib/rubocop/cop/gusto/sorbet/predicate_boolean_return.rb', line 68

def on_def(node)
  return unless node.predicate_method?
  return unless typed_file?

  check_predicate_method(node)
end