Skip to content

Commit

Permalink
Fix stackoverflow error in simplifyExpr (#165)
Browse files Browse the repository at this point in the history
This was caused by trying to reorder multiple arguments back and forth
  • Loading branch information
laurentlb authored Nov 12, 2022
1 parent e84c45f commit 2273d84
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/rewriter.fs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ let private inlineFn (declArgs:Decl list) passedArgs bodyExpr =

/// Expression that doesn't need parentheses around it.
let (|NoParen|_|) = function
| Int _ | Float _ | Dot _ | Var _ | FunCall _ | Subscript _ as x -> Some x
| Int _ | Float _ | Dot _ | Var _ | FunCall (Var _, _) | Subscript _ as x -> Some x
| _ -> None

let rec private simplifyExpr (didInline: bool ref) env = function
Expand Down Expand Up @@ -108,7 +108,7 @@ let rec private simplifyExpr (didInline: bool ref) env = function
| FunCall(Op "-", [x; Int (i, s)]) when i < 0 ->
FunCall(Op "+", [x; Int (-i, s)]) |> env.fExpr env

// Swap operands to get rid of parenthese
// Swap operands to get rid of parentheses
// x*(y*z) -> y*z*x
| FunCall(Op "*", [NoParen x; FunCall(Op "*", [y; z])]) ->
FunCall(Op "*", [FunCall(Op "*", [y; z]); x]) |> env.fExpr env
Expand All @@ -117,10 +117,10 @@ let rec private simplifyExpr (didInline: bool ref) env = function
| FunCall(Op "+", [NoParen x; FunCall(Op ("+"|"-") as op, [y; z])]) ->
FunCall(Op "+", [FunCall(op, [y; z]); x]) |> env.fExpr env
// x-(y+z) -> x-y-z
| FunCall(Op "-", [NoParen x; FunCall(Op "+", [y; z])]) ->
| FunCall(Op "-", [x; FunCall(Op "+", [y; z])]) ->
FunCall(Op "-", [FunCall(Op "-", [x; y]); z]) |> env.fExpr env
// x-(y-z) -> x-y+z
| FunCall(Op "-", [NoParen x; FunCall(Op "-", [y; z])]) ->
| FunCall(Op "-", [x; FunCall(Op "-", [y; z])]) ->
FunCall(Op "+", [FunCall(Op "-", [x; y]); z]) |> env.fExpr env

// Boolean simplifications (let's ignore the suffix)
Expand Down
4 changes: 4 additions & 0 deletions tests/unit/operators.expected
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,8 @@
"{"
"int d=b*c*a;"
"return a-b+1-d+c;"
"}"
"int other(int a,int b,int c,int d)"
"{"
"return a*b*(c*d)*(a*b);"
"}",
4 changes: 4 additions & 0 deletions tests/unit/operators.frag
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,7 @@ int no_parens2(int a, int b, int c) {
int d = a*(b*c);
return a - (b - 1) - (d - c);
}

int other(int a, int b, int c, int d) {
return (a*b)*(c*d)*(a*b);
}

0 comments on commit 2273d84

Please sign in to comment.