Cac*_*tus 8 haskell pretty-print
我正在尝试使用生成Javascript Text.PrettyPrint.问题是,nest当放在另一个漂亮的元素旁边时会产生巨大的缩进.例如,在此代码中:
import Text.PrettyPrint
fun :: Doc
fun = vcat [ text "function" <+> lbrace
, nest 4 $ vcat $ replicate 5 $ text "// foo"
, rbrace
]
var :: Doc
var = text "var" <+> text "x"
test :: Doc
test = var <+> equals <+> fun <> semi
Run Code Online (Sandbox Code Playgroud)
fun从第9列开始test(由于var <+> equals <> empty它的左侧),因此其后续行缩进9 + 4 = 13列:
var x = function {
// foo
// foo
// foo
// foo
// foo
};
Run Code Online (Sandbox Code Playgroud)
有没有办法从左边距渲染缩进,以便上面将呈现为
var x = function {
// foo
// foo
// foo
// foo
// foo
};
Run Code Online (Sandbox Code Playgroud)
?
解决方案确实是使用wl-pprint(并替换nest为indent)。然后,给出的代码产生
var x = function {
// foo
// foo
// foo
// foo
// foo
};
Run Code Online (Sandbox Code Playgroud)
如预期的。对于任何仍然打算尝试破解 的人pretty,请注意,尽管 的构造函数Doc没有公开,但您仍然可以通过Generic以下方式获取它们-XPatternSynonyms:
-- | Means of exposing the data constructors of `Doc` from `pretty`
pattern GEmpty = M1 (L1 (L1 (L1 (M1 U1))))
pattern GNilAbove doc = M1 (L1 (L1 (R1 (M1 (M1 (K1 doc))))))
pattern GTextBeside d doc = M1 (L1 (R1 (L1 (M1 (M1 (K1 d) :*: M1 (K1 doc))))))
pattern GNest n doc = M1 (L1 (R1 (R1 (M1 (M1 (K1 n) :*: M1 (K1 doc))))))
pattern GUnion ldoc rdoc = M1 (R1 (L1 (L1 (M1 (M1 (K1 ldoc) :*: M1 (K1 rdoc))))))
pattern GNoDoc = M1 (R1 (L1 (R1 (M1 U1))))
pattern GBeside ldoc s rdoc = M1 (R1 (R1 (L1 (M1 (M1 (K1 ldoc) :*: M1 (K1 s) :*: M1 (K1 rdoc))))))
pattern GAbove ldoc b rdoc = M1 (R1 (R1 (R1 (M1 (M1 (K1 ldoc) :*: M1 (K1 b) :*: M1 (K1 rdoc))))))
Run Code Online (Sandbox Code Playgroud)
问题主要在于不违反图书馆幕后的许多不变量中的任何一个。
作为旁注,我还发现wl-pprint-annotated,现代重写wl-pprint,通过它可以访问底层数据构造函数(代价是需要记住所涉及的不变量)。这实际上是我最终将使用的包。
特别是,它让我可以制作这种大括号块,如果它足够小,它将只占一行:
-- | Asserts a 'Doc a' cannot render on multiple lines.
oneLine :: Doc a -> Bool
oneLine (WL.FlatAlt d _) = oneLine d
oneLine (WL.Cat a b) = oneLine a && oneLine b
oneLine (WL.Union a b) = oneLine a && oneLine b
oneLine (WL.Annotate _ d) = oneLine d
oneLine WL.Line = False
oneLine _ = True
-- | Make a curly-brace delimited block. When possible, permit fitting everything on one line
block :: Doc a -> Doc a
block b | oneLine b = hsep ["{", b, "}"] `WL.Union` vsep [ "{", indent 2 b, "}" ]
| otherwise = vsep [ "{", indent 2 b, "}" ]
Run Code Online (Sandbox Code Playgroud)
然后我得到了很好的结果,自动跨越或不跨越多行:
ghci> "function" <> parens "x" <+> block ("return" <+> "x" <> semi)
function(x) { return x; }
ghci> "function" <> parens "x" <+> block ("x" <> "++" <> semi <#> "return" <+> "x" <> semi)
function(x) {
x++;
return x;
}
Run Code Online (Sandbox Code Playgroud)