class RuboCop::Cop::Style::YodaExpression


1 | x
# good
CONST + 1
z & 1
y * 10
x + 1
60 * 24
# good
1 + CONST
1 & z
10 * y
1 + x
# bad
@example SupportedOperators: [‘*’, ‘+’, ‘&”]
have the same result if reversed.
differently on different classes, and are not guaranteed to
This cop is unsafe because binary operators can be defined
@safety
—-
config.server_port = 9000 + ENV.to_i
—-
[source,ruby]

This cop is disabled by default to respect user intentions such as:
This cop complements `Style/YodaCondition` cop, which has a similar purpose.
and `^` operators) where the order of expression is reversed, eg. `1 + x`.
Forbids Yoda expressions, i.e. binary operations (using `*`, `+`, `&`, `|`,

def constant_portion?(node)

def constant_portion?(node)
  node.numeric_type? || node.const_type?
end

def offended_ancestor?(node)

def offended_ancestor?(node)
  node.each_ancestor(:send).any? { |ancestor| @offended_nodes&.include?(ancestor) }
end

def offended_nodes

def offended_nodes
  @offended_nodes ||= Set.new.compare_by_identity
end

def on_new_investigation

def on_new_investigation
  @offended_nodes = nil
end

def on_send(node)

def on_send(node)
  return unless supported_operators.include?(node.method_name.to_s)
  lhs = node.receiver
  rhs = node.first_argument
  return unless yoda_expression_constant?(lhs, rhs)
  return if offended_ancestor?(node)
  message = format(MSG, source: rhs.source)
  add_offense(node, message: message) do |corrector|
    corrector.swap(lhs, rhs)
  end
  offended_nodes.add(node)
end

def supported_operators

def supported_operators
  Array(cop_config['SupportedOperators'])
end

def yoda_expression_constant?(lhs, rhs)

def yoda_expression_constant?(lhs, rhs)
  constant_portion?(lhs) && !constant_portion?(rhs)
end