[Haskell-cafe] Morphing ASTs and scrapping boilerplate code

Joel Reymont joelr1 at gmail.com
Thu Apr 19 12:11:08 EDT 2007


I'm transforming ASTs as part of my compiler from one language into  
another. The source AST is a list of statements whereas the target  
AST is a "class definition".

type Object a = State Obj a

data Obj
     = Object
       { objSym :: Integer -- starting # for gensym
       , objVars :: M.Map String VarDecl
       , objProps :: M.Map String PropDecl
       , objMeths :: M.Map String MethodDecl
     deriving (Show, Eq)

I'm using a state monad and the transformations are supposed to  
update the state (object) as needed to add variables, methods, etc.

class Morpher a b | a -> b where
     morph :: a -> Object b

I have a lot of boilerplate code like this and wonder how I can  
scrape it.

instance Morpher Type C.Type where
     morph TyInt = return C.TyInt
     morph TyFloat = return C.TyFloat
     morph TyStr = return C.TyStr
     morph TyBool = return C.TyBool
     morph TyColor = return C.TyColor
     morph TyStyle = return C.TyStyle
     morph (TyList ty) = liftM C.TyList (morph ty)
     morph (TyArray ty) = liftM C.TyArray (morph ty)
     morph (TySeries ty) = liftM C.TySeries (morph ty)
     morph (TyInput ty) = liftM C.TyProp (morph ty)
     morph (TyRef ty) = liftM C.TyRef (morph ty)
     morph TyUnit = return C.TyUnit
     morph TyPrintDest = return C.TyPrintDest

Notice that I'm calling a constructor of the same name in a different  
module ... unless it's an exception.

instance Morpher BackRef C.Expr where
     morph Now = C.Int 0
     morph (BarsBack e) = morph e

instance Morpher DataRef C.Expr where
     morph (DS x) = C.Int x

How can I reduce the boilerplate here?

	Thanks, Joel


More information about the Haskell-Cafe mailing list