Merge pull request #5 from lethalman/pretty

Pretty print nix expressions
This commit is contained in:
John Wiegley 2014-07-07 09:31:28 -05:00
commit be5c81d190
4 changed files with 49 additions and 1 deletions

3
Nix.hs
View File

@ -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

42
Nix/Pretty.hs Normal file
View File

@ -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

View File

@ -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 ]);

View File

@ -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)