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.hsindex 54c9f47..628b250 100644--- a/exe/RadicleExe.hs+++ b/exe/RadicleExe.hs@@ -19,9 +19,9 @@ main = do(result, _state) <- runLang bindings progcase result ofLeft (LangError _ Exit) -> pure ()- Left e -> do putStrLn $ renderPrettyDef e+ Left e -> do putStrLn $ renderAnsi eexitWith (ExitFailure 1)- Right v -> putStrLn $ renderPrettyDef v+ Right v -> putStrLn $ renderAnsi velse dosrc <- readSource (sourceFile opts')hist <- case histFile opts' ofdiff --git a/src/Radicle.hs b/src/Radicle.hsindex ac1cdb0..66f8c4f 100644--- a/src/Radicle.hs+++ b/src/Radicle.hs@@ -71,6 +71,7 @@ module Radicle, renderPretty, renderPrettyDef, renderCompactPretty+ , renderAnsi-- ** Re-exports, PageWidth(..), Prettydiff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hsindex 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 Mapimport 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 Timeimport GHC.Exts (IsList(..))@@ -57,7 +57,7 @@ repl histFile preFileName preCode bindings = do$ void $ interpretMany preFileName preCodecase r ofLeft (LangError _ Exit) -> pure ()- Left e -> putDoc $ pretty e+ Left e -> putDoc $ reAnnotate toAnsi $ prettyV eRight () -> 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 nilxs -> throwErrorHere $ WrongNumberOfArgs "print!" 1 (length xs))@@ -144,10 +144,10 @@ replPrimFns = fromList $ allDocs $(\err -> case err ofLangError _ Exit -> pure (pure nil)LangError _ (Impossible _) -> do- putStrS (renderPrettyDef err)+ putStrS (renderAnsi err)throwError err_ -> do- putStrS (renderPrettyDef err)+ putStrS (renderAnsi err)put stpure (loop action))go = dodiff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex 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 Mapimport Data.Sequence (Seq(..))+import qualified Data.Sequence as Seqimport qualified Data.Text as Timport Data.Text.Prettyprint.Doc+import Data.Text.Prettyprint.Doc.Render.Terminal (Color(..), color)+import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Termimport Data.Text.Prettyprint.Doc.Render.Textimport Text.Megaparsec.Error (parseErrorPretty)import Text.Megaparsec.Pos (sourcePosPretty)@@ -17,43 +20,48 @@ import qualified Radicle.Internal.Annotation as Annimport Radicle.Internal.Coreimport 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 wherepretty (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 ofAtom i -> pretty iKeyword i -> ":" <> pretty i- Ref i -> pretty i+ Ref i -> prettyV iString t -> "\"" <> pretty (escapeStr t) <> "\""Number (a :% b) -> pretty a <> if b == 1 then "" else "/" <> pretty bBoolean 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 ofEmpty -> "[]"- v' :<| Empty -> brackets $ pretty v'- _ -> brackets . sep $ pretty <$> toList vs+ v' :<| Empty -> brackets $ prettyV v'+ _ -> brackets . sep $ prettyV <$> toList vsPrimFn i -> pretty iDict 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 wherepretty (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 ofUnknownIdentifier i -> "Unknown identifier:" <+> pretty iImpossible t -> "This cannot be!" <+> pretty tTypeError 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) whereSpecialForm 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 valPatternMatchError e -> case e ofNoMatch -> "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 pwherepos :: Int -> Textpos 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 . prettyVdiff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex df4936e..f022471 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -600,6 +600,11 @@ test_pretty =pp = renderPrettyDef vv_ = parseTest ppin 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"]whereapl 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" $ dolet 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 inputresult @==> 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