From 64fe02892bebbff158cd6e96899e6365b9a5cbe9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20=C5=A0ebek?= <44544735+xsebek@users.noreply.github.com> Date: Sat, 26 Aug 2023 19:18:13 +0200 Subject: [PATCH] Fix lambda precedence (#1470) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - give lambdas lower precedence (9) then application (10) - closes #1468 Before (with #1459): ``` ❯ cabal run swarm -O0 -- format <(echo '\\m. case m (\\x. x + 1) (\\y. y * 2)') \m. case m \x. x + 1 \y. y * 2 ``` After: ``` ❯ cabal run swarm -O0 -- format <(echo '\\m. case m (\\x. x + 1) (\\y. y * 2)') \m. case m (\x. x + 1) (\y. y * 2) ``` --- src/Swarm/Language/Pretty.hs | 4 +++- test/unit/TestPretty.hs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Swarm/Language/Pretty.hs b/src/Swarm/Language/Pretty.hs index 05bd3cc79..ddd510c59 100644 --- a/src/Swarm/Language/Pretty.hs +++ b/src/Swarm/Language/Pretty.hs @@ -188,7 +188,9 @@ instance PrettyPrec Term where prettyPrec _ (TVar s) = pretty s prettyPrec _ (TDelay _ t) = group . encloseWithIndent 2 lbrace rbrace $ ppr t prettyPrec _ t@TPair {} = prettyTuple t - prettyPrec _ t@(TLam {}) = prettyLambdas t + prettyPrec p t@(TLam {}) = + pparens (p > 9) $ + prettyLambdas t -- Special handling of infix operators - ((+) 2) 3 --> 2 + 3 prettyPrec p (TApp t@(TApp (TConst c) l) r) = let ci = constInfo c diff --git a/test/unit/TestPretty.hs b/test/unit/TestPretty.hs index 1c6fff5a7..5e21e58bb 100644 --- a/test/unit/TestPretty.hs +++ b/test/unit/TestPretty.hs @@ -95,6 +95,18 @@ testPrettyConst = ( equalPretty "1 : int" $ TAnnotate (TInt 1) (Forall [] TyInt) ) + , testCase + "lambda precedence (#1468)" + ( equalPretty "\\m. case m (\\x. x + 1) (\\y. y * 2)" $ + TLam + "m" + Nothing + ( TConst Case + :$: STerm (TVar "m") + :$: STerm (TLam "x" Nothing (mkOp' Add (TVar "x") (TInt 1))) + :$: STerm (TLam "y" Nothing (mkOp' Mul (TVar "y") (TInt 2))) + ) + ) ] where equalPretty :: String -> Term -> Assertion