diff --git a/Nix.hs b/Nix.hs index 911c2b8..dfeefd9 100644 --- a/Nix.hs +++ b/Nix.hs @@ -3,7 +3,9 @@ module Main where import Data.Map as Map import Nix.Eval import Nix.Parser +import Nix.Pretty import Nix.Types +import Text.PrettyPrint.HughesPJ import System.Environment nix :: FilePath -> IO () @@ -12,6 +14,7 @@ nix path = do case res of Failure e -> error $ "Parse failed: " ++ show e Success n -> do + putStrLn $ render (prettyNix n) top <- evalExpr n (Fix (NVSet Map.empty)) -- evaluate top level print top diff --git a/Nix/Pretty.hs b/Nix/Pretty.hs new file mode 100644 index 0000000..4007a0e --- /dev/null +++ b/Nix/Pretty.hs @@ -0,0 +1,42 @@ +module Nix.Pretty where + +import Text.PrettyPrint.HughesPJ +import Nix.Types +import Data.Map (toList) +import Data.Text (Text) + +prettyBind :: (NExpr, NExpr) -> Doc +prettyBind (n, v) = prettyNix n <+> equals <+> prettyNix v <> semi + +prettySetArg :: (Text, Maybe NExpr) -> Doc +prettySetArg (n, Nothing) = text (show n) +prettySetArg (n, Just v) = text (show n) <+> text "?" <+> prettyNix v + +prettyFold = foldr (<+>) empty + +prettyNix :: NExpr -> Doc +prettyNix (Fix expr) = go expr where + go (NConstant atom) = text $ show atom + go (NOper oper) = text $ show oper + go (NList list) = lbrack <+> (prettyFold $ map prettyNix list) <+> rbrack + + go (NArgSet args) = lbrace <+> (prettyFold $ map prettySetArg $ toList args) <+> rbrace + + go (NSet rec list) = + (if rec then text "rec" else empty) + <+> lbrace <+> (foldr (<+>) empty $ map prettyBind list) <+> rbrace + + go (NLet binds body) = text "let" + go (NIf cond trueBody falseBody) = + text "if" <+> prettyNix cond + <+> text "then" <+> prettyNix trueBody + <+> text "else" <+> prettyNix falseBody + + go (NWith scope body) = text "with" <+> prettyNix scope <> semi <+> prettyNix body + go (NAssert cond body) = text "assert" <+> prettyNix cond <> semi <+> prettyNix body + go (NInherit attrs) = text "inherit" + + go (NVar e) = prettyNix e + go (NApp fun arg) = prettyNix fun <+> prettyNix arg + go (NAbs args body) = prettyNix args <> colon <+> prettyNix body + diff --git a/default.nix b/default.nix index 7ec70d0..55eb007 100644 --- a/default.nix +++ b/default.nix @@ -1,5 +1,5 @@ { cabal, parsers, trifecta, text, ansiWlPprint, parsec, transformers -, useParsec ? true +, pretty, useParsec ? true }: cabal.mkDerivation (self: rec { @@ -11,6 +11,7 @@ cabal.mkDerivation (self: rec { noHaddock = true; buildDepends = [ ansiWlPprint + pretty text transformers ] ++ (if useParsec then [ parsec ] else [ parsers trifecta ]); diff --git a/hnix.cabal b/hnix.cabal index 5ed20ce..9bbc8ef 100644 --- a/hnix.cabal +++ b/hnix.cabal @@ -45,6 +45,7 @@ Library base >= 4.3 && < 5 , ansi-wl-pprint , containers + , pretty , text , transformers if flag(parsec) @@ -80,6 +81,7 @@ executable hnix , hnix , ansi-wl-pprint , containers + , pretty , text , transformers if flag(parsec)