1 {-# LANGUAGE TemplateHaskell #-}
3 {-| TemplateHaskell helper for HTools.
5 As TemplateHaskell require that splices be defined in a separate
6 module, we combine all the TemplateHaskell functionality that HTools
7 needs in this module (except the one for unittests).
13 Copyright (C) 2011, 2012 Google Inc.
15 This program is free software; you can redistribute it and/or modify
16 it under the terms of the GNU General Public License as published by
17 the Free Software Foundation; either version 2 of the License, or
18 (at your option) any later version.
20 This program is distributed in the hope that it will be useful, but
21 WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 General Public License for more details.
25 You should have received a copy of the GNU General Public License
26 along with this program; if not, write to the Free Software
27 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
32 module Ganeti.THH ( declareSADT
52 , buildObjectSerialisation
56 import Control.Monad (liftM)
59 import qualified Data.Set as Set
60 import Language.Haskell.TH
62 import qualified Text.JSON as JSON
66 -- | Serialised field data type.
67 data Field = Field { fieldName :: String
69 , fieldRead :: Maybe (Q Exp)
70 , fieldShow :: Maybe (Q Exp)
71 , fieldDefault :: Maybe (Q Exp)
72 , fieldConstr :: Maybe String
73 , fieldIsOptional :: Bool
76 -- | Generates a simple field.
77 simpleField :: String -> Q Type -> Field
78 simpleField fname ftype =
79 Field { fieldName = fname
83 , fieldDefault = Nothing
84 , fieldConstr = Nothing
85 , fieldIsOptional = False
88 -- | Sets the renamed constructor field.
89 renameField :: String -> Field -> Field
90 renameField constrName field = field { fieldConstr = Just constrName }
92 -- | Sets the default value on a field (makes it optional with a
94 defaultField :: Q Exp -> Field -> Field
95 defaultField defval field = field { fieldDefault = Just defval }
97 -- | Marks a field optional (turning its base type into a Maybe).
98 optionalField :: Field -> Field
99 optionalField field = field { fieldIsOptional = True }
101 -- | Sets custom functions on a field.
102 customField :: Name -- ^ The name of the read function
103 -> Name -- ^ The name of the show function
104 -> Field -- ^ The original field
105 -> Field -- ^ Updated field
106 customField readfn showfn field =
107 field { fieldRead = Just (varE readfn), fieldShow = Just (varE showfn) }
109 fieldRecordName :: Field -> String
110 fieldRecordName (Field { fieldName = name, fieldConstr = alias }) =
111 maybe (camelCase name) id alias
113 -- | Computes the preferred variable name to use for the value of this
114 -- field. If the field has a specific constructor name, then we use a
115 -- first-letter-lowercased version of that; otherwise, we simply use
116 -- the field name. See also 'fieldRecordName'.
117 fieldVariable :: Field -> String
119 case (fieldConstr f) of
120 Just name -> ensureLower name
121 _ -> map (\c -> if c == '-' then '_' else c) $ fieldName f
123 actualFieldType :: Field -> Q Type
124 actualFieldType f | fieldIsOptional f = [t| Maybe $t |]
126 where t = fieldType f
128 checkNonOptDef :: (Monad m) => Field -> m ()
129 checkNonOptDef (Field { fieldIsOptional = True, fieldName = name }) =
130 fail $ "Optional field " ++ name ++ " used in parameter declaration"
131 checkNonOptDef (Field { fieldDefault = (Just _), fieldName = name }) =
132 fail $ "Default field " ++ name ++ " used in parameter declaration"
133 checkNonOptDef _ = return ()
135 -- | Produces the expression that will de-serialise a given
136 -- field. Since some custom parsing functions might need to use the
137 -- entire object, we do take and pass the object to any custom read
139 loadFn :: Field -- ^ The field definition
140 -> Q Exp -- ^ The value of the field as existing in the JSON message
141 -> Q Exp -- ^ The entire object in JSON object format
142 -> Q Exp -- ^ Resulting expression
143 loadFn (Field { fieldRead = Just readfn }) expr o = [| $expr >>= $readfn $o |]
144 loadFn _ expr _ = expr
146 -- * Common field declarations
148 timeStampFields :: [Field]
150 [ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |]
151 , defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |]
154 serialFields :: [Field]
156 [ renameField "Serial" $ simpleField "serial_no" [t| Int |] ]
158 uuidFields :: [Field]
159 uuidFields = [ simpleField "uuid" [t| String |] ]
161 -- | Tag field description.
162 tagsFields :: [Field]
163 tagsFields = [ defaultField [| Set.empty |] $
164 simpleField "tags" [t| Set.Set String |] ]
166 -- * Helper functions
168 -- | Ensure first letter is lowercase.
170 -- Used to convert type name to function prefix, e.g. in @data Aa ->
172 ensureLower :: String -> String
174 ensureLower (x:xs) = toLower x:xs
176 -- | Ensure first letter is uppercase.
178 -- Used to convert constructor name to component
179 ensureUpper :: String -> String
181 ensureUpper (x:xs) = toUpper x:xs
183 -- | Helper for quoted expressions.
184 varNameE :: String -> Q Exp
185 varNameE = varE . mkName
187 -- | showJSON as an expression, for reuse.
189 showJSONE = varNameE "showJSON"
191 -- | ToRaw function name.
192 toRawName :: String -> Name
193 toRawName = mkName . (++ "ToRaw") . ensureLower
195 -- | FromRaw function name.
196 fromRawName :: String -> Name
197 fromRawName = mkName . (++ "FromRaw") . ensureLower
199 -- | Converts a name to it's varE/litE representations.
201 reprE :: Either String Name -> Q Exp
202 reprE = either stringE varE
204 -- | Smarter function application.
206 -- This does simply f x, except that if is 'id', it will skip it, in
207 -- order to generate more readable code when using -ddump-splices.
208 appFn :: Exp -> Exp -> Exp
209 appFn f x | f == VarE 'id = x
210 | otherwise = AppE f x
212 -- * Template code for simple raw type-equivalent ADTs
214 -- | Generates a data type declaration.
216 -- The type will have a fixed list of instances.
217 strADTDecl :: Name -> [String] -> Dec
218 strADTDecl name constructors =
220 (map (flip NormalC [] . mkName) constructors)
221 [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
223 -- | Generates a toRaw function.
225 -- This generates a simple function of the form:
228 -- nameToRaw :: Name -> /traw/
229 -- nameToRaw Cons1 = var1
230 -- nameToRaw Cons2 = \"value2\"
232 genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec]
233 genToRaw traw fname tname constructors = do
234 let sigt = AppT (AppT ArrowT (ConT tname)) (ConT traw)
235 -- the body clauses, matching on the constructor and returning the
237 clauses <- mapM (\(c, v) -> clause [recP (mkName c) []]
238 (normalB (reprE v)) []) constructors
239 return [SigD fname sigt, FunD fname clauses]
241 -- | Generates a fromRaw function.
243 -- The function generated is monadic and can fail parsing the
244 -- raw value. It is of the form:
247 -- nameFromRaw :: (Monad m) => /traw/ -> m Name
248 -- nameFromRaw s | s == var1 = Cons1
249 -- | s == \"value2\" = Cons2
250 -- | otherwise = fail /.../
252 genFromRaw :: Name -> Name -> Name -> [(String, Name)] -> Q [Dec]
253 genFromRaw traw fname tname constructors = do
254 -- signature of form (Monad m) => String -> m $name
255 sigt <- [t| (Monad m) => $(conT traw) -> m $(conT tname) |]
256 -- clauses for a guarded pattern
257 let varp = mkName "s"
259 clauses <- mapM (\(c, v) -> do
260 -- the clause match condition
261 g <- normalG [| $varpe == $(varE v) |]
263 r <- [| return $(conE (mkName c)) |]
264 return (g, r)) constructors
265 -- the otherwise clause (fallback)
267 g <- normalG [| otherwise |]
268 r <- [|fail ("Invalid string value for type " ++
269 $(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
271 let fun = FunD fname [Clause [VarP varp]
272 (GuardedB (clauses++[oth_clause])) []]
273 return [SigD fname sigt, fun]
275 -- | Generates a data type from a given raw format.
277 -- The format is expected to multiline. The first line contains the
278 -- type name, and the rest of the lines must contain two words: the
279 -- constructor name and then the string representation of the
280 -- respective constructor.
282 -- The function will generate the data type declaration, and then two
285 -- * /name/ToRaw, which converts the type to a raw type
287 -- * /name/FromRaw, which (monadically) converts from a raw type to the type
289 -- Note that this is basically just a custom show/read instance,
291 declareADT :: Name -> String -> [(String, Name)] -> Q [Dec]
292 declareADT traw sname cons = do
293 let name = mkName sname
294 ddecl = strADTDecl name (map fst cons)
295 -- process cons in the format expected by genToRaw
296 cons' = map (\(a, b) -> (a, Right b)) cons
297 toraw <- genToRaw traw (toRawName sname) name cons'
298 fromraw <- genFromRaw traw (fromRawName sname) name cons
299 return $ ddecl:toraw ++ fromraw
301 declareIADT :: String -> [(String, Name)] -> Q [Dec]
302 declareIADT = declareADT ''Int
304 declareSADT :: String -> [(String, Name)] -> Q [Dec]
305 declareSADT = declareADT ''String
307 -- | Creates the showJSON member of a JSON instance declaration.
309 -- This will create what is the equivalent of:
312 -- showJSON = showJSON . /name/ToRaw
315 -- in an instance JSON /name/ declaration
316 genShowJSON :: String -> Q Dec
317 genShowJSON name = do
318 body <- [| JSON.showJSON . $(varE (toRawName name)) |]
319 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
321 -- | Creates the readJSON member of a JSON instance declaration.
323 -- This will create what is the equivalent of:
326 -- readJSON s = case readJSON s of
327 -- Ok s' -> /name/FromRaw s'
328 -- Error e -> Error /description/
331 -- in an instance JSON /name/ declaration
332 genReadJSON :: String -> Q Dec
333 genReadJSON name = do
335 body <- [| case JSON.readJSON $(varE s) of
336 JSON.Ok s' -> $(varE (fromRawName name)) s'
338 JSON.Error $ "Can't parse raw value for type " ++
339 $(stringE name) ++ ": " ++ e ++ " from " ++
342 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
344 -- | Generates a JSON instance for a given type.
346 -- This assumes that the /name/ToRaw and /name/FromRaw functions
347 -- have been defined as by the 'declareSADT' function.
348 makeJSONInstance :: Name -> Q [Dec]
349 makeJSONInstance name = do
350 let base = nameBase name
351 showJ <- genShowJSON base
352 readJ <- genReadJSON base
353 return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [readJ,showJ]]
355 -- * Template code for opcodes
357 -- | Transforms a CamelCase string into an_underscore_based_one.
358 deCamelCase :: String -> String
360 intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
362 -- | Transform an underscore_name into a CamelCase one.
363 camelCase :: String -> String
364 camelCase = concatMap (ensureUpper . drop 1) .
365 groupBy (\_ b -> b /= '_' && b /= '-') . ('_':)
367 -- | Computes the name of a given constructor.
368 constructorName :: Con -> Q Name
369 constructorName (NormalC name _) = return name
370 constructorName (RecC name _) = return name
371 constructorName x = fail $ "Unhandled constructor " ++ show x
373 -- | Extract all constructor names from a given type.
374 reifyConsNames :: Name -> Q [String]
375 reifyConsNames name = do
376 reify_result <- reify name
378 TyConI (DataD _ _ _ cons _) -> mapM (liftM nameBase . constructorName) cons
379 o -> fail $ "Unhandled name passed to reifyConsNames, expected\
380 \ type constructor but got '" ++ show o ++ "'"
382 -- | Builds the generic constructor-to-string function.
384 -- This generates a simple function of the following form:
387 -- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
388 -- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
391 -- This builds a custom list of name/string pairs and then uses
392 -- 'genToRaw' to actually generate the function
393 genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
394 genConstrToStr trans_fun name fname = do
395 cnames <- reifyConsNames name
396 let svalues = map (Left . trans_fun) cnames
397 genToRaw ''String (mkName fname) name $ zip cnames svalues
399 -- | Constructor-to-string for OpCode.
400 genOpID :: Name -> String -> Q [Dec]
401 genOpID = genConstrToStr deCamelCase
403 -- | Builds a list with all defined constructor names for a type.
410 -- Where the actual values of the string are the constructor names
411 -- mapped via @trans_fun@.
412 genAllConstr :: (String -> String) -> Name -> String -> Q [Dec]
413 genAllConstr trans_fun name vstr = do
414 cnames <- reifyConsNames name
415 let svalues = sort $ map trans_fun cnames
417 sig = SigD vname (AppT ListT (ConT ''String))
418 body = NormalB (ListE (map (LitE . StringL) svalues))
419 return $ [sig, ValD (VarP vname) body []]
421 -- | Generates a list of all defined opcode IDs.
422 genAllOpIDs :: Name -> String -> Q [Dec]
423 genAllOpIDs = genAllConstr deCamelCase
425 -- | OpCode parameter (field) type.
426 type OpParam = (String, Q Type, Q Exp)
428 -- | Generates the OpCode data type.
430 -- This takes an opcode logical definition, and builds both the
431 -- datatype and the JSON serialisation out of it. We can't use a
432 -- generic serialisation since we need to be compatible with Ganeti's
433 -- own, so we have a few quirks to work around.
434 genOpCode :: String -- ^ Type name to use
435 -> [(String, [Field])] -- ^ Constructor name and parameters
437 genOpCode name cons = do
438 decl_d <- mapM (\(cname, fields) -> do
439 -- we only need the type of the field, without Q
440 fields' <- mapM actualFieldType fields
441 let fields'' = zip (repeat NotStrict) fields'
442 return $ NormalC (mkName cname) fields'')
444 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
446 (savesig, savefn) <- genSaveOpCode cons
447 (loadsig, loadfn) <- genLoadOpCode cons
448 return [declD, loadsig, loadfn, savesig, savefn]
450 -- | Checks whether a given parameter is options.
452 -- This requires that it's a 'Maybe'.
453 isOptional :: Type -> Bool
454 isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
457 -- | Generates the \"save\" clause for an entire opcode constructor.
459 -- This matches the opcode with variables named the same as the
460 -- constructor fields (just so that the spliced in code looks nicer),
461 -- and passes those name plus the parameter definition to 'saveObjectField'.
462 saveConstructor :: String -- ^ The constructor name
463 -> [Field] -- ^ The parameter definitions for this
465 -> Q Clause -- ^ Resulting clause
466 saveConstructor sname fields = do
467 let cname = mkName sname
468 fnames <- mapM (newName . fieldVariable) fields
469 let pat = conP cname (map varP fnames)
470 let felems = map (uncurry saveObjectField) (zip fnames fields)
471 -- now build the OP_ID serialisation
472 opid = [| [( $(stringE "OP_ID"),
473 JSON.showJSON $(stringE . deCamelCase $ sname) )] |]
474 flist = listE (opid:felems)
475 -- and finally convert all this to a json object
476 flist' = [| $(varNameE "makeObj") (concat $flist) |]
477 clause [pat] (normalB flist') []
479 -- | Generates the main save opcode function.
481 -- This builds a per-constructor match clause that contains the
482 -- respective constructor-serialisation code.
483 genSaveOpCode :: [(String, [Field])] -> Q (Dec, Dec)
484 genSaveOpCode opdefs = do
485 cclauses <- mapM (uncurry saveConstructor) opdefs
486 let fname = mkName "saveOpCode"
487 sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |]
488 return $ (SigD fname sigt, FunD fname cclauses)
490 loadConstructor :: String -> [Field] -> Q Exp
491 loadConstructor sname fields = do
492 let name = mkName sname
493 fbinds <- mapM loadObjectField fields
494 let (fnames, fstmts) = unzip fbinds
495 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
496 fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
499 genLoadOpCode :: [(String, [Field])] -> Q (Dec, Dec)
500 genLoadOpCode opdefs = do
501 let fname = mkName "loadOpCode"
504 opid = mkName "op_id"
505 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
506 (JSON.readJSON $(varE arg1)) |]
507 st2 <- bindS (varP opid) [| $(varNameE "fromObj")
508 $(varE objname) $(stringE "OP_ID") |]
509 -- the match results (per-constructor blocks)
510 mexps <- mapM (uncurry loadConstructor) opdefs
511 fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
512 let mpats = map (\(me, c) ->
513 let mp = LitP . StringL . deCamelCase . fst $ c
514 in Match mp (NormalB me) []
516 defmatch = Match WildP (NormalB fails) []
517 cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
518 body = DoE [st1, st2, cst]
519 sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
520 return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
522 -- * Template code for luxi
524 -- | Constructor-to-string for LuxiOp.
525 genStrOfOp :: Name -> String -> Q [Dec]
526 genStrOfOp = genConstrToStr id
528 -- | Constructor-to-string for MsgKeys.
529 genStrOfKey :: Name -> String -> Q [Dec]
530 genStrOfKey = genConstrToStr ensureLower
532 -- | LuxiOp parameter type.
533 type LuxiParam = (String, Q Type)
535 -- | Generates the LuxiOp data type.
537 -- This takes a Luxi operation definition and builds both the
538 -- datatype and the function trnasforming the arguments to JSON.
539 -- We can't use anything less generic, because the way different
540 -- operations are serialized differs on both parameter- and top-level.
542 -- There are two things to be defined for each parameter:
548 genLuxiOp :: String -> [(String, [LuxiParam])] -> Q [Dec]
549 genLuxiOp name cons = do
550 decl_d <- mapM (\(cname, fields) -> do
551 fields' <- mapM (\(_, qt) ->
552 qt >>= \t -> return (NotStrict, t))
554 return $ NormalC (mkName cname) fields')
556 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
557 (savesig, savefn) <- genSaveLuxiOp cons
558 req_defs <- declareSADT "LuxiReq" .
559 map (\(str, _) -> ("Req" ++ str, mkName ("luxiReq" ++ str))) $
561 return $ [declD, savesig, savefn] ++ req_defs
563 -- | Generates the \"save\" expression for a single luxi parameter.
564 saveLuxiField :: Name -> LuxiParam -> Q Exp
565 saveLuxiField fvar (_, qt) =
566 [| JSON.showJSON $(varE fvar) |]
568 -- | Generates the \"save\" clause for entire LuxiOp constructor.
569 saveLuxiConstructor :: (String, [LuxiParam]) -> Q Clause
570 saveLuxiConstructor (sname, fields) = do
571 let cname = mkName sname
572 fnames = map (mkName . fst) fields
573 pat = conP cname (map varP fnames)
574 flist = map (uncurry saveLuxiField) (zip fnames fields)
575 finval = if null flist
576 then [| JSON.showJSON () |]
577 else [| JSON.showJSON $(listE flist) |]
578 clause [pat] (normalB finval) []
580 -- | Generates the main save LuxiOp function.
581 genSaveLuxiOp :: [(String, [LuxiParam])]-> Q (Dec, Dec)
582 genSaveLuxiOp opdefs = do
583 sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
584 let fname = mkName "opToArgs"
585 cclauses <- mapM saveLuxiConstructor opdefs
586 return $ (SigD fname sigt, FunD fname cclauses)
588 -- * "Objects" functionality
590 -- | Extract the field's declaration from a Field structure.
591 fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
592 fieldTypeInfo field_pfx fd = do
593 t <- actualFieldType fd
594 let n = mkName . (field_pfx ++) . fieldRecordName $ fd
595 return (n, NotStrict, t)
597 -- | Build an object declaration.
598 buildObject :: String -> String -> [Field] -> Q [Dec]
599 buildObject sname field_pfx fields = do
600 let name = mkName sname
601 fields_d <- mapM (fieldTypeInfo field_pfx) fields
602 let decl_d = RecC name fields_d
603 let declD = DataD [] name [] [decl_d] [''Show, ''Read, ''Eq]
604 ser_decls <- buildObjectSerialisation sname fields
605 return $ declD:ser_decls
607 buildObjectSerialisation :: String -> [Field] -> Q [Dec]
608 buildObjectSerialisation sname fields = do
609 let name = mkName sname
610 savedecls <- genSaveObject saveObjectField sname fields
611 (loadsig, loadfn) <- genLoadObject loadObjectField sname fields
612 shjson <- objectShowJSON sname
613 rdjson <- objectReadJSON sname
614 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
616 return $ savedecls ++ [loadsig, loadfn, instdecl]
618 genSaveObject :: (Name -> Field -> Q Exp)
619 -> String -> [Field] -> Q [Dec]
620 genSaveObject save_fn sname fields = do
621 let name = mkName sname
622 fnames <- mapM (newName . fieldVariable) fields
623 let pat = conP name (map varP fnames)
624 let tdname = mkName ("toDict" ++ sname)
625 tdsigt <- [t| $(conT name) -> [(String, JSON.JSValue)] |]
627 let felems = map (uncurry save_fn) (zip fnames fields)
629 -- and finally convert all this to a json object
630 tdlist = [| concat $flist |]
632 tclause <- clause [pat] (normalB tdlist) []
633 cclause <- [| $(varNameE "makeObj") . $(varE tdname) |]
634 let fname = mkName ("save" ++ sname)
635 sigt <- [t| $(conT name) -> JSON.JSValue |]
636 return [SigD tdname tdsigt, FunD tdname [tclause],
637 SigD fname sigt, ValD (VarP fname) (NormalB cclause) []]
639 saveObjectField :: Name -> Field -> Q Exp
640 saveObjectField fvar field
641 | fisOptional = [| case $(varE fvar) of
643 Just v -> [( $nameE, JSON.showJSON v)]
645 | otherwise = case fieldShow field of
646 Nothing -> [| [( $nameE, JSON.showJSON $fvarE)] |]
647 Just fn -> [| let (actual, extra) = $fn $fvarE
648 in extra ++ [( $nameE, JSON.showJSON actual)]
650 where fisOptional = fieldIsOptional field
651 nameE = stringE (fieldName field)
654 objectShowJSON :: String -> Q Dec
655 objectShowJSON name = do
656 body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |]
657 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
659 genLoadObject :: (Field -> Q (Name, Stmt))
660 -> String -> [Field] -> Q (Dec, Dec)
661 genLoadObject load_fn sname fields = do
662 let name = mkName sname
663 funname = mkName $ "load" ++ sname
666 opid = mkName "op_id"
667 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
668 (JSON.readJSON $(varE arg1)) |]
669 fbinds <- mapM load_fn fields
670 let (fnames, fstmts) = unzip fbinds
671 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
672 fstmts' = st1:fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
673 sigt <- [t| JSON.JSValue -> JSON.Result $(conT name) |]
674 return $ (SigD funname sigt,
675 FunD funname [Clause [VarP arg1] (NormalB (DoE fstmts')) []])
677 loadObjectField :: Field -> Q (Name, Stmt)
678 loadObjectField field = do
679 let name = fieldVariable field
681 -- these are used in all patterns below
682 let objvar = varNameE "o"
683 objfield = stringE (fieldName field)
685 if fieldIsOptional field
686 then [| $(varNameE "maybeFromObj") $objvar $objfield |]
687 else case fieldDefault field of
689 [| $(varNameE "fromObjWithDefault") $objvar
691 Nothing -> [| $(varNameE "fromObj") $objvar $objfield |]
692 bexp <- loadFn field loadexp objvar
694 return (fvar, BindS (VarP fvar) bexp)
696 objectReadJSON :: String -> Q Dec
697 objectReadJSON name = do
699 body <- [| case JSON.readJSON $(varE s) of
700 JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s'
702 JSON.Error $ "Can't parse value for type " ++
703 $(stringE name) ++ ": " ++ e
705 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
707 -- * Inheritable parameter tables implementation
709 -- | Compute parameter type names.
710 paramTypeNames :: String -> (String, String)
711 paramTypeNames root = ("Filled" ++ root ++ "Params",
712 "Partial" ++ root ++ "Params")
714 -- | Compute information about the type of a parameter field.
715 paramFieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
716 paramFieldTypeInfo field_pfx fd = do
717 t <- actualFieldType fd
718 let n = mkName . (++ "P") . (field_pfx ++) .
720 return (n, NotStrict, AppT (ConT ''Maybe) t)
722 -- | Build a parameter declaration.
724 -- This function builds two different data structures: a /filled/ one,
725 -- in which all fields are required, and a /partial/ one, in which all
726 -- fields are optional. Due to the current record syntax issues, the
727 -- fields need to be named differrently for the two structures, so the
728 -- partial ones get a /P/ suffix.
729 buildParam :: String -> String -> [Field] -> Q [Dec]
730 buildParam sname field_pfx fields = do
731 let (sname_f, sname_p) = paramTypeNames sname
732 name_f = mkName sname_f
733 name_p = mkName sname_p
734 fields_f <- mapM (fieldTypeInfo field_pfx) fields
735 fields_p <- mapM (paramFieldTypeInfo field_pfx) fields
736 let decl_f = RecC name_f fields_f
737 decl_p = RecC name_p fields_p
738 let declF = DataD [] name_f [] [decl_f] [''Show, ''Read, ''Eq]
739 declP = DataD [] name_p [] [decl_p] [''Show, ''Read, ''Eq]
740 ser_decls_f <- buildObjectSerialisation sname_f fields
741 ser_decls_p <- buildPParamSerialisation sname_p fields
742 fill_decls <- fillParam sname field_pfx fields
743 return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls
745 buildPParamSerialisation :: String -> [Field] -> Q [Dec]
746 buildPParamSerialisation sname fields = do
747 let name = mkName sname
748 savedecls <- genSaveObject savePParamField sname fields
749 (loadsig, loadfn) <- genLoadObject loadPParamField sname fields
750 shjson <- objectShowJSON sname
751 rdjson <- objectReadJSON sname
752 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
754 return $ savedecls ++ [loadsig, loadfn, instdecl]
756 savePParamField :: Name -> Field -> Q Exp
757 savePParamField fvar field = do
759 let actualVal = mkName "v"
760 normalexpr <- saveObjectField actualVal field
761 -- we have to construct the block here manually, because we can't
763 return $ CaseE (VarE fvar) [ Match (ConP 'Nothing [])
764 (NormalB (ConE '[])) []
765 , Match (ConP 'Just [VarP actualVal])
766 (NormalB normalexpr) []
768 loadPParamField :: Field -> Q (Name, Stmt)
769 loadPParamField field = do
771 let name = fieldName field
773 -- these are used in all patterns below
774 let objvar = varNameE "o"
775 objfield = stringE name
776 loadexp = [| $(varNameE "maybeFromObj") $objvar $objfield |]
777 bexp <- loadFn field loadexp objvar
778 return (fvar, BindS (VarP fvar) bexp)
780 -- | Builds a simple declaration of type @n_x = fromMaybe f_x p_x@.
781 buildFromMaybe :: String -> Q Dec
782 buildFromMaybe fname =
783 valD (varP (mkName $ "n_" ++ fname))
784 (normalB [| $(varNameE "fromMaybe")
785 $(varNameE $ "f_" ++ fname)
786 $(varNameE $ "p_" ++ fname) |]) []
788 fillParam :: String -> String -> [Field] -> Q [Dec]
789 fillParam sname field_pfx fields = do
790 let fnames = map (\fd -> field_pfx ++ fieldRecordName fd) fields
791 (sname_f, sname_p) = paramTypeNames sname
794 name_f = mkName sname_f
795 name_p = mkName sname_p
796 fun_name = mkName $ "fill" ++ sname ++ "Params"
797 le_full = ValD (ConP name_f (map (VarP . mkName . ("f_" ++)) fnames))
798 (NormalB . VarE . mkName $ oname_f) []
799 le_part = ValD (ConP name_p (map (VarP . mkName . ("p_" ++)) fnames))
800 (NormalB . VarE . mkName $ oname_p) []
801 obj_new = foldl (\accu vname -> AppE accu (VarE vname)) (ConE name_f)
802 $ map (mkName . ("n_" ++)) fnames
803 le_new <- mapM buildFromMaybe fnames
804 funt <- [t| $(conT name_f) -> $(conT name_p) -> $(conT name_f) |]
805 let sig = SigD fun_name funt
806 fclause = Clause [VarP (mkName oname_f), VarP (mkName oname_p)]
807 (NormalB $ LetE (le_full:le_part:le_new) obj_new) []
808 fun = FunD fun_name [fclause]