查看模板 Haskell 生成的代码的首选方法 [英] Preferred method for viewing code generated by Template Haskell

查看:19
本文介绍了查看模板 Haskell 生成的代码的首选方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,Template Haskell 用于在编译时以编程方式生成各种 AST 拼接.

As you know, Template Haskell is used to generate various kinds of AST splices programmatically at compile-time.

但是,接头通常非常不透明,而且通常很难辨别接头实际生成的内容.如果您为拼接运行 Q monad,并且拼接是类型良好的,您将获得生成的 AST 片段的 showable 表示,但这种表示可以是非常难以理解,因为它的非结构化布局.

However, a splice can often be very opaque, and it is often difficult to discern what a splice actually generates. If you run the Q monad for a splice, and the splice is well-typed, you get a showable representation of the generated piece of AST, but this representation can be very difficult to understand, because of its unstructured layout.

将一段 TH 生成的 AST 转换为类似于普通 Haskell 代码的内容的首选方法是什么,以便代码易于阅读和理解?可以从例如重建源代码吗?给定的 Dec 值?是否必须阅读 GHC 核心代码?有没有办法至少构造 AST 以使其更具可读性(超出例如 pretty-show 包的作用)?

What is the preferred method for converting a piece of TH-generated AST into something akin to normal Haskell code, so that the code can be easily read and understood? Can one reconstruct source code from e.g. a given Dec value? Does one have to read the GHC Core code? Is there a way to at least structure the AST so that it becomes more readable (Beyond what e.g. the pretty-show package does)?

推荐答案

您可以使用 pprintppr 来自 Language.Haskell.TH.Ppr(自动导入使用 Language.Haskell.TH):

You may be able to use pprint or ppr from Language.Haskell.TH.Ppr (imported automatically with Language.Haskell.TH):

GHCi> expr <- runQ [| f g x -> f (x*2 + 3) . g |]
GHCi> putStrLn $ pprint expr
f_0 g_1 x_2 -> f_0 ((x_2 GHC.Num.* 2) GHC.Num.+ 3) GHC.Base.. g_1

它并不漂亮,但它是有效的 Haskell.您应该能够通过从 Prelude 名称中去除模块前缀来使输出更好(尽管您可能需要小心仅去除预期的前缀;Foo.* 是一个完全有效的中缀运算符,在全部).

It's not pretty, but it is valid Haskell. You should be able to make the output nicer by stripping off module prefixes from Prelude names (although you might need to be careful to only strip the expected prefix; Foo.* is a perfectly valid infix operator, after all).

这篇关于查看模板 Haskell 生成的代码的首选方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆