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
55 import Control.Monad (liftM)
58 import qualified Data.Set as Set
59 import Language.Haskell.TH
61 import qualified Text.JSON as JSON
65 -- | Serialised field data type.
66 data Field = Field { fieldName :: String
68 , fieldRead :: Maybe (Q Exp)
69 , fieldShow :: Maybe (Q Exp)
70 , fieldDefault :: Maybe (Q Exp)
71 , fieldConstr :: Maybe String
72 , fieldIsOptional :: Bool
75 -- | Generates a simple field.
76 simpleField :: String -> Q Type -> Field
77 simpleField fname ftype =
78 Field { fieldName = fname
82 , fieldDefault = Nothing
83 , fieldConstr = Nothing
84 , fieldIsOptional = False
87 -- | Sets the renamed constructor field.
88 renameField :: String -> Field -> Field
89 renameField constrName field = field { fieldConstr = Just constrName }
91 -- | Sets the default value on a field (makes it optional with a
93 defaultField :: Q Exp -> Field -> Field
94 defaultField defval field = field { fieldDefault = Just defval }
96 -- | Marks a field optional (turning its base type into a Maybe).
97 optionalField :: Field -> Field
98 optionalField field = field { fieldIsOptional = True }
100 -- | Sets custom functions on a field.
101 customField :: Name -- ^ The name of the read function
102 -> Name -- ^ The name of the show function
103 -> Field -- ^ The original field
104 -> Field -- ^ Updated field
105 customField readfn showfn field =
106 field { fieldRead = Just (varE readfn), fieldShow = Just (varE showfn) }
108 fieldRecordName :: Field -> String
109 fieldRecordName (Field { fieldName = name, fieldConstr = alias }) =
110 maybe (camelCase name) id alias
112 -- | Computes the preferred variable name to use for the value of this
113 -- field. If the field has a specific constructor name, then we use a
114 -- first-letter-lowercased version of that; otherwise, we simply use
115 -- the field name. See also 'fieldRecordName'.
116 fieldVariable :: Field -> String
118 case (fieldConstr f) of
119 Just name -> ensureLower name
120 _ -> map (\c -> if c == '-' then '_' else c) $ fieldName f
122 actualFieldType :: Field -> Q Type
123 actualFieldType f | fieldIsOptional f = [t| Maybe $t |]
125 where t = fieldType f
127 checkNonOptDef :: (Monad m) => Field -> m ()
128 checkNonOptDef (Field { fieldIsOptional = True, fieldName = name }) =
129 fail $ "Optional field " ++ name ++ " used in parameter declaration"
130 checkNonOptDef (Field { fieldDefault = (Just _), fieldName = name }) =
131 fail $ "Default field " ++ name ++ " used in parameter declaration"
132 checkNonOptDef _ = return ()
134 -- | Produces the expression that will de-serialise a given
135 -- field. Since some custom parsing functions might need to use the
136 -- entire object, we do take and pass the object to any custom read
138 loadFn :: Field -- ^ The field definition
139 -> Q Exp -- ^ The value of the field as existing in the JSON message
140 -> Q Exp -- ^ The entire object in JSON object format
141 -> Q Exp -- ^ Resulting expression
142 loadFn (Field { fieldRead = Just readfn }) expr o = [| $expr >>= $readfn $o |]
143 loadFn _ expr _ = expr
145 -- * Common field declarations
147 timeStampFields :: [Field]
149 [ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |]
150 , defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |]
153 serialFields :: [Field]
155 [ renameField "Serial" $ simpleField "serial_no" [t| Int |] ]
157 uuidFields :: [Field]
158 uuidFields = [ simpleField "uuid" [t| String |] ]
160 -- | Tag field description.
161 tagsFields :: [Field]
162 tagsFields = [ defaultField [| Set.empty |] $
163 simpleField "tags" [t| Set.Set String |] ]
165 -- * Helper functions
167 -- | Ensure first letter is lowercase.
169 -- Used to convert type name to function prefix, e.g. in @data Aa ->
171 ensureLower :: String -> String
173 ensureLower (x:xs) = toLower x:xs
175 -- | Ensure first letter is uppercase.
177 -- Used to convert constructor name to component
178 ensureUpper :: String -> String
180 ensureUpper (x:xs) = toUpper x:xs
182 -- | Helper for quoted expressions.
183 varNameE :: String -> Q Exp
184 varNameE = varE . mkName
186 -- | showJSON as an expression, for reuse.
188 showJSONE = varNameE "showJSON"
190 -- | ToRaw function name.
191 toRawName :: String -> Name
192 toRawName = mkName . (++ "ToRaw") . ensureLower
194 -- | FromRaw function name.
195 fromRawName :: String -> Name
196 fromRawName = mkName . (++ "FromRaw") . ensureLower
198 -- | Converts a name to it's varE/litE representations.
200 reprE :: Either String Name -> Q Exp
201 reprE = either stringE varE
203 -- | Smarter function application.
205 -- This does simply f x, except that if is 'id', it will skip it, in
206 -- order to generate more readable code when using -ddump-splices.
207 appFn :: Exp -> Exp -> Exp
208 appFn f x | f == VarE 'id = x
209 | otherwise = AppE f x
211 -- * Template code for simple raw type-equivalent ADTs
213 -- | Generates a data type declaration.
215 -- The type will have a fixed list of instances.
216 strADTDecl :: Name -> [String] -> Dec
217 strADTDecl name constructors =
219 (map (flip NormalC [] . mkName) constructors)
220 [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
222 -- | Generates a toRaw function.
224 -- This generates a simple function of the form:
227 -- nameToRaw :: Name -> /traw/
228 -- nameToRaw Cons1 = var1
229 -- nameToRaw Cons2 = \"value2\"
231 genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec]
232 genToRaw traw fname tname constructors = do
233 let sigt = AppT (AppT ArrowT (ConT tname)) (ConT traw)
234 -- the body clauses, matching on the constructor and returning the
236 clauses <- mapM (\(c, v) -> clause [recP (mkName c) []]
237 (normalB (reprE v)) []) constructors
238 return [SigD fname sigt, FunD fname clauses]
240 -- | Generates a fromRaw function.
242 -- The function generated is monadic and can fail parsing the
243 -- raw value. It is of the form:
246 -- nameFromRaw :: (Monad m) => /traw/ -> m Name
247 -- nameFromRaw s | s == var1 = Cons1
248 -- | s == \"value2\" = Cons2
249 -- | otherwise = fail /.../
251 genFromRaw :: Name -> Name -> Name -> [(String, Name)] -> Q [Dec]
252 genFromRaw traw fname tname constructors = do
253 -- signature of form (Monad m) => String -> m $name
254 sigt <- [t| (Monad m) => $(conT traw) -> m $(conT tname) |]
255 -- clauses for a guarded pattern
256 let varp = mkName "s"
258 clauses <- mapM (\(c, v) -> do
259 -- the clause match condition
260 g <- normalG [| $varpe == $(varE v) |]
262 r <- [| return $(conE (mkName c)) |]
263 return (g, r)) constructors
264 -- the otherwise clause (fallback)
266 g <- normalG [| otherwise |]
267 r <- [|fail ("Invalid string value for type " ++
268 $(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
270 let fun = FunD fname [Clause [VarP varp]
271 (GuardedB (clauses++[oth_clause])) []]
272 return [SigD fname sigt, fun]
274 -- | Generates a data type from a given raw format.
276 -- The format is expected to multiline. The first line contains the
277 -- type name, and the rest of the lines must contain two words: the
278 -- constructor name and then the string representation of the
279 -- respective constructor.
281 -- The function will generate the data type declaration, and then two
284 -- * /name/ToRaw, which converts the type to a raw type
286 -- * /name/FromRaw, which (monadically) converts from a raw type to the type
288 -- Note that this is basically just a custom show/read instance,
290 declareADT :: Name -> String -> [(String, Name)] -> Q [Dec]
291 declareADT traw sname cons = do
292 let name = mkName sname
293 ddecl = strADTDecl name (map fst cons)
294 -- process cons in the format expected by genToRaw
295 cons' = map (\(a, b) -> (a, Right b)) cons
296 toraw <- genToRaw traw (toRawName sname) name cons'
297 fromraw <- genFromRaw traw (fromRawName sname) name cons
298 return $ ddecl:toraw ++ fromraw
300 declareIADT :: String -> [(String, Name)] -> Q [Dec]
301 declareIADT = declareADT ''Int
303 declareSADT :: String -> [(String, Name)] -> Q [Dec]
304 declareSADT = declareADT ''String
306 -- | Creates the showJSON member of a JSON instance declaration.
308 -- This will create what is the equivalent of:
311 -- showJSON = showJSON . /name/ToRaw
314 -- in an instance JSON /name/ declaration
315 genShowJSON :: String -> Q Dec
316 genShowJSON name = do
317 body <- [| JSON.showJSON . $(varE (toRawName name)) |]
318 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
320 -- | Creates the readJSON member of a JSON instance declaration.
322 -- This will create what is the equivalent of:
325 -- readJSON s = case readJSON s of
326 -- Ok s' -> /name/FromRaw s'
327 -- Error e -> Error /description/
330 -- in an instance JSON /name/ declaration
331 genReadJSON :: String -> Q Dec
332 genReadJSON name = do
334 body <- [| case JSON.readJSON $(varE s) of
335 JSON.Ok s' -> $(varE (fromRawName name)) s'
337 JSON.Error $ "Can't parse raw value for type " ++
338 $(stringE name) ++ ": " ++ e ++ " from " ++
341 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
343 -- | Generates a JSON instance for a given type.
345 -- This assumes that the /name/ToRaw and /name/FromRaw functions
346 -- have been defined as by the 'declareSADT' function.
347 makeJSONInstance :: Name -> Q [Dec]
348 makeJSONInstance name = do
349 let base = nameBase name
350 showJ <- genShowJSON base
351 readJ <- genReadJSON base
352 return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [readJ,showJ]]
354 -- * Template code for opcodes
356 -- | Transforms a CamelCase string into an_underscore_based_one.
357 deCamelCase :: String -> String
359 intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
361 -- | Transform an underscore_name into a CamelCase one.
362 camelCase :: String -> String
363 camelCase = concatMap (ensureUpper . drop 1) .
364 groupBy (\_ b -> b /= '_' && b /= '-') . ('_':)
366 -- | Computes the name of a given constructor.
367 constructorName :: Con -> Q Name
368 constructorName (NormalC name _) = return name
369 constructorName (RecC name _) = return name
370 constructorName x = fail $ "Unhandled constructor " ++ show x
372 -- | Extract all constructor names from a given type.
373 reifyConsNames :: Name -> Q [String]
374 reifyConsNames name = do
375 reify_result <- reify name
377 TyConI (DataD _ _ _ cons _) -> mapM (liftM nameBase . constructorName) cons
378 o -> fail $ "Unhandled name passed to reifyConsNames, expected\
379 \ type constructor but got '" ++ show o ++ "'"
381 -- | Builds the generic constructor-to-string function.
383 -- This generates a simple function of the following form:
386 -- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
387 -- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
390 -- This builds a custom list of name/string pairs and then uses
391 -- 'genToRaw' to actually generate the function
392 genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
393 genConstrToStr trans_fun name fname = do
394 cnames <- reifyConsNames name
395 let svalues = map (Left . trans_fun) cnames
396 genToRaw ''String (mkName fname) name $ zip cnames svalues
398 -- | Constructor-to-string for OpCode.
399 genOpID :: Name -> String -> Q [Dec]
400 genOpID = genConstrToStr deCamelCase
402 -- | OpCode parameter (field) type.
403 type OpParam = (String, Q Type, Q Exp)
405 -- | Generates the OpCode data type.
407 -- This takes an opcode logical definition, and builds both the
408 -- datatype and the JSON serialisation out of it. We can't use a
409 -- generic serialisation since we need to be compatible with Ganeti's
410 -- own, so we have a few quirks to work around.
411 genOpCode :: String -- ^ Type name to use
412 -> [(String, [Field])] -- ^ Constructor name and parameters
414 genOpCode name cons = do
415 decl_d <- mapM (\(cname, fields) -> do
416 -- we only need the type of the field, without Q
417 fields' <- mapM actualFieldType fields
418 let fields'' = zip (repeat NotStrict) fields'
419 return $ NormalC (mkName cname) fields'')
421 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
423 (savesig, savefn) <- genSaveOpCode cons
424 (loadsig, loadfn) <- genLoadOpCode cons
425 return [declD, loadsig, loadfn, savesig, savefn]
427 -- | Checks whether a given parameter is options.
429 -- This requires that it's a 'Maybe'.
430 isOptional :: Type -> Bool
431 isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
434 -- | Generates the \"save\" clause for an entire opcode constructor.
436 -- This matches the opcode with variables named the same as the
437 -- constructor fields (just so that the spliced in code looks nicer),
438 -- and passes those name plus the parameter definition to 'saveObjectField'.
439 saveConstructor :: String -- ^ The constructor name
440 -> [Field] -- ^ The parameter definitions for this
442 -> Q Clause -- ^ Resulting clause
443 saveConstructor sname fields = do
444 let cname = mkName sname
445 fnames <- mapM (newName . fieldVariable) fields
446 let pat = conP cname (map varP fnames)
447 let felems = map (uncurry saveObjectField) (zip fnames fields)
448 -- now build the OP_ID serialisation
449 opid = [| [( $(stringE "OP_ID"),
450 JSON.showJSON $(stringE . deCamelCase $ sname) )] |]
451 flist = listE (opid:felems)
452 -- and finally convert all this to a json object
453 flist' = [| $(varNameE "makeObj") (concat $flist) |]
454 clause [pat] (normalB flist') []
456 -- | Generates the main save opcode function.
458 -- This builds a per-constructor match clause that contains the
459 -- respective constructor-serialisation code.
460 genSaveOpCode :: [(String, [Field])] -> Q (Dec, Dec)
461 genSaveOpCode opdefs = do
462 cclauses <- mapM (uncurry saveConstructor) opdefs
463 let fname = mkName "saveOpCode"
464 sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |]
465 return $ (SigD fname sigt, FunD fname cclauses)
467 loadConstructor :: String -> [Field] -> Q Exp
468 loadConstructor sname fields = do
469 let name = mkName sname
470 fbinds <- mapM loadObjectField fields
471 let (fnames, fstmts) = unzip fbinds
472 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
473 fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
476 genLoadOpCode :: [(String, [Field])] -> Q (Dec, Dec)
477 genLoadOpCode opdefs = do
478 let fname = mkName "loadOpCode"
481 opid = mkName "op_id"
482 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
483 (JSON.readJSON $(varE arg1)) |]
484 st2 <- bindS (varP opid) [| $(varNameE "fromObj")
485 $(varE objname) $(stringE "OP_ID") |]
486 -- the match results (per-constructor blocks)
487 mexps <- mapM (uncurry loadConstructor) opdefs
488 fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
489 let mpats = map (\(me, c) ->
490 let mp = LitP . StringL . deCamelCase . fst $ c
491 in Match mp (NormalB me) []
493 defmatch = Match WildP (NormalB fails) []
494 cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
495 body = DoE [st1, st2, cst]
496 sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
497 return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
499 -- * Template code for luxi
501 -- | Constructor-to-string for LuxiOp.
502 genStrOfOp :: Name -> String -> Q [Dec]
503 genStrOfOp = genConstrToStr id
505 -- | Constructor-to-string for MsgKeys.
506 genStrOfKey :: Name -> String -> Q [Dec]
507 genStrOfKey = genConstrToStr ensureLower
509 -- | LuxiOp parameter type.
510 type LuxiParam = (String, Q Type)
512 -- | Generates the LuxiOp data type.
514 -- This takes a Luxi operation definition and builds both the
515 -- datatype and the function trnasforming the arguments to JSON.
516 -- We can't use anything less generic, because the way different
517 -- operations are serialized differs on both parameter- and top-level.
519 -- There are two things to be defined for each parameter:
525 genLuxiOp :: String -> [(String, [LuxiParam])] -> Q [Dec]
526 genLuxiOp name cons = do
527 decl_d <- mapM (\(cname, fields) -> do
528 fields' <- mapM (\(_, qt) ->
529 qt >>= \t -> return (NotStrict, t))
531 return $ NormalC (mkName cname) fields')
533 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
534 (savesig, savefn) <- genSaveLuxiOp cons
535 req_defs <- declareSADT "LuxiReq" .
536 map (\(str, _) -> ("Req" ++ str, mkName ("luxiReq" ++ str))) $
538 return $ [declD, savesig, savefn] ++ req_defs
540 -- | Generates the \"save\" expression for a single luxi parameter.
541 saveLuxiField :: Name -> LuxiParam -> Q Exp
542 saveLuxiField fvar (_, qt) =
543 [| JSON.showJSON $(varE fvar) |]
545 -- | Generates the \"save\" clause for entire LuxiOp constructor.
546 saveLuxiConstructor :: (String, [LuxiParam]) -> Q Clause
547 saveLuxiConstructor (sname, fields) = do
548 let cname = mkName sname
549 fnames = map (mkName . fst) fields
550 pat = conP cname (map varP fnames)
551 flist = map (uncurry saveLuxiField) (zip fnames fields)
552 finval = if null flist
553 then [| JSON.showJSON () |]
554 else [| JSON.showJSON $(listE flist) |]
555 clause [pat] (normalB finval) []
557 -- | Generates the main save LuxiOp function.
558 genSaveLuxiOp :: [(String, [LuxiParam])]-> Q (Dec, Dec)
559 genSaveLuxiOp opdefs = do
560 sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
561 let fname = mkName "opToArgs"
562 cclauses <- mapM saveLuxiConstructor opdefs
563 return $ (SigD fname sigt, FunD fname cclauses)
565 -- * "Objects" functionality
567 -- | Extract the field's declaration from a Field structure.
568 fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
569 fieldTypeInfo field_pfx fd = do
570 t <- actualFieldType fd
571 let n = mkName . (field_pfx ++) . fieldRecordName $ fd
572 return (n, NotStrict, t)
574 -- | Build an object declaration.
575 buildObject :: String -> String -> [Field] -> Q [Dec]
576 buildObject sname field_pfx fields = do
577 let name = mkName sname
578 fields_d <- mapM (fieldTypeInfo field_pfx) fields
579 let decl_d = RecC name fields_d
580 let declD = DataD [] name [] [decl_d] [''Show, ''Read, ''Eq]
581 ser_decls <- buildObjectSerialisation sname fields
582 return $ declD:ser_decls
584 buildObjectSerialisation :: String -> [Field] -> Q [Dec]
585 buildObjectSerialisation sname fields = do
586 let name = mkName sname
587 savedecls <- genSaveObject saveObjectField sname fields
588 (loadsig, loadfn) <- genLoadObject loadObjectField sname fields
589 shjson <- objectShowJSON sname
590 rdjson <- objectReadJSON sname
591 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
593 return $ savedecls ++ [loadsig, loadfn, instdecl]
595 genSaveObject :: (Name -> Field -> Q Exp)
596 -> String -> [Field] -> Q [Dec]
597 genSaveObject save_fn sname fields = do
598 let name = mkName sname
599 fnames <- mapM (newName . fieldVariable) fields
600 let pat = conP name (map varP fnames)
601 let tdname = mkName ("toDict" ++ sname)
602 tdsigt <- [t| $(conT name) -> [(String, JSON.JSValue)] |]
604 let felems = map (uncurry save_fn) (zip fnames fields)
606 -- and finally convert all this to a json object
607 tdlist = [| concat $flist |]
609 tclause <- clause [pat] (normalB tdlist) []
610 cclause <- [| $(varNameE "makeObj") . $(varE tdname) |]
611 let fname = mkName ("save" ++ sname)
612 sigt <- [t| $(conT name) -> JSON.JSValue |]
613 return [SigD tdname tdsigt, FunD tdname [tclause],
614 SigD fname sigt, ValD (VarP fname) (NormalB cclause) []]
616 saveObjectField :: Name -> Field -> Q Exp
617 saveObjectField fvar field
618 | fisOptional = [| case $(varE fvar) of
620 Just v -> [( $nameE, JSON.showJSON v)]
622 | otherwise = case fieldShow field of
623 Nothing -> [| [( $nameE, JSON.showJSON $fvarE)] |]
624 Just fn -> [| let (actual, extra) = $fn $fvarE
625 in extra ++ [( $nameE, JSON.showJSON actual)]
627 where fisOptional = fieldIsOptional field
628 nameE = stringE (fieldName field)
631 objectShowJSON :: String -> Q Dec
632 objectShowJSON name = do
633 body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |]
634 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
636 genLoadObject :: (Field -> Q (Name, Stmt))
637 -> String -> [Field] -> Q (Dec, Dec)
638 genLoadObject load_fn sname fields = do
639 let name = mkName sname
640 funname = mkName $ "load" ++ sname
643 opid = mkName "op_id"
644 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
645 (JSON.readJSON $(varE arg1)) |]
646 fbinds <- mapM load_fn fields
647 let (fnames, fstmts) = unzip fbinds
648 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
649 fstmts' = st1:fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
650 sigt <- [t| JSON.JSValue -> JSON.Result $(conT name) |]
651 return $ (SigD funname sigt,
652 FunD funname [Clause [VarP arg1] (NormalB (DoE fstmts')) []])
654 loadObjectField :: Field -> Q (Name, Stmt)
655 loadObjectField field = do
656 let name = fieldVariable field
658 -- these are used in all patterns below
659 let objvar = varNameE "o"
660 objfield = stringE (fieldName field)
662 if fieldIsOptional field
663 then [| $(varNameE "maybeFromObj") $objvar $objfield |]
664 else case fieldDefault field of
666 [| $(varNameE "fromObjWithDefault") $objvar
668 Nothing -> [| $(varNameE "fromObj") $objvar $objfield |]
669 bexp <- loadFn field loadexp objvar
671 return (fvar, BindS (VarP fvar) bexp)
673 objectReadJSON :: String -> Q Dec
674 objectReadJSON name = do
676 body <- [| case JSON.readJSON $(varE s) of
677 JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s'
679 JSON.Error $ "Can't parse value for type " ++
680 $(stringE name) ++ ": " ++ e
682 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
684 -- * Inheritable parameter tables implementation
686 -- | Compute parameter type names.
687 paramTypeNames :: String -> (String, String)
688 paramTypeNames root = ("Filled" ++ root ++ "Params",
689 "Partial" ++ root ++ "Params")
691 -- | Compute information about the type of a parameter field.
692 paramFieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
693 paramFieldTypeInfo field_pfx fd = do
694 t <- actualFieldType fd
695 let n = mkName . (++ "P") . (field_pfx ++) .
697 return (n, NotStrict, AppT (ConT ''Maybe) t)
699 -- | Build a parameter declaration.
701 -- This function builds two different data structures: a /filled/ one,
702 -- in which all fields are required, and a /partial/ one, in which all
703 -- fields are optional. Due to the current record syntax issues, the
704 -- fields need to be named differrently for the two structures, so the
705 -- partial ones get a /P/ suffix.
706 buildParam :: String -> String -> [Field] -> Q [Dec]
707 buildParam sname field_pfx fields = do
708 let (sname_f, sname_p) = paramTypeNames sname
709 name_f = mkName sname_f
710 name_p = mkName sname_p
711 fields_f <- mapM (fieldTypeInfo field_pfx) fields
712 fields_p <- mapM (paramFieldTypeInfo field_pfx) fields
713 let decl_f = RecC name_f fields_f
714 decl_p = RecC name_p fields_p
715 let declF = DataD [] name_f [] [decl_f] [''Show, ''Read, ''Eq]
716 declP = DataD [] name_p [] [decl_p] [''Show, ''Read, ''Eq]
717 ser_decls_f <- buildObjectSerialisation sname_f fields
718 ser_decls_p <- buildPParamSerialisation sname_p fields
719 fill_decls <- fillParam sname field_pfx fields
720 return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls
722 buildPParamSerialisation :: String -> [Field] -> Q [Dec]
723 buildPParamSerialisation sname fields = do
724 let name = mkName sname
725 savedecls <- genSaveObject savePParamField sname fields
726 (loadsig, loadfn) <- genLoadObject loadPParamField sname fields
727 shjson <- objectShowJSON sname
728 rdjson <- objectReadJSON sname
729 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
731 return $ savedecls ++ [loadsig, loadfn, instdecl]
733 savePParamField :: Name -> Field -> Q Exp
734 savePParamField fvar field = do
736 let actualVal = mkName "v"
737 normalexpr <- saveObjectField actualVal field
738 -- we have to construct the block here manually, because we can't
740 return $ CaseE (VarE fvar) [ Match (ConP 'Nothing [])
741 (NormalB (ConE '[])) []
742 , Match (ConP 'Just [VarP actualVal])
743 (NormalB normalexpr) []
745 loadPParamField :: Field -> Q (Name, Stmt)
746 loadPParamField field = do
748 let name = fieldName field
750 -- these are used in all patterns below
751 let objvar = varNameE "o"
752 objfield = stringE name
753 loadexp = [| $(varNameE "maybeFromObj") $objvar $objfield |]
754 bexp <- loadFn field loadexp objvar
755 return (fvar, BindS (VarP fvar) bexp)
757 -- | Builds a simple declaration of type @n_x = fromMaybe f_x p_x@.
758 buildFromMaybe :: String -> Q Dec
759 buildFromMaybe fname =
760 valD (varP (mkName $ "n_" ++ fname))
761 (normalB [| $(varNameE "fromMaybe")
762 $(varNameE $ "f_" ++ fname)
763 $(varNameE $ "p_" ++ fname) |]) []
765 fillParam :: String -> String -> [Field] -> Q [Dec]
766 fillParam sname field_pfx fields = do
767 let fnames = map (\fd -> field_pfx ++ fieldRecordName fd) fields
768 (sname_f, sname_p) = paramTypeNames sname
771 name_f = mkName sname_f
772 name_p = mkName sname_p
773 fun_name = mkName $ "fill" ++ sname ++ "Params"
774 le_full = ValD (ConP name_f (map (VarP . mkName . ("f_" ++)) fnames))
775 (NormalB . VarE . mkName $ oname_f) []
776 le_part = ValD (ConP name_p (map (VarP . mkName . ("p_" ++)) fnames))
777 (NormalB . VarE . mkName $ oname_p) []
778 obj_new = foldl (\accu vname -> AppE accu (VarE vname)) (ConE name_f)
779 $ map (mkName . ("n_" ++)) fnames
780 le_new <- mapM buildFromMaybe fnames
781 funt <- [t| $(conT name_f) -> $(conT name_p) -> $(conT name_f) |]
782 let sig = SigD fun_name funt
783 fclause = Clause [VarP (mkName oname_f), VarP (mkName oname_p)]
784 (NormalB $ LetE (le_full:le_part:le_new) obj_new) []
785 fun = FunD fun_name [fclause]