Skip to content

Commit

Permalink
Merge pull request JuliaLang#8461 from JuliaLang/teh/cartesian_noeval
Browse files Browse the repository at this point in the history
Resolve many arithmetic and conditional operations without eval
  • Loading branch information
timholy committed Sep 24, 2014
2 parents a449f9e + ed1f136 commit 050dc17
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions base/cartesian.jl
Original file line number Diff line number Diff line change
Expand Up @@ -449,14 +449,37 @@ function poplinenum(ex::Expr)
ex
end

## Resolve expressions at parsing time ##

const exprresolve_arith_dict = (Symbol=>Function)[:+ => +,
:- => -, :* => *, :/ => /, :^ => ^, :div => div]
const exprresolve_cond_dict = (Symbol=>Function)[:(==) => ==,
:(<) => <, :(>) => >, :(<=) => <=, :(>=) => >=]

function exprresolve_arith(ex::Expr)
if ex.head == :call && haskey(exprresolve_arith_dict, ex.args[1]) && all([isa(ex.args[i], Number) for i = 2:length(ex.args)])
return true, exprresolve_arith_dict[ex.args[1]](ex.args[2:end]...)
end
false, 0
end

exprresolve_conditional(b::Bool) = true, b
function exprresolve_conditional(ex::Expr)
if ex.head == :comparison && isa(ex.args[1], Number) && isa(ex.args[3], Number)
return true, exprresolve_cond_dict[ex.args[2]](ex.args[1], ex.args[3])
end
false, false
end

exprresolve(arg) = arg
function exprresolve(ex::Expr)
for i = 1:length(ex.args)
ex.args[i] = exprresolve(ex.args[i])
end
# Handle simple arithmetic
if ex.head == :call && in(ex.args[1], (:+, :-, :*, :/)) && all([isa(ex.args[i], Number) for i = 2:length(ex.args)])
return eval(ex)
can_eval, result = exprresolve_arith(ex)
if can_eval
return result
elseif ex.head == :call && (ex.args[1] == :+ || ex.args[1] == :-) && length(ex.args) == 3 && ex.args[3] == 0
# simplify x+0 and x-0
return ex.args[2]
Expand All @@ -472,10 +495,9 @@ function exprresolve(ex::Expr)
end
# Resolve conditionals
if ex.head == :if
try
tf = eval(ex.args[1])
can_eval, tf = exprresolve_conditional(ex.args[1])
if can_eval
ex = tf?ex.args[2]:ex.args[3]
catch
end
end
ex
Expand Down

0 comments on commit 050dc17

Please sign in to comment.