提交 32a7bc62 编写于 作者: J Justin Collins

Special case `if [...].include? x`

if the array is all literals and the condition is true, then `x` must
also be one of those literals.
上级 2994bb51
......@@ -465,6 +465,19 @@ class Brakeman::AliasProcessor < Brakeman::SexpProcessor
exp
end
# Check if exp is a call to Array#include? on an array literal
# that contains all literal values. For example:
#
# [1, 2, "a"].include? x
#
def array_include_all_literals? exp
call? exp and
exp.method == :include? and
node_type? exp.target, :array and
exp.target.length > 1 and
exp.target.all? { |e| e.is_a? Symbol or node_type? e, :lit, :str }
end
#Sets @inside_if = true
def process_if exp
if @ignore_ifs.nil?
......@@ -498,7 +511,17 @@ class Brakeman::AliasProcessor < Brakeman::SexpProcessor
scope do
@branch_env = env.current
branch_index = 2 + i # s(:if, condition, then_branch, else_branch)
exp[branch_index] = process_if_branch branch
if i == 0 and array_include_all_literals? condition
# If the condition is ["a", "b"].include? x
# set x to "a" inside the true branch
var = condition.first_arg
previous_value = env.current[var]
env.current[var] = condition.target[1]
exp[branch_index] = process_if_branch branch
env.current[var] = previous_value
else
exp[branch_index] = process_if_branch branch
end
branch_scopes << env.current
@branch_env = nil
end
......
......@@ -12,4 +12,15 @@ class User < ActiveRecord::Base
def symbol_stuff
self.where(User.table_name.to_sym)
end
scope :sorted_by, ->(field, asc) {
asc = ['desc', 'asc'].include?(asc) ? asc : 'asc'
ordering = if field == 'extension'
"substring_index(#{table_name}.data_file_name, '.', -1) #{asc}"
elsif SORTABLE_COLUMNS.include?(field)
{ field.to_sym => asc.to_sym }
end
order(ordering) # should not warn about `asc` interpolation
}
end
......@@ -640,4 +640,30 @@ class AliasProcessorTests < Test::Unit::TestCase
x
INPUT
end
def test_branch_array_include
assert_alias 'x', <<-INPUT
if [1,2,3].include? x
stuff
end
x
INPUT
assert_output <<-INPUT, <<-OUTPUT
if [1,2,3].include? x
y = x + 2
p y
end
x
INPUT
if [1,2,3].include? x
y = 3
p 3
end
x
OUTPUT
end
end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册