From b8fb1e1bea569817352a1b1ff29a42fd9c749885 Mon Sep 17 00:00:00 2001 From: Eldritch Conundrum Date: Tue, 11 May 2021 19:49:38 +0200 Subject: [PATCH] Rewrite the full pi constant as acos(-1.) (#66) --- src/parse.fs | 1 + src/rewriter.fs | 5 +++++ tests/commands.txt | 4 ++++ tests/unit/pi.frag | 10 ++++++++++ tests/unit/pi.frag.expected | 1 + 5 files changed, 21 insertions(+) create mode 100644 tests/unit/pi.frag create mode 100644 tests/unit/pi.frag.expected diff --git a/src/parse.fs b/src/parse.fs index 692d6314..1f998943 100644 --- a/src/parse.fs +++ b/src/parse.fs @@ -59,6 +59,7 @@ module private ParseImpl = let anyNumber = let n = (hexa <|> octal <|> number) "number" + // number suffixes: float, long float, unsigned, long, half. FIXME: test the last two let suffix = ["f"; "F"; "LF"; "lf"; "u"; "U"; "l"; "L"; "h"; "H"] |> List.map str |> choice let suffix = suffix "suffix" diff --git a/src/rewriter.fs b/src/rewriter.fs index 2f40f1be..d7e727da 100644 --- a/src/rewriter.fs +++ b/src/rewriter.fs @@ -136,6 +136,11 @@ let rec private simplifyExpr env = function | Some (_, _, Some init) -> init | _ -> e + // pi is acos(-1), pi/2 is acos(0) + | Float(f, _) when f = 3.141592653589793 -> FunCall(Var "acos", [Float (-1., "")]) + | Float(f, _) when f = 6.283185307179586 -> FunCall(Op "*", [Float (2., ""); FunCall(Var "acos", [Float (-1., "")])]) + | Float(f, _) when f = 1.5707963267948966 -> FunCall(Var "acos", [Float (0., "")]) + | e -> e // Squeeze declarations: "float a=2.; float b;" => "float a=2.,b;" diff --git a/tests/commands.txt b/tests/commands.txt index 253d0dc3..1893ee77 100644 --- a/tests/commands.txt +++ b/tests/commands.txt @@ -26,3 +26,7 @@ -o tests/real/yx_long_way_from_home.frag.expected tests/real/yx_long_way_from_home.frag -o tests/real/oscars_chair.frag.expected tests/real/oscars_chair.frag -o tests/real/the_real_party_is_in_your_pocket.frag.expected tests/real/the_real_party_is_in_your_pocket.frag + +# Optimization tests + +--no-renaming --format text -o tests/unit/pi.frag.expected tests/unit/pi.frag diff --git a/tests/unit/pi.frag b/tests/unit/pi.frag new file mode 100644 index 00000000..01ca2aba --- /dev/null +++ b/tests/unit/pi.frag @@ -0,0 +1,10 @@ + +void main() { + double pi = 3.141592653589793; + double minus_pi = -3.141592653589793; + double tau = 6.283185307179586; + double minus_tau = -6.283185307179586; + double half_pi = 1.5707963267948966; + double minus_half_pi = -1.5707963267948966; + double precise_pi = 3.14159265358979323846264338327950288419716939937510; +} diff --git a/tests/unit/pi.frag.expected b/tests/unit/pi.frag.expected new file mode 100644 index 00000000..9d23827a --- /dev/null +++ b/tests/unit/pi.frag.expected @@ -0,0 +1 @@ +void main(){double pi=acos(-1.),minus_pi=-acos(-1.),tau=2.*acos(-1.),minus_tau=-(2.*acos(-1.)),half_pi=acos(0.),minus_half_pi=-acos(0.),precise_pi=acos(-1.);} \ No newline at end of file