Skip to content

A peer-to-peer stack for code collaboration

Add colours to pretty printing of values. (#251)

James Haydon016604e9f113
diff --git a/exe/RadicleExe.hs b/exe/RadicleExe.hs
index 54c9f47..628b250 100644
--- a/exe/RadicleExe.hs
+++ b/exe/RadicleExe.hs
@@ -19,9 +19,9 @@ main = do
(result, _state) <- runLang bindings prog
case result of
Left (LangError _ Exit) -> pure ()
- Left e -> do putStrLn $ renderPrettyDef e
+ Left e -> do putStrLn $ renderAnsi e
exitWith (ExitFailure 1)
- Right v -> putStrLn $ renderPrettyDef v
+ Right v -> putStrLn $ renderAnsi v
else do
src <- readSource (sourceFile opts')
hist <- case histFile opts' of
diff --git a/src/Radicle.hs b/src/Radicle.hs
index ac1cdb0..66f8c4f 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -71,6 +71,7 @@ module Radicle
, renderPretty
, renderPrettyDef
, renderCompactPretty
+ , renderAnsi
-- ** Re-exports
, PageWidth(..)
, Pretty
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 8b2099e..ef5ded8 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -6,7 +6,7 @@ import Protolude hiding (TypeError, toList)
import qualified Data.Map as Map
import qualified Data.Text as T
-import Data.Text.Prettyprint.Doc (pretty)
+import Data.Text.Prettyprint.Doc (reAnnotate)
import Data.Text.Prettyprint.Doc.Render.Terminal (putDoc)
import qualified Data.Time as Time
import GHC.Exts (IsList(..))
@@ -57,7 +57,7 @@ repl histFile preFileName preCode bindings = do
$ void $ interpretMany preFileName preCode
case r of
Left (LangError _ Exit) -> pure ()
- Left e -> putDoc $ pretty e
+ Left e -> putDoc $ reAnnotate toAnsi $ prettyV e
Right () -> pure ()
completion :: Monad m => CompletionFunc m
@@ -82,7 +82,7 @@ replPrimFns = fromList $ allDocs $
, "Pretty-prints a value."
, \case
[x] -> do
- putStrS (renderPrettyDef x)
+ putStrS (renderAnsi x)
pure nil
xs -> throwErrorHere $ WrongNumberOfArgs "print!" 1 (length xs))
@@ -144,10 +144,10 @@ replPrimFns = fromList $ allDocs $
(\err -> case err of
LangError _ Exit -> pure (pure nil)
LangError _ (Impossible _) -> do
- putStrS (renderPrettyDef err)
+ putStrS (renderAnsi err)
throwError err
_ -> do
- putStrS (renderPrettyDef err)
+ putStrS (renderAnsi err)
put st
pure (loop action))
go = do
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index af2027a..c60d51c 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -7,8 +7,11 @@ import Protolude hiding (Type, TypeError, (<>))
import Data.Copointed (Copointed(..))
import qualified Data.Map as Map
import Data.Sequence (Seq(..))
+import qualified Data.Sequence as Seq
import qualified Data.Text as T
import Data.Text.Prettyprint.Doc
+import Data.Text.Prettyprint.Doc.Render.Terminal (Color(..), color)
+import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Term
import Data.Text.Prettyprint.Doc.Render.Text
import Text.Megaparsec.Error (parseErrorPretty)
import Text.Megaparsec.Pos (sourcePosPretty)
@@ -17,43 +20,48 @@ import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
import Radicle.Internal.Type
+class PrettyV a where
+ prettyV :: a -> Doc Type
+
-- | We can't just pretty print the pointer id since that would break
-- referential transparency, so instead we just label refs as '<ref>'
-instance Pretty Reference where
- pretty _ = angles "ref"
+instance PrettyV Reference where
+ prettyV _ = annotate TRef $ angles "ref"
instance Pretty Ident where
pretty (Ident i) = pretty i
-instance Pretty Type where
- pretty = pretty . typeToValue
+instance PrettyV Type where
+ prettyV = prettyV . typeToValue
-instance (Copointed t, Ann.Annotation t) => Pretty (Ann.Annotated t ValueF) where
- pretty v = case v of
+instance forall t. (Copointed t, Ann.Annotation t) => PrettyV (Ann.Annotated t ValueF) where
+ prettyV v = annotate (valType v) $ case v of
Atom i -> pretty i
Keyword i -> ":" <> pretty i
- Ref i -> pretty i
+ Ref i -> prettyV i
String t -> "\"" <> pretty (escapeStr t) <> "\""
Number (a :% b) -> pretty a <> if b == 1 then "" else "/" <> pretty b
Boolean True -> "#t"
Boolean False -> "#f"
List vs -> case vs of
[] -> "()"
- [v'] -> parens $ pretty v'
- _ -> parens $ hang 1 (sep $ pretty <$> vs)
+ [v'] -> parens $ prettyV v'
+ _ -> parens $ hang 1 (sep $ prettyV <$> vs)
Vec vs -> case vs of
Empty -> "[]"
- v' :<| Empty -> brackets $ pretty v'
- _ -> brackets . sep $ pretty <$> toList vs
+ v' :<| Empty -> brackets $ prettyV v'
+ _ -> brackets . sep $ prettyV <$> toList vs
PrimFn i -> pretty i
Dict mp -> braces . align $
- sep [ pretty k <+> pretty val
+ sep [ prettyV k <+> prettyV val
| (k, val) <- Map.toList mp ]
- Lambda ids vals _ -> parens $
- "fn" <+> align (sep
- [ brackets . sep $ pretty <$> ids
- , sep $ pretty <$> toList vals
- ])
+ Lambda ids vals _ ->
+ let args :: Ann.Annotated t ValueF = Vec $ Seq.fromList (Atom <$> ids)
+ in parens $
+ annotate TAtom "fn" <+>
+ align (sep [ prettyV args
+ , sep $ prettyV <$> toList vals
+ ])
where
-- We print string literals escaped just like Haskell does.
escapeStr = T.init . T.tail . show
@@ -62,22 +70,22 @@ instance Pretty Ann.SrcPos where
pretty (Ann.SrcPos pos) = pretty (sourcePosPretty pos)
pretty (Ann.InternalPos stack) = pretty stack
-instance Pretty r => Pretty (LangError r) where
- pretty (LangError stack err) = vsep $
- [pretty err, "Call stack:"] ++ map pretty (reverse stack)
+instance PrettyV r => PrettyV (LangError r) where
+ prettyV (LangError stack err) = vsep $
+ [prettyV err, "Call stack:"] ++ map pretty (reverse stack)
-instance Pretty r => Pretty (LangErrorData r) where
- pretty v = case v of
+instance PrettyV r => PrettyV (LangErrorData r) where
+ prettyV v = case v of
UnknownIdentifier i -> "Unknown identifier:" <+> pretty i
Impossible t -> "This cannot be!" <+> pretty t
TypeError fname i t val -> vsep
[ "Type error:" <+> pretty fname <+> "expects a value of type"
- <+> pretty t <+> "in the" <+> pretty (pos (i + 1)) <+> "argument."
- , "But got a" <+> pretty (valType val) <> ":"
- , indent 2 $ pretty val ]
+ <+> prettyV t <+> "in the" <+> pretty (pos (i + 1)) <+> "argument."
+ , "But got a" <+> prettyV (valType val) <> ":"
+ , indent 2 $ prettyV val ]
NonFunctionCalled val -> vsep
- [ "Value was invoked as a function, but it has type" <+> pretty (valType val) <> ":"
- , indent 2 $ pretty val ]
+ [ "Value was invoked as a function, but it has type" <+> prettyV (valType val) <> ":"
+ , indent 2 $ prettyV val ]
WrongNumberOfArgs t x y -> "Wrong number of args in" <+> pretty t
<+> "Expected:" <+> pretty x
<+> "Got:" <+> pretty y
@@ -86,13 +94,13 @@ instance Pretty r => Pretty (LangErrorData r) where
SpecialForm f t -> "Error using special form" <+> pretty f <> ":" <+> pretty t <> "."
ParseError t -> "Parser error:" <+> pretty (parseErrorPretty t)
Exit -> "Exit"
- ThrownError i val -> "Exception" <+> pretty i <+> pretty val
+ ThrownError i val -> "Exception" <+> pretty i <+> prettyV val
PatternMatchError e -> case e of
NoMatch -> "Pattern match(es) are non-exhaustive."
NoValue -> "The `match` special form must be given a value to match on."
BadBindings p -> "Faulty pattern function. Pattern functions must return\
\ `[:just b]` where `b` is a dict of new bindings (from\
- \ atoms to values), or `:nothing`:" <+> pretty p
+ \ atoms to values), or `:nothing`:" <+> prettyV p
where
pos :: Int -> Text
pos 1 = "1st"
@@ -107,8 +115,8 @@ instance Pretty r => Pretty (LangErrorData r) where
--
-- >>> renderCompactPretty (asValue (List [String "hi", String "there"]))
-- "(\"hi\"\n\"there\")"
-renderCompactPretty :: Pretty v => v -> Text
-renderCompactPretty = renderStrict . layoutCompact . pretty
+renderCompactPretty :: PrettyV v => v -> Text
+renderCompactPretty = renderStrict . layoutCompact . prettyV
-- | Render prettily into text, with specified width.
--
@@ -119,8 +127,8 @@ renderCompactPretty = renderStrict . layoutCompact . pretty
--
-- >>> renderPretty (AvailablePerLine 6 0.5) (asValue (List [String "hi", String "there"]))
-- "(\"hi\"\n \"there\")"
-renderPretty :: Pretty v => PageWidth -> v -> Text
-renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
+renderPretty :: PrettyV v => PageWidth -> v -> Text
+renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . prettyV
-- | 'renderPretty', but with default layout options (80 chars, 1.0 ribbon)
--
@@ -128,5 +136,23 @@ renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
--
-- >>> renderPrettyDef (asValue (List [String "hi", String "there"]))
-- "(\"hi\" \"there\")"
-renderPrettyDef :: Pretty v => v -> Text
-renderPrettyDef = renderStrict . layoutSmart defaultLayoutOptions . pretty
+renderPrettyDef :: PrettyV v => v -> Text
+renderPrettyDef = renderStrict . layoutSmart defaultLayoutOptions . prettyV
+
+toAnsi :: Type -> Term.AnsiStyle
+toAnsi = \case
+ TKeyword -> color Magenta
+ TString -> color Green
+ TNumber -> color Yellow
+ TBoolean -> color Cyan
+ TRef -> color Red
+ _ -> mempty
+
+-- | Like 'renderPrettyDef', but includes escape sequences for terminal colours.
+--
+-- Examples:
+--
+-- >>> renderAnsi (asValue (List [String "hi", Keyword (Ident "there")]))
+-- "\ESC[0m(\ESC[0;92m\"hi\"\ESC[0m \ESC[0;95m:there\ESC[0m)\ESC[0m"
+renderAnsi :: PrettyV v => v -> Text
+renderAnsi = Term.renderStrict . reAnnotateS toAnsi . layoutSmart defaultLayoutOptions . prettyV
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index df4936e..f022471 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -600,6 +600,11 @@ test_pretty =
pp = renderPrettyDef v
v_ = parseTest pp
in v_ == Right v
+ , testCase "renderAnsi renders colours" $ do
+ renderAnsi (kw "hello") @?= "\ESC[0;95m:hello\ESC[0m"
+ renderAnsi (asValue (String "hello")) @?= "\ESC[0;92m\"hello\"\ESC[0m"
+ renderAnsi (int 42) @?= "\ESC[0;93m42\ESC[0m"
+ renderAnsi (asValue (Boolean True)) @?= "\ESC[0;96m#t\ESC[0m"
]
where
apl cols = AvailablePerLine cols 1
@@ -699,19 +704,19 @@ test_repl =
, "#t"
]
(_, result) <- runInRepl input
- result @==> ["#t"]
+ result @==> [ "#t" ]
, testCase "load! a non-existent file is a non-fatal exception" $ do
let input = [ "(load! \"not-a-thing.rad\")"
, "#t"
]
(_, result) <- runInRepl input
- result @==> ["#t"]
+ result @==> [ "#t"]
]
where
-- In addition to the output of the lines tested, tests get
-- printed, so we take only the last few output lines.
- r @==> out = reverse (take (length out) r) @?= out
+ r @==> out = reverse (take (length out) r) @?= (ansi <$> out)
test_from_to_radicle :: [TestTree]
test_from_to_radicle =
@@ -809,7 +814,7 @@ test_macros =
, ":quit"
, "x"
]
- output = [ "0" ]
+ output = [ ansi "0" ]
(_, result) <- runInRepl input
result @==> output
]
@@ -849,3 +854,8 @@ runInRepl inp = do
, "repl.rad" `T.isSuffixOf` name
]
pure $ runTestWithFiles testBindings inp (Map.fromList srcMap) (fromJust replSrc)
+
+ansi :: Text -> Text
+ansi t = case parseTest t of
+ Left _ -> panic "Error adding colour codes to value string: original string does not parse."
+ Right v -> renderAnsi v