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
51 , buildObjectSerialisation
57 import Control.Monad (liftM, liftM2)
60 import qualified Data.Map as M
61 import Language.Haskell.TH
63 import qualified Text.JSON as JSON
65 import Ganeti.HTools.JSON
69 type Container = M.Map String
71 -- | Serialised field data type.
72 data Field = Field { fieldName :: String
74 , fieldRead :: Maybe (Q Exp)
75 , fieldShow :: Maybe (Q Exp)
76 , fieldDefault :: Maybe (Q Exp)
77 , fieldConstr :: Maybe String
78 , fieldIsContainer :: Bool
79 , fieldIsOptional :: Bool
82 -- | Generates a simple field.
83 simpleField :: String -> Q Type -> Field
84 simpleField fname ftype =
85 Field { fieldName = fname
89 , fieldDefault = Nothing
90 , fieldConstr = Nothing
91 , fieldIsContainer = False
92 , fieldIsOptional = False
95 -- | Sets the renamed constructor field.
96 renameField :: String -> Field -> Field
97 renameField constrName field = field { fieldConstr = Just constrName }
99 -- | Sets the default value on a field (makes it optional with a
101 defaultField :: Q Exp -> Field -> Field
102 defaultField defval field = field { fieldDefault = Just defval }
104 -- | Marks a field optional (turning its base type into a Maybe).
105 optionalField :: Field -> Field
106 optionalField field = field { fieldIsOptional = True }
108 -- | Marks a field as a container.
109 containerField :: Field -> Field
110 containerField field = field { fieldIsContainer = True }
112 -- | Sets custom functions on a field.
113 customField :: Name -- ^ The name of the read function
114 -> Name -- ^ The name of the show function
115 -> Field -- ^ The original field
116 -> Field -- ^ Updated field
117 customField readfn showfn field =
118 field { fieldRead = Just (varE readfn), fieldShow = Just (varE showfn) }
120 fieldRecordName :: Field -> String
121 fieldRecordName (Field { fieldName = name, fieldConstr = alias }) =
122 maybe (camelCase name) id alias
124 -- | Computes the preferred variable name to use for the value of this
125 -- field. If the field has a specific constructor name, then we use a
126 -- first-letter-lowercased version of that; otherwise, we simply use
127 -- the field name. See also 'fieldRecordName'.
128 fieldVariable :: Field -> String
130 case (fieldConstr f) of
131 Just name -> ensureLower name
134 actualFieldType :: Field -> Q Type
135 actualFieldType f | fieldIsContainer f = [t| Container $t |]
136 | fieldIsOptional f = [t| Maybe $t |]
138 where t = fieldType f
140 checkNonOptDef :: (Monad m) => Field -> m ()
141 checkNonOptDef (Field { fieldIsOptional = True, fieldName = name }) =
142 fail $ "Optional field " ++ name ++ " used in parameter declaration"
143 checkNonOptDef (Field { fieldDefault = (Just _), fieldName = name }) =
144 fail $ "Default field " ++ name ++ " used in parameter declaration"
145 checkNonOptDef _ = return ()
147 -- | Produces the expression that will de-serialise a given
148 -- field. Since some custom parsing functions might need to use the
149 -- entire object, we do take and pass the object to any custom read
151 loadFn :: Field -- ^ The field definition
152 -> Q Exp -- ^ The value of the field as existing in the JSON message
153 -> Q Exp -- ^ The entire object in JSON object format
154 -> Q Exp -- ^ Resulting expression
155 loadFn (Field { fieldIsContainer = True }) expr _ =
156 [| $expr >>= readContainer |]
157 loadFn (Field { fieldRead = Just readfn }) expr o = [| $expr >>= $readfn $o |]
158 loadFn _ expr _ = expr
160 -- * Common field declarations
162 timeStampFields :: [Field]
164 [ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |]
165 , defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |]
168 serialFields :: [Field]
170 [ renameField "Serial" $ simpleField "serial_no" [t| Int |] ]
172 uuidFields :: [Field]
173 uuidFields = [ simpleField "uuid" [t| String |] ]
175 -- * Helper functions
177 -- | Ensure first letter is lowercase.
179 -- Used to convert type name to function prefix, e.g. in @data Aa ->
181 ensureLower :: String -> String
183 ensureLower (x:xs) = toLower x:xs
185 -- | Ensure first letter is uppercase.
187 -- Used to convert constructor name to component
188 ensureUpper :: String -> String
190 ensureUpper (x:xs) = toUpper x:xs
192 -- | Helper for quoted expressions.
193 varNameE :: String -> Q Exp
194 varNameE = varE . mkName
196 -- | showJSON as an expression, for reuse.
198 showJSONE = varNameE "showJSON"
200 -- | ToRaw function name.
201 toRawName :: String -> Name
202 toRawName = mkName . (++ "ToRaw") . ensureLower
204 -- | FromRaw function name.
205 fromRawName :: String -> Name
206 fromRawName = mkName . (++ "FromRaw") . ensureLower
208 -- | Converts a name to it's varE/litE representations.
210 reprE :: Either String Name -> Q Exp
211 reprE = either stringE varE
213 -- | Smarter function application.
215 -- This does simply f x, except that if is 'id', it will skip it, in
216 -- order to generate more readable code when using -ddump-splices.
217 appFn :: Exp -> Exp -> Exp
218 appFn f x | f == VarE 'id = x
219 | otherwise = AppE f x
221 -- | Container loader
222 readContainer :: (Monad m, JSON.JSON a) =>
223 JSON.JSObject JSON.JSValue -> m (Container a)
224 readContainer obj = do
225 let kjvlist = JSON.fromJSObject obj
226 kalist <- mapM (\(k, v) -> fromKeyValue k v >>= \a -> return (k, a)) kjvlist
227 return $ M.fromList kalist
229 -- | Container dumper
230 showContainer :: (JSON.JSON a) => Container a -> JSON.JSValue
231 showContainer = JSON.makeObj . map (second JSON.showJSON) . M.toList
233 -- * Template code for simple raw type-equivalent ADTs
235 -- | Generates a data type declaration.
237 -- The type will have a fixed list of instances.
238 strADTDecl :: Name -> [String] -> Dec
239 strADTDecl name constructors =
241 (map (flip NormalC [] . mkName) constructors)
242 [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
244 -- | Generates a toRaw function.
246 -- This generates a simple function of the form:
249 -- nameToRaw :: Name -> /traw/
250 -- nameToRaw Cons1 = var1
251 -- nameToRaw Cons2 = \"value2\"
253 genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec]
254 genToRaw traw fname tname constructors = do
255 let sigt = AppT (AppT ArrowT (ConT tname)) (ConT traw)
256 -- the body clauses, matching on the constructor and returning the
258 clauses <- mapM (\(c, v) -> clause [recP (mkName c) []]
259 (normalB (reprE v)) []) constructors
260 return [SigD fname sigt, FunD fname clauses]
262 -- | Generates a fromRaw function.
264 -- The function generated is monadic and can fail parsing the
265 -- raw value. It is of the form:
268 -- nameFromRaw :: (Monad m) => /traw/ -> m Name
269 -- nameFromRaw s | s == var1 = Cons1
270 -- | s == \"value2\" = Cons2
271 -- | otherwise = fail /.../
273 genFromRaw :: Name -> Name -> Name -> [(String, Name)] -> Q [Dec]
274 genFromRaw traw fname tname constructors = do
275 -- signature of form (Monad m) => String -> m $name
276 sigt <- [t| (Monad m) => $(conT traw) -> m $(conT tname) |]
277 -- clauses for a guarded pattern
278 let varp = mkName "s"
280 clauses <- mapM (\(c, v) -> do
281 -- the clause match condition
282 g <- normalG [| $varpe == $(varE v) |]
284 r <- [| return $(conE (mkName c)) |]
285 return (g, r)) constructors
286 -- the otherwise clause (fallback)
288 g <- normalG [| otherwise |]
289 r <- [|fail ("Invalid string value for type " ++
290 $(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
292 let fun = FunD fname [Clause [VarP varp]
293 (GuardedB (clauses++[oth_clause])) []]
294 return [SigD fname sigt, fun]
296 -- | Generates a data type from a given raw format.
298 -- The format is expected to multiline. The first line contains the
299 -- type name, and the rest of the lines must contain two words: the
300 -- constructor name and then the string representation of the
301 -- respective constructor.
303 -- The function will generate the data type declaration, and then two
306 -- * /name/ToRaw, which converts the type to a raw type
308 -- * /name/FromRaw, which (monadically) converts from a raw type to the type
310 -- Note that this is basically just a custom show/read instance,
312 declareADT :: Name -> String -> [(String, Name)] -> Q [Dec]
313 declareADT traw sname cons = do
314 let name = mkName sname
315 ddecl = strADTDecl name (map fst cons)
316 -- process cons in the format expected by genToRaw
317 cons' = map (\(a, b) -> (a, Right b)) cons
318 toraw <- genToRaw traw (toRawName sname) name cons'
319 fromraw <- genFromRaw traw (fromRawName sname) name cons
320 return $ ddecl:toraw ++ fromraw
322 declareIADT :: String -> [(String, Name)] -> Q [Dec]
323 declareIADT = declareADT ''Int
325 declareSADT :: String -> [(String, Name)] -> Q [Dec]
326 declareSADT = declareADT ''String
328 -- | Creates the showJSON member of a JSON instance declaration.
330 -- This will create what is the equivalent of:
333 -- showJSON = showJSON . /name/ToRaw
336 -- in an instance JSON /name/ declaration
337 genShowJSON :: String -> Q Dec
338 genShowJSON name = do
339 body <- [| JSON.showJSON . $(varE (toRawName name)) |]
340 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
342 -- | Creates the readJSON member of a JSON instance declaration.
344 -- This will create what is the equivalent of:
347 -- readJSON s = case readJSON s of
348 -- Ok s' -> /name/FromRaw s'
349 -- Error e -> Error /description/
352 -- in an instance JSON /name/ declaration
353 genReadJSON :: String -> Q Dec
354 genReadJSON name = do
356 body <- [| case JSON.readJSON $(varE s) of
357 JSON.Ok s' -> $(varE (fromRawName name)) s'
359 JSON.Error $ "Can't parse raw value for type " ++
360 $(stringE name) ++ ": " ++ e ++ " from " ++
363 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
365 -- | Generates a JSON instance for a given type.
367 -- This assumes that the /name/ToRaw and /name/FromRaw functions
368 -- have been defined as by the 'declareSADT' function.
369 makeJSONInstance :: Name -> Q [Dec]
370 makeJSONInstance name = do
371 let base = nameBase name
372 showJ <- genShowJSON base
373 readJ <- genReadJSON base
374 return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [readJ,showJ]]
376 -- * Template code for opcodes
378 -- | Transforms a CamelCase string into an_underscore_based_one.
379 deCamelCase :: String -> String
381 intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
383 -- | Transform an underscore_name into a CamelCase one.
384 camelCase :: String -> String
385 camelCase = concatMap (ensureUpper . drop 1) .
386 groupBy (\_ b -> b /= '_') . ('_':)
388 -- | Computes the name of a given constructor.
389 constructorName :: Con -> Q Name
390 constructorName (NormalC name _) = return name
391 constructorName (RecC name _) = return name
392 constructorName x = fail $ "Unhandled constructor " ++ show x
394 -- | Builds the generic constructor-to-string function.
396 -- This generates a simple function of the following form:
399 -- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
400 -- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
403 -- This builds a custom list of name/string pairs and then uses
404 -- 'genToRaw' to actually generate the function
405 genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
406 genConstrToStr trans_fun name fname = do
407 TyConI (DataD _ _ _ cons _) <- reify name
408 cnames <- mapM (liftM nameBase . constructorName) cons
409 let svalues = map (Left . trans_fun) cnames
410 genToRaw ''String (mkName fname) name $ zip cnames svalues
412 -- | Constructor-to-string for OpCode.
413 genOpID :: Name -> String -> Q [Dec]
414 genOpID = genConstrToStr deCamelCase
416 -- | OpCode parameter (field) type.
417 type OpParam = (String, Q Type, Q Exp)
419 -- | Generates the OpCode data type.
421 -- This takes an opcode logical definition, and builds both the
422 -- datatype and the JSON serialisation out of it. We can't use a
423 -- generic serialisation since we need to be compatible with Ganeti's
424 -- own, so we have a few quirks to work around.
425 genOpCode :: String -- ^ Type name to use
426 -> [(String, [Field])] -- ^ Constructor name and parameters
428 genOpCode name cons = do
429 decl_d <- mapM (\(cname, fields) -> do
430 -- we only need the type of the field, without Q
431 fields' <- mapM actualFieldType fields
432 let fields'' = zip (repeat NotStrict) fields'
433 return $ NormalC (mkName cname) fields'')
435 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
437 (savesig, savefn) <- genSaveOpCode cons
438 (loadsig, loadfn) <- genLoadOpCode cons
439 return [declD, loadsig, loadfn, savesig, savefn]
441 -- | Checks whether a given parameter is options.
443 -- This requires that it's a 'Maybe'.
444 isOptional :: Type -> Bool
445 isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
448 -- | Generates the \"save\" clause for an entire opcode constructor.
450 -- This matches the opcode with variables named the same as the
451 -- constructor fields (just so that the spliced in code looks nicer),
452 -- and passes those name plus the parameter definition to 'saveObjectField'.
453 saveConstructor :: String -- ^ The constructor name
454 -> [Field] -- ^ The parameter definitions for this
456 -> Q Clause -- ^ Resulting clause
457 saveConstructor sname fields = do
458 let cname = mkName sname
459 let fnames = map (mkName . fieldVariable) fields
460 let pat = conP cname (map varP fnames)
461 let felems = map (uncurry saveObjectField) (zip fnames fields)
462 -- now build the OP_ID serialisation
463 opid = [| [( $(stringE "OP_ID"),
464 JSON.showJSON $(stringE . deCamelCase $ sname) )] |]
465 flist = listE (opid:felems)
466 -- and finally convert all this to a json object
467 flist' = [| $(varNameE "makeObj") (concat $flist) |]
468 clause [pat] (normalB flist') []
470 -- | Generates the main save opcode function.
472 -- This builds a per-constructor match clause that contains the
473 -- respective constructor-serialisation code.
474 genSaveOpCode :: [(String, [Field])] -> Q (Dec, Dec)
475 genSaveOpCode opdefs = do
476 cclauses <- mapM (uncurry saveConstructor) opdefs
477 let fname = mkName "saveOpCode"
478 sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |]
479 return $ (SigD fname sigt, FunD fname cclauses)
481 loadConstructor :: String -> [Field] -> Q Exp
482 loadConstructor sname fields = do
483 let name = mkName sname
484 fbinds <- mapM loadObjectField fields
485 let (fnames, fstmts) = unzip fbinds
486 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
487 fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
490 genLoadOpCode :: [(String, [Field])] -> Q (Dec, Dec)
491 genLoadOpCode opdefs = do
492 let fname = mkName "loadOpCode"
495 opid = mkName "op_id"
496 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
497 (JSON.readJSON $(varE arg1)) |]
498 st2 <- bindS (varP opid) [| $(varNameE "fromObj")
499 $(varE objname) $(stringE "OP_ID") |]
500 -- the match results (per-constructor blocks)
501 mexps <- mapM (uncurry loadConstructor) opdefs
502 fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
503 let mpats = map (\(me, c) ->
504 let mp = LitP . StringL . deCamelCase . fst $ c
505 in Match mp (NormalB me) []
507 defmatch = Match WildP (NormalB fails) []
508 cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
509 body = DoE [st1, st2, cst]
510 sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
511 return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
513 -- * Template code for luxi
515 -- | Constructor-to-string for LuxiOp.
516 genStrOfOp :: Name -> String -> Q [Dec]
517 genStrOfOp = genConstrToStr id
519 -- | Constructor-to-string for MsgKeys.
520 genStrOfKey :: Name -> String -> Q [Dec]
521 genStrOfKey = genConstrToStr ensureLower
523 -- | LuxiOp parameter type.
524 type LuxiParam = (String, Q Type, Q Exp)
526 -- | Generates the LuxiOp data type.
528 -- This takes a Luxi operation definition and builds both the
529 -- datatype and the function trnasforming the arguments to JSON.
530 -- We can't use anything less generic, because the way different
531 -- operations are serialized differs on both parameter- and top-level.
533 -- There are three things to be defined for each parameter:
539 -- * operation; this is the operation performed on the parameter before
542 genLuxiOp :: String -> [(String, [LuxiParam])] -> Q [Dec]
543 genLuxiOp name cons = do
544 decl_d <- mapM (\(cname, fields) -> do
545 fields' <- mapM (\(_, qt, _) ->
546 qt >>= \t -> return (NotStrict, t))
548 return $ NormalC (mkName cname) fields')
550 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
551 (savesig, savefn) <- genSaveLuxiOp cons
552 req_defs <- declareSADT "LuxiReq" .
553 map (\(str, _) -> ("Req" ++ str, mkName ("luxiReq" ++ str))) $
555 return $ [declD, savesig, savefn] ++ req_defs
557 -- | Generates the \"save\" expression for a single luxi parameter.
558 saveLuxiField :: Name -> LuxiParam -> Q Exp
559 saveLuxiField fvar (_, qt, fn) =
560 [| JSON.showJSON ( $(liftM2 appFn fn $ varE fvar) ) |]
562 -- | Generates the \"save\" clause for entire LuxiOp constructor.
563 saveLuxiConstructor :: (String, [LuxiParam]) -> Q Clause
564 saveLuxiConstructor (sname, fields) = do
565 let cname = mkName sname
566 fnames = map (\(nm, _, _) -> mkName nm) fields
567 pat = conP cname (map varP fnames)
568 flist = map (uncurry saveLuxiField) (zip fnames fields)
569 finval = if null flist
570 then [| JSON.showJSON () |]
571 else [| JSON.showJSON $(listE flist) |]
572 clause [pat] (normalB finval) []
574 -- | Generates the main save LuxiOp function.
575 genSaveLuxiOp :: [(String, [LuxiParam])]-> Q (Dec, Dec)
576 genSaveLuxiOp opdefs = do
577 sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
578 let fname = mkName "opToArgs"
579 cclauses <- mapM saveLuxiConstructor opdefs
580 return $ (SigD fname sigt, FunD fname cclauses)
582 -- * "Objects" functionality
584 -- | Extract the field's declaration from a Field structure.
585 fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
586 fieldTypeInfo field_pfx fd = do
587 t <- actualFieldType fd
588 let n = mkName . (field_pfx ++) . fieldRecordName $ fd
589 return (n, NotStrict, t)
591 -- | Build an object declaration.
592 buildObject :: String -> String -> [Field] -> Q [Dec]
593 buildObject sname field_pfx fields = do
594 let name = mkName sname
595 fields_d <- mapM (fieldTypeInfo field_pfx) fields
596 let decl_d = RecC name fields_d
597 let declD = DataD [] name [] [decl_d] [''Show, ''Read, ''Eq]
598 ser_decls <- buildObjectSerialisation sname fields
599 return $ declD:ser_decls
601 buildObjectSerialisation :: String -> [Field] -> Q [Dec]
602 buildObjectSerialisation sname fields = do
603 let name = mkName sname
604 savedecls <- genSaveObject saveObjectField sname fields
605 (loadsig, loadfn) <- genLoadObject loadObjectField sname fields
606 shjson <- objectShowJSON sname
607 rdjson <- objectReadJSON sname
608 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
610 return $ savedecls ++ [loadsig, loadfn, instdecl]
612 genSaveObject :: (Name -> Field -> Q Exp)
613 -> String -> [Field] -> Q [Dec]
614 genSaveObject save_fn sname fields = do
615 let name = mkName sname
616 let fnames = map (mkName . fieldVariable) fields
617 let pat = conP name (map varP fnames)
618 let tdname = mkName ("toDict" ++ sname)
619 tdsigt <- [t| $(conT name) -> [(String, JSON.JSValue)] |]
621 let felems = map (uncurry save_fn) (zip fnames fields)
623 -- and finally convert all this to a json object
624 tdlist = [| concat $flist |]
626 tclause <- clause [pat] (normalB tdlist) []
627 cclause <- [| $(varNameE "makeObj") . $(varE tdname) |]
628 let fname = mkName ("save" ++ sname)
629 sigt <- [t| $(conT name) -> JSON.JSValue |]
630 return [SigD tdname tdsigt, FunD tdname [tclause],
631 SigD fname sigt, ValD (VarP fname) (NormalB cclause) []]
633 saveObjectField :: Name -> Field -> Q Exp
634 saveObjectField fvar field
635 | isContainer = [| [( $nameE , JSON.showJSON . showContainer $ $fvarE)] |]
636 | fisOptional = [| case $(varE fvar) of
638 Just v -> [( $nameE, JSON.showJSON v)]
640 | otherwise = case fieldShow field of
641 Nothing -> [| [( $nameE, JSON.showJSON $fvarE)] |]
642 Just fn -> [| let (actual, extra) = $fn $fvarE
643 in extra ++ [( $nameE, JSON.showJSON actual)]
645 where isContainer = fieldIsContainer field
646 fisOptional = fieldIsOptional field
647 nameE = stringE (fieldName field)
650 objectShowJSON :: String -> Q Dec
651 objectShowJSON name = do
652 body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |]
653 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
655 genLoadObject :: (Field -> Q (Name, Stmt))
656 -> String -> [Field] -> Q (Dec, Dec)
657 genLoadObject load_fn sname fields = do
658 let name = mkName sname
659 funname = mkName $ "load" ++ sname
662 opid = mkName "op_id"
663 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
664 (JSON.readJSON $(varE arg1)) |]
665 fbinds <- mapM load_fn fields
666 let (fnames, fstmts) = unzip fbinds
667 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
668 fstmts' = st1:fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
669 sigt <- [t| JSON.JSValue -> JSON.Result $(conT name) |]
670 return $ (SigD funname sigt,
671 FunD funname [Clause [VarP arg1] (NormalB (DoE fstmts')) []])
673 loadObjectField :: Field -> Q (Name, Stmt)
674 loadObjectField field = do
675 let name = fieldVariable field
677 -- these are used in all patterns below
678 let objvar = varNameE "o"
679 objfield = stringE (fieldName field)
681 if fieldIsOptional field
682 then [| $(varNameE "maybeFromObj") $objvar $objfield |]
683 else case fieldDefault field of
685 [| $(varNameE "fromObjWithDefault") $objvar
687 Nothing -> [| $(varNameE "fromObj") $objvar $objfield |]
688 bexp <- loadFn field loadexp objvar
690 return (fvar, BindS (VarP fvar) bexp)
692 objectReadJSON :: String -> Q Dec
693 objectReadJSON name = do
695 body <- [| case JSON.readJSON $(varE s) of
696 JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s'
698 JSON.Error $ "Can't parse value for type " ++
699 $(stringE name) ++ ": " ++ e
701 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
703 -- * Inheritable parameter tables implementation
705 -- | Compute parameter type names.
706 paramTypeNames :: String -> (String, String)
707 paramTypeNames root = ("Filled" ++ root ++ "Params",
708 "Partial" ++ root ++ "Params")
710 -- | Compute information about the type of a parameter field.
711 paramFieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
712 paramFieldTypeInfo field_pfx fd = do
713 t <- actualFieldType fd
714 let n = mkName . (++ "P") . (field_pfx ++) .
716 return (n, NotStrict, AppT (ConT ''Maybe) t)
718 -- | Build a parameter declaration.
720 -- This function builds two different data structures: a /filled/ one,
721 -- in which all fields are required, and a /partial/ one, in which all
722 -- fields are optional. Due to the current record syntax issues, the
723 -- fields need to be named differrently for the two structures, so the
724 -- partial ones get a /P/ suffix.
725 buildParam :: String -> String -> [Field] -> Q [Dec]
726 buildParam sname field_pfx fields = do
727 let (sname_f, sname_p) = paramTypeNames sname
728 name_f = mkName sname_f
729 name_p = mkName sname_p
730 fields_f <- mapM (fieldTypeInfo field_pfx) fields
731 fields_p <- mapM (paramFieldTypeInfo field_pfx) fields
732 let decl_f = RecC name_f fields_f
733 decl_p = RecC name_p fields_p
734 let declF = DataD [] name_f [] [decl_f] [''Show, ''Read, ''Eq]
735 declP = DataD [] name_p [] [decl_p] [''Show, ''Read, ''Eq]
736 ser_decls_f <- buildObjectSerialisation sname_f fields
737 ser_decls_p <- buildPParamSerialisation sname_p fields
738 fill_decls <- fillParam sname field_pfx fields
739 return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls
741 buildPParamSerialisation :: String -> [Field] -> Q [Dec]
742 buildPParamSerialisation sname fields = do
743 let name = mkName sname
744 savedecls <- genSaveObject savePParamField sname fields
745 (loadsig, loadfn) <- genLoadObject loadPParamField sname fields
746 shjson <- objectShowJSON sname
747 rdjson <- objectReadJSON sname
748 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
750 return $ savedecls ++ [loadsig, loadfn, instdecl]
752 savePParamField :: Name -> Field -> Q Exp
753 savePParamField fvar field = do
755 let actualVal = mkName "v"
756 normalexpr <- saveObjectField actualVal field
757 -- we have to construct the block here manually, because we can't
759 return $ CaseE (VarE fvar) [ Match (ConP 'Nothing [])
760 (NormalB (ConE '[])) []
761 , Match (ConP 'Just [VarP actualVal])
762 (NormalB normalexpr) []
764 loadPParamField :: Field -> Q (Name, Stmt)
765 loadPParamField field = do
767 let name = fieldName field
769 -- these are used in all patterns below
770 let objvar = varNameE "o"
771 objfield = stringE name
772 loadexp = [| $(varNameE "maybeFromObj") $objvar $objfield |]
773 bexp <- loadFn field loadexp objvar
774 return (fvar, BindS (VarP fvar) bexp)
776 -- | Builds a simple declaration of type @n_x = fromMaybe f_x p_x@.
777 buildFromMaybe :: String -> Q Dec
778 buildFromMaybe fname =
779 valD (varP (mkName $ "n_" ++ fname))
780 (normalB [| $(varNameE "fromMaybe")
781 $(varNameE $ "f_" ++ fname)
782 $(varNameE $ "p_" ++ fname) |]) []
784 fillParam :: String -> String -> [Field] -> Q [Dec]
785 fillParam sname field_pfx fields = do
786 let fnames = map (\fd -> field_pfx ++ fieldRecordName fd) fields
787 (sname_f, sname_p) = paramTypeNames sname
790 name_f = mkName sname_f
791 name_p = mkName sname_p
792 fun_name = mkName $ "fill" ++ sname ++ "Params"
793 le_full = ValD (ConP name_f (map (VarP . mkName . ("f_" ++)) fnames))
794 (NormalB . VarE . mkName $ oname_f) []
795 le_part = ValD (ConP name_p (map (VarP . mkName . ("p_" ++)) fnames))
796 (NormalB . VarE . mkName $ oname_p) []
797 obj_new = foldl (\accu vname -> AppE accu (VarE vname)) (ConE name_f)
798 $ map (mkName . ("n_" ++)) fnames
799 le_new <- mapM buildFromMaybe fnames
800 funt <- [t| $(conT name_f) -> $(conT name_p) -> $(conT name_f) |]
801 let sig = SigD fun_name funt
802 fclause = Clause [VarP (mkName oname_f), VarP (mkName oname_p)]
803 (NormalB $ LetE (le_full:le_part:le_new) obj_new) []
804 fun = FunD fun_name [fclause]