Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/actions/spelling/allow.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ fst
GHC
Haskeline
hds
Hspec
HUnit
lexer
mempty
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/haskell.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
strategy:
matrix:
os:
- ubuntu-latest
- ubuntu-24.04
plan:
- {build: stack}

Expand Down
13 changes: 13 additions & 0 deletions package.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,19 @@ tests:
- filepath
- HUnit
- ansi-terminal
unit:
source-dirs: test
main: Spec.hs
ghc-options:
- -Wall
- -Werror
- -threaded
- -rtsopts
- -with-rtsopts=-N
dependencies:
- prolog
- HUnit
- hspec

benchmarks:
bench:
Expand Down
24 changes: 24 additions & 0 deletions prolog.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,30 @@ test-suite spec
, transformers >=0.2.2.0
default-language: Haskell2010

test-suite unit
type: exitcode-stdio-1.0
main-is: Spec.hs
other-modules:
PrettyPrintingSpec
Paths_prolog
hs-source-dirs:
test
ghc-options: -Wall -Wincomplete-uni-patterns -Werror=incomplete-uni-patterns -Werror=incomplete-patterns -Wall -Werror -threaded -rtsopts -with-rtsopts=-N
build-depends:
HUnit
, base ==4.*
, containers
, hspec
, mtl >=2.0.1.0
, parsec >=3.1.1
, pipes
, prolog
, syb >=0.3
, template-haskell
, th-lift >=0.5.3
, transformers >=0.2.2.0
default-language: Haskell2010

benchmark bench
type: exitcode-stdio-1.0
main-is: Main.hs
Expand Down
6 changes: 6 additions & 0 deletions src/Prolog.hs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ module Prolog (
runQueryN',
Signature (..),
termSignature,
prettifyVariableName,
prettifyTerm,
prettifyClause,
)
where

Expand Down Expand Up @@ -76,6 +79,9 @@ import Syntax (
Term (..),
VariableName (..),
cut,
prettifyClause,
prettifyTerm,
prettifyVariableName,
rhs,
var,
)
Expand Down
100 changes: 69 additions & 31 deletions src/Syntax.hs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#if !MIN_VERSION_base(4,18,0)
{-# LANGUAGE DerivingStrategies #-}
#endif
{-# LANGUAGE RecordWildCards #-}

module Syntax (
Term (..),
Expand All @@ -27,12 +28,15 @@ module Syntax (
hierarchy,
Operator (..),
Assoc (..),
prettifyVariableName,
prettifyTerm,
prettifyClause,
)
where

import Data.Char (digitToInt)
import Data.Generics (Data (..))
import Data.List (intercalate, uncons, unsnoc)
import Data.List (intercalate, uncons)
#if !MIN_VERSION_base(4,18,0)
import Data.Typeable (Typeable)
#endif
Expand All @@ -44,7 +48,7 @@ data Term
= Struct Atom [Term]
| Var VariableName
| Cut Int
deriving (Data, Eq, Generic)
deriving (Data, Eq, Generic, Show)
#if !MIN_VERSION_base(4,18,0)
deriving Typeable
#endif
Expand All @@ -63,14 +67,29 @@ data Clause
deriving Typeable
#endif

instance Show Clause where
show c =
name
++ " {predicateName = "
++ show (predicateName c)
++ ", predicateArgs = "
++ show (predicateArgs c)
++ ", "
++ lastArg
++ "}"
where
(name, lastArg) = case c of
Clause {} -> ("Clause", "rhs_ = " ++ show (rhs_ c))
ClauseFn {} -> ("ClauseFn", "fn = <function>")

rhs :: Clause -> [Term] -> [Goal]
rhs (Clause _ _ rhs') = const rhs'
rhs (ClauseFn _ _ fn') = fn'

data VariableName
= VariableName Int String
| Wildcard (Maybe Int)
deriving (Data, Eq, Generic, Ord)
deriving (Data, Eq, Generic, Ord, Show)
#if !MIN_VERSION_base(4,18,0)
deriving Typeable
#endif
Expand Down Expand Up @@ -108,20 +127,23 @@ compoundTerms :: Term -> Maybe (Int, Atom, [Term])
compoundTerms (Struct a ts) = Just (length ts, a, ts)
compoundTerms _ = Nothing

instance Show Term where
show = prettyPrint False 0
prettifyTerm :: Term -> String
prettifyTerm = prettyPrint False 0

prettyPrint :: Bool -> Int -> Term -> [Char]
prettyPrint True _ t@(Struct "," [_, _]) =
"(" ++ prettyPrint False 0 t ++ ")"
prettyPrint f n (Struct (flip lookup operatorTable -> Just (p, InfixOp assoc name)) [l, r]) =
parensIf (n >= p) $ prettyPrint f n_l l ++ spaced name ++ prettyPrint f n_r r
prettyPrint f n (Struct (flip lookup infixOperatorTable -> Just (p, InfixOp assoc name)) [l, r]) =
parensIf addParens $ prettyPrint f' n_l l ++ spaced name ++ prettyPrint f' n_r r
where
addParens = f && name == "," || n >= p
f' = not addParens && f
(n_l, n_r) = case assoc of
AssocLeft -> (p - 1, p)
AssocRight -> (p, p - 1)
prettyPrint f n (Struct (flip lookup operatorTable -> Just (p, PrefixOp name)) [r]) =
parensIf (n >= p) $ name ++ prettyPrint f p {- Non-associative -} r
prettyPrint f n (Struct (flip lookup prefixOperatorTable -> Just (p, PrefixOp name)) [r]) =
parensIf addParens $ name ++ prettyPrint f' p {- Non-associative -} r
where
addParens = n >= p
f' = not addParens && f
prettyPrint _ _ t@(Struct "." [_, _]) =
let (ts, rest) = g [] t
in -- case guard (isNil rest) >> sequence (map toChar ts) of
Expand All @@ -138,7 +160,7 @@ prettyPrint _ _ t@(Struct "." [_, _]) =
isNil _ = False
prettyPrint _ _ (Struct a []) = a
prettyPrint _ _ (Struct a ts) = a ++ "(" ++ intercalate ", " (map (prettyPrint True 0) ts) ++ ")"
prettyPrint _ _ (Var v) = show v
prettyPrint _ _ (Var v) = prettifyVariableName v
-- prettyPrint _ _ Wildcard = "_"
prettyPrint _ _ (Cut _) = "!"

Expand All @@ -147,11 +169,8 @@ prettyPrint _ _ (Cut _) = "!"

spaced :: [Char] -> [Char]
spaced s =
let
condPrefix = maybe True ((`notElem` ",;") . fst) $ uncons s
condPostfix = maybe False ((/= ';') . snd) $ unsnoc s
in
spaceIf condPrefix ++ s ++ spaceIf condPostfix
let condPrefix = maybe False ((`notElem` ",;") . fst) $ uncons s
in spaceIf condPrefix ++ s ++ " "

spaceIf :: Bool -> String
spaceIf True = " "
Expand All @@ -161,22 +180,34 @@ parensIf :: Bool -> String -> String
parensIf True s = "(" ++ s ++ ")"
parensIf False s = s

operatorTable :: [(String, (Int, Operator))]
operatorTable = concat $ zipWith (map . g) [1 ..] $ hierarchy False
where
g p op@(InfixOp _ name) = (name, (p, op))
g p op@(PrefixOp name) = (name, (p, op))
-- Split by arity so that an operator name used as both prefix and infix
-- (e.g. '-') matches the right rule: prefix '-' has precedence 10, infix '-' 5.
infixOperatorTable :: [(Atom, (Int, Operator))]
infixOperatorTable = concat $ zipWith opInfix [1 ..] (hierarchy True)

instance Show VariableName where
show (VariableName 0 v) = v
show (VariableName i v) = v ++ subscriptDigits i
show (Wildcard (Just i)) = "_" ++ show i
show (Wildcard Nothing) = "_"
prefixOperatorTable :: [(Atom, (Int, Operator))]
prefixOperatorTable = concat $ zipWith opPrefix [1 ..] (hierarchy True)

instance Show Clause where
show (Clause name args []) = show (Struct name args) ++ "."
show (Clause name args rhs') = show (Struct name args) ++ " :- " ++ intercalate ", " (map show rhs') ++ "."
show (ClauseFn name args _) = show (Struct name args) ++ " :- " ++ "<Haskell function>" ++ "."
opInfix :: Int -> [Operator] -> [(Atom, (Int, Operator))]
opInfix p ops = [(name, (p, op)) | op@(InfixOp _ name) <- ops]

opPrefix :: Int -> [Operator] -> [(Atom, (Int, Operator))]
opPrefix p ops = [(name, (p, op)) | op@(PrefixOp name) <- ops]

prettifyVariableName :: VariableName -> String
prettifyVariableName (VariableName 0 v) = v
prettifyVariableName (VariableName i v) = v ++ subscriptDigits i
prettifyVariableName (Wildcard (Just i)) = "_" ++ show i
prettifyVariableName (Wildcard Nothing) = "_"

prettifyClause :: Clause -> String
prettifyClause (Clause name args []) = prettifyTerm (Struct name args) ++ "."
prettifyClause (Clause name args rhs') =
prettifyTerm (Struct name args)
++ " :- "
++ prettyPrint False 0 (foldr1 conjunction (concatMap flattenConjunction rhs'))
++ "."
prettifyClause (ClauseFn name args _) = prettifyTerm (Struct name args) ++ " :- " ++ "<Haskell function>" ++ "."

foldrPl :: (Term -> a -> a) -> a -> Term -> a
foldrPl f k (Struct "." [h, t]) = f h (foldrPl f k t)
Expand All @@ -191,6 +222,13 @@ cons t1 t2 = Struct "." [t1, t2]
nil :: Term
nil = Struct "[]" []

conjunction :: Term -> Term -> Term
conjunction l r = Struct "," [l, r]

flattenConjunction :: Term -> [Term]
flattenConjunction (Struct "," [l, r]) = flattenConjunction l ++ flattenConjunction r
flattenConjunction t = [t]

data Operator
= PrefixOp String
| InfixOp Assoc String
Expand Down
72 changes: 72 additions & 0 deletions test/PrettyPrintingSpec.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
module PrettyPrintingSpec where

import Control.Monad (forM_)
import Language.Prolog (Clause (Clause), Term (Struct), consultString, prettifyClause)
import Test.HUnit (assertFailure)
import Test.Hspec (Spec, describe, it, shouldBe)

dis :: Term -> Term -> Term
dis l r = Struct ";" [l, r]

con :: Term -> Term -> Term
con l r = Struct "," [l, r]

a, b, c, d :: Term
a = Struct "a" []
b = Struct "b" []
c = Struct "c" []
d = Struct "d" []

preservations :: [(String, String)]
preservations =
[ ("p :- (a;b),c,d.", "p :- (a; b), c, d.")
, ("p :- a;b,c,d.", "p :- a; b, c, d.")
, ("p :- a;(b,c,d).", "p :- a; b, c, d.")
, ("p :- (a;(b,(c,d))).", "p :- a; b, c, d.")
, ("p :- a;b, (c, d).", "p :- a; b, c, d.")
, ("p :- (a, b); c.", "p :- a, b; c.")
, ("p :- a ; b ; c.", "p :- a; b; c.")
, ("p :- a, ! ; b ; c.", "p :- a, !; b; c.")
, ("p :- (a ; b) ; c.", "p :- (a; b); c.")
, ("p :- a, b, c.", "p :- a, b, c.")
, ("p :- \\+ a ; b.", "p :- \\+a; b.")
, ("p :- not(a) ; b.", "p :- not(a); b.")
, ("p :- \\+ (a, b).", "p :- \\+(a, b).")
, ("p :- not(a, b).", "p :- not(a, b).")
, ("p(X) :- X = [a, b, c].", "p(X) :- X = [a,b,c].")
, ("p(X) :- X = [a, b|c].", "p(X) :- X = [a,b|c].")
, ("p(X,Y,Z) :- X is Y + Z.", "p(X, Y, Z) :- X is Y + Z.")
, ("p(X,Y,Z) :- X is Y * Y + Z.", "p(X, Y, Z) :- X is Y * Y + Z.")
, ("p(X,Y,Z) :- X is Y * (Y + Z).", "p(X, Y, Z) :- X is Y * (Y + Z).")
, ("p(X) :- X =.. [Y, Z].", "p(X) :- X =.. [Y,Z].")
, ("p :- q(a, g(b, c)); h.", "p :- q(a, g(b, c)); h.")
, ("p(X) :- X = Y, g(Y).", "p(X) :- X = Y, g(Y).")
, ("p(X) :- (X = Y, Y = Z), g(Z).", "p(X) :- X = Y, Y = Z, g(Z).")
, ("p(X, Y) :- X is -Y.", "p(X, Y) :- X is -Y.")
, ("p(X, Y, Z) :- X is -Y - Z.", "p(X, Y, Z) :- X is -Y - Z.")
, ("p(X, Y, Z) :- X is -(Y - Z).", "p(X, Y, Z) :- X is -(Y - Z).")
]

expectations :: [(Clause, String)]
expectations =
[ -- a ; (b, (c, d))
(Clause "p" [] [dis a (con b (con c d))], "p :- a; b, c, d.")
, -- a ; (b, c)
(Clause "p" [] [dis a (con b c)], "p :- a; b, c.")
, -- (a, (b, c)) ; d
(Clause "p" [] [dis (con a (con b c)) d], "p :- a, b, c; d.")
]

spec :: Spec
spec = describe "pretty printing" $ do
describe "it should preserve semantics but remove redundant parentheses" $ do
forM_ preservations $ \(input, expected) -> do
it input $ case consultString input of
Left err -> assertFailure $ show err
Right [(n, args, goals)] -> prettifyClause (Clause n args goals) `shouldBe` expected
_ -> assertFailure "only one clause should be parsed"

describe "it should correctly print the given value" $ do
forM_ (zip [1 :: Int ..] expectations) $ \(i, (input, expected)) -> do
it ("case " ++ show i) $
prettifyClause input `shouldBe` expected
1 change: 1 addition & 0 deletions test/Spec.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
Loading