折腾了一整天,我得出以下结论:
问题中提出的 Ast 并不是很灵活。
在后期阶段,我想以一种无法注释的方式注释不同的节点
仅通过参数化原始 Ast 来表达。
所以我更改了 Ast 以作为编写新类型的基础:
Ast funcdef = Ast funcdef
deriving (Show)
Header id fpartype = Header id (Maybe Type) [fpartype]
deriving (Show)
FuncDef header block = FuncDef header block
deriving (Show)
Block stmt = Block [stmt]
deriving (Show)
Stmt lvalue expr funccall =
StmtAssign lvalue expr |
StmtFuncCall funccall |
..
Expr expr intConst lvalue funccall =
ExprIntConst intConst |
ExprLvalue lvalue |
ExprFuncCall funccall |
expr :+ expr |
expr :- expr |
..
现在我可以简单地为每个编译阶段定义一个新类型链。
重命名器阶段的 Ast 可以围绕标识符类型进行参数化:
newtype RAst id = RAst { ast :: Ast (RFuncDef id) }
newtype RHeader id = RHeader { header :: Header id (RFparType id) }
newtype RFuncDef id = RFuncDef {
funcDef :: FuncDef (RHeader id) (RBlock id)
}
..
newtype RExpr id = RExpr {
expr :: Expr (RExpr id) RIntConst (RLvalue id) (RFuncCall id)
}
在类型检查阶段,Ast 可以通过以下方式参数化
节点中使用的不同内部类型。
此参数化允许构造带有 Maybe 包装的 Asts
每个阶段中间的参数。
如果一切正常,我们可以使用fmap 删除Maybes 并为下一阶段准备树。 Functor, Foldable 和 Traversable 还有其他有用的方法,所以这些是必须具备的。
此时我想我想要的很可能是不可能的
没有元编程,所以我搜索了一个模板 haskell 解决方案。
果然有实现泛型的genifunctors库
fmap, foldMap 和 traverse 函数。使用这些很简单
编写一些新类型包装器以围绕适当的参数创建所需类型类的不同实例:
fmapGAst = $(genFmap Ast)
foldMapGAst = $(genFoldMap Ast)
traverseGast = $(genTraverse Ast)
newtype OverT1 t2 t3 t1 = OverT1 {unwrapT1 :: Ast t1 t2 t3 }
newtype OverT2 t1 t3 t2 = OverT2 {unwrapT2 :: Ast t1 t2 t3 }
newtype OverT3 t1 t2 t3 = OverT3 {unwrapT3 :: Ast t1 t2 t3 }
instance Functor (OverT1 a b) where
fmap f w = OverT1 $ fmapGAst f id id $ unwrapT1 w
instance Functor (OverT2 a b) where
fmap f w = OverT2 $ fmapGAst id f id $ unwrapT2 w
instance Functor (OverT3 a b) where
fmap f w = OverT3 $ fmapGAst id id f $ unwrapT3 w
..