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
58 import Control.Monad (liftM, liftM2)
61 import qualified Data.Map as M
62 import qualified Data.Set as Set
63 import Language.Haskell.TH
65 import qualified Text.JSON as JSON
67 import Ganeti.HTools.JSON
71 type Container = M.Map String
73 -- | Serialised field data type.
74 data Field = Field { fieldName :: String
76 , fieldRead :: Maybe (Q Exp)
77 , fieldShow :: Maybe (Q Exp)
78 , fieldDefault :: Maybe (Q Exp)
79 , fieldConstr :: Maybe String
80 , fieldIsContainer :: Bool
81 , fieldIsOptional :: Bool
84 -- | Generates a simple field.
85 simpleField :: String -> Q Type -> Field
86 simpleField fname ftype =
87 Field { fieldName = fname
91 , fieldDefault = Nothing
92 , fieldConstr = Nothing
93 , fieldIsContainer = False
94 , fieldIsOptional = False
97 -- | Sets the renamed constructor field.
98 renameField :: String -> Field -> Field
99 renameField constrName field = field { fieldConstr = Just constrName }
101 -- | Sets the default value on a field (makes it optional with a
103 defaultField :: Q Exp -> Field -> Field
104 defaultField defval field = field { fieldDefault = Just defval }
106 -- | Marks a field optional (turning its base type into a Maybe).
107 optionalField :: Field -> Field
108 optionalField field = field { fieldIsOptional = True }
110 -- | Marks a field as a container.
111 containerField :: Field -> Field
112 containerField field = field { fieldIsContainer = True }
114 -- | Sets custom functions on a field.
115 customField :: Name -- ^ The name of the read function
116 -> Name -- ^ The name of the show function
117 -> Field -- ^ The original field
118 -> Field -- ^ Updated field
119 customField readfn showfn field =
120 field { fieldRead = Just (varE readfn), fieldShow = Just (varE showfn) }
122 fieldRecordName :: Field -> String
123 fieldRecordName (Field { fieldName = name, fieldConstr = alias }) =
124 maybe (camelCase name) id alias
126 -- | Computes the preferred variable name to use for the value of this
127 -- field. If the field has a specific constructor name, then we use a
128 -- first-letter-lowercased version of that; otherwise, we simply use
129 -- the field name. See also 'fieldRecordName'.
130 fieldVariable :: Field -> String
132 case (fieldConstr f) of
133 Just name -> ensureLower name
136 actualFieldType :: Field -> Q Type
137 actualFieldType f | fieldIsContainer f = [t| Container $t |]
138 | fieldIsOptional f = [t| Maybe $t |]
140 where t = fieldType f
142 checkNonOptDef :: (Monad m) => Field -> m ()
143 checkNonOptDef (Field { fieldIsOptional = True, fieldName = name }) =
144 fail $ "Optional field " ++ name ++ " used in parameter declaration"
145 checkNonOptDef (Field { fieldDefault = (Just _), fieldName = name }) =
146 fail $ "Default field " ++ name ++ " used in parameter declaration"
147 checkNonOptDef _ = return ()
149 -- | Produces the expression that will de-serialise a given
150 -- field. Since some custom parsing functions might need to use the
151 -- entire object, we do take and pass the object to any custom read
153 loadFn :: Field -- ^ The field definition
154 -> Q Exp -- ^ The value of the field as existing in the JSON message
155 -> Q Exp -- ^ The entire object in JSON object format
156 -> Q Exp -- ^ Resulting expression
157 loadFn (Field { fieldIsContainer = True }) expr _ =
158 [| $expr >>= readContainer |]
159 loadFn (Field { fieldRead = Just readfn }) expr o = [| $expr >>= $readfn $o |]
160 loadFn _ expr _ = expr
162 -- * Common field declarations
164 timeStampFields :: [Field]
166 [ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |]
167 , defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |]
170 serialFields :: [Field]
172 [ renameField "Serial" $ simpleField "serial_no" [t| Int |] ]
174 uuidFields :: [Field]
175 uuidFields = [ simpleField "uuid" [t| String |] ]
177 -- | Tag field description.
178 tagsFields :: [Field]
179 tagsFields = [ defaultField [| Set.empty |] $
180 simpleField "tags" [t| Set.Set String |] ]
182 -- * Helper functions
184 -- | Ensure first letter is lowercase.
186 -- Used to convert type name to function prefix, e.g. in @data Aa ->
188 ensureLower :: String -> String
190 ensureLower (x:xs) = toLower x:xs
192 -- | Ensure first letter is uppercase.
194 -- Used to convert constructor name to component
195 ensureUpper :: String -> String
197 ensureUpper (x:xs) = toUpper x:xs
199 -- | Helper for quoted expressions.
200 varNameE :: String -> Q Exp
201 varNameE = varE . mkName
203 -- | showJSON as an expression, for reuse.
205 showJSONE = varNameE "showJSON"
207 -- | ToRaw function name.
208 toRawName :: String -> Name
209 toRawName = mkName . (++ "ToRaw") . ensureLower
211 -- | FromRaw function name.
212 fromRawName :: String -> Name
213 fromRawName = mkName . (++ "FromRaw") . ensureLower
215 -- | Converts a name to it's varE/litE representations.
217 reprE :: Either String Name -> Q Exp
218 reprE = either stringE varE
220 -- | Smarter function application.
222 -- This does simply f x, except that if is 'id', it will skip it, in
223 -- order to generate more readable code when using -ddump-splices.
224 appFn :: Exp -> Exp -> Exp
225 appFn f x | f == VarE 'id = x
226 | otherwise = AppE f x
228 -- | Container loader
229 readContainer :: (Monad m, JSON.JSON a) =>
230 JSON.JSObject JSON.JSValue -> m (Container a)
231 readContainer obj = do
232 let kjvlist = JSON.fromJSObject obj
233 kalist <- mapM (\(k, v) -> fromKeyValue k v >>= \a -> return (k, a)) kjvlist
234 return $ M.fromList kalist
236 -- | Container dumper
237 showContainer :: (JSON.JSON a) => Container a -> JSON.JSValue
238 showContainer = JSON.makeObj . map (second JSON.showJSON) . M.toList
240 -- * Template code for simple raw type-equivalent ADTs
242 -- | Generates a data type declaration.
244 -- The type will have a fixed list of instances.
245 strADTDecl :: Name -> [String] -> Dec
246 strADTDecl name constructors =
248 (map (flip NormalC [] . mkName) constructors)
249 [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
251 -- | Generates a toRaw function.
253 -- This generates a simple function of the form:
256 -- nameToRaw :: Name -> /traw/
257 -- nameToRaw Cons1 = var1
258 -- nameToRaw Cons2 = \"value2\"
260 genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec]
261 genToRaw traw fname tname constructors = do
262 let sigt = AppT (AppT ArrowT (ConT tname)) (ConT traw)
263 -- the body clauses, matching on the constructor and returning the
265 clauses <- mapM (\(c, v) -> clause [recP (mkName c) []]
266 (normalB (reprE v)) []) constructors
267 return [SigD fname sigt, FunD fname clauses]
269 -- | Generates a fromRaw function.
271 -- The function generated is monadic and can fail parsing the
272 -- raw value. It is of the form:
275 -- nameFromRaw :: (Monad m) => /traw/ -> m Name
276 -- nameFromRaw s | s == var1 = Cons1
277 -- | s == \"value2\" = Cons2
278 -- | otherwise = fail /.../
280 genFromRaw :: Name -> Name -> Name -> [(String, Name)] -> Q [Dec]
281 genFromRaw traw fname tname constructors = do
282 -- signature of form (Monad m) => String -> m $name
283 sigt <- [t| (Monad m) => $(conT traw) -> m $(conT tname) |]
284 -- clauses for a guarded pattern
285 let varp = mkName "s"
287 clauses <- mapM (\(c, v) -> do
288 -- the clause match condition
289 g <- normalG [| $varpe == $(varE v) |]
291 r <- [| return $(conE (mkName c)) |]
292 return (g, r)) constructors
293 -- the otherwise clause (fallback)
295 g <- normalG [| otherwise |]
296 r <- [|fail ("Invalid string value for type " ++
297 $(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
299 let fun = FunD fname [Clause [VarP varp]
300 (GuardedB (clauses++[oth_clause])) []]
301 return [SigD fname sigt, fun]
303 -- | Generates a data type from a given raw format.
305 -- The format is expected to multiline. The first line contains the
306 -- type name, and the rest of the lines must contain two words: the
307 -- constructor name and then the string representation of the
308 -- respective constructor.
310 -- The function will generate the data type declaration, and then two
313 -- * /name/ToRaw, which converts the type to a raw type
315 -- * /name/FromRaw, which (monadically) converts from a raw type to the type
317 -- Note that this is basically just a custom show/read instance,
319 declareADT :: Name -> String -> [(String, Name)] -> Q [Dec]
320 declareADT traw sname cons = do
321 let name = mkName sname
322 ddecl = strADTDecl name (map fst cons)
323 -- process cons in the format expected by genToRaw
324 cons' = map (\(a, b) -> (a, Right b)) cons
325 toraw <- genToRaw traw (toRawName sname) name cons'
326 fromraw <- genFromRaw traw (fromRawName sname) name cons
327 return $ ddecl:toraw ++ fromraw
329 declareIADT :: String -> [(String, Name)] -> Q [Dec]
330 declareIADT = declareADT ''Int
332 declareSADT :: String -> [(String, Name)] -> Q [Dec]
333 declareSADT = declareADT ''String
335 -- | Creates the showJSON member of a JSON instance declaration.
337 -- This will create what is the equivalent of:
340 -- showJSON = showJSON . /name/ToRaw
343 -- in an instance JSON /name/ declaration
344 genShowJSON :: String -> Q Dec
345 genShowJSON name = do
346 body <- [| JSON.showJSON . $(varE (toRawName name)) |]
347 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
349 -- | Creates the readJSON member of a JSON instance declaration.
351 -- This will create what is the equivalent of:
354 -- readJSON s = case readJSON s of
355 -- Ok s' -> /name/FromRaw s'
356 -- Error e -> Error /description/
359 -- in an instance JSON /name/ declaration
360 genReadJSON :: String -> Q Dec
361 genReadJSON name = do
363 body <- [| case JSON.readJSON $(varE s) of
364 JSON.Ok s' -> $(varE (fromRawName name)) s'
366 JSON.Error $ "Can't parse raw value for type " ++
367 $(stringE name) ++ ": " ++ e ++ " from " ++
370 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
372 -- | Generates a JSON instance for a given type.
374 -- This assumes that the /name/ToRaw and /name/FromRaw functions
375 -- have been defined as by the 'declareSADT' function.
376 makeJSONInstance :: Name -> Q [Dec]
377 makeJSONInstance name = do
378 let base = nameBase name
379 showJ <- genShowJSON base
380 readJ <- genReadJSON base
381 return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [readJ,showJ]]
383 -- * Template code for opcodes
385 -- | Transforms a CamelCase string into an_underscore_based_one.
386 deCamelCase :: String -> String
388 intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
390 -- | Transform an underscore_name into a CamelCase one.
391 camelCase :: String -> String
392 camelCase = concatMap (ensureUpper . drop 1) .
393 groupBy (\_ b -> b /= '_') . ('_':)
395 -- | Computes the name of a given constructor.
396 constructorName :: Con -> Q Name
397 constructorName (NormalC name _) = return name
398 constructorName (RecC name _) = return name
399 constructorName x = fail $ "Unhandled constructor " ++ show x
401 -- | Builds the generic constructor-to-string function.
403 -- This generates a simple function of the following form:
406 -- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
407 -- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
410 -- This builds a custom list of name/string pairs and then uses
411 -- 'genToRaw' to actually generate the function
412 genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
413 genConstrToStr trans_fun name fname = do
414 TyConI (DataD _ _ _ cons _) <- reify name
415 cnames <- mapM (liftM nameBase . constructorName) cons
416 let svalues = map (Left . trans_fun) cnames
417 genToRaw ''String (mkName fname) name $ zip cnames svalues
419 -- | Constructor-to-string for OpCode.
420 genOpID :: Name -> String -> Q [Dec]
421 genOpID = genConstrToStr deCamelCase
423 -- | OpCode parameter (field) type.
424 type OpParam = (String, Q Type, Q Exp)
426 -- | Generates the OpCode data type.
428 -- This takes an opcode logical definition, and builds both the
429 -- datatype and the JSON serialisation out of it. We can't use a
430 -- generic serialisation since we need to be compatible with Ganeti's
431 -- own, so we have a few quirks to work around.
432 genOpCode :: String -- ^ Type name to use
433 -> [(String, [Field])] -- ^ Constructor name and parameters
435 genOpCode name cons = do
436 decl_d <- mapM (\(cname, fields) -> do
437 -- we only need the type of the field, without Q
438 fields' <- mapM actualFieldType fields
439 let fields'' = zip (repeat NotStrict) fields'
440 return $ NormalC (mkName cname) fields'')
442 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
444 (savesig, savefn) <- genSaveOpCode cons
445 (loadsig, loadfn) <- genLoadOpCode cons
446 return [declD, loadsig, loadfn, savesig, savefn]
448 -- | Checks whether a given parameter is options.
450 -- This requires that it's a 'Maybe'.
451 isOptional :: Type -> Bool
452 isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
455 -- | Generates the \"save\" clause for an entire opcode constructor.
457 -- This matches the opcode with variables named the same as the
458 -- constructor fields (just so that the spliced in code looks nicer),
459 -- and passes those name plus the parameter definition to 'saveObjectField'.
460 saveConstructor :: String -- ^ The constructor name
461 -> [Field] -- ^ The parameter definitions for this
463 -> Q Clause -- ^ Resulting clause
464 saveConstructor sname fields = do
465 let cname = mkName sname
466 let fnames = map (mkName . fieldVariable) fields
467 let pat = conP cname (map varP fnames)
468 let felems = map (uncurry saveObjectField) (zip fnames fields)
469 -- now build the OP_ID serialisation
470 opid = [| [( $(stringE "OP_ID"),
471 JSON.showJSON $(stringE . deCamelCase $ sname) )] |]
472 flist = listE (opid:felems)
473 -- and finally convert all this to a json object
474 flist' = [| $(varNameE "makeObj") (concat $flist) |]
475 clause [pat] (normalB flist') []
477 -- | Generates the main save opcode function.
479 -- This builds a per-constructor match clause that contains the
480 -- respective constructor-serialisation code.
481 genSaveOpCode :: [(String, [Field])] -> Q (Dec, Dec)
482 genSaveOpCode opdefs = do
483 cclauses <- mapM (uncurry saveConstructor) opdefs
484 let fname = mkName "saveOpCode"
485 sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |]
486 return $ (SigD fname sigt, FunD fname cclauses)
488 loadConstructor :: String -> [Field] -> Q Exp
489 loadConstructor sname fields = do
490 let name = mkName sname
491 fbinds <- mapM loadObjectField fields
492 let (fnames, fstmts) = unzip fbinds
493 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
494 fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
497 genLoadOpCode :: [(String, [Field])] -> Q (Dec, Dec)
498 genLoadOpCode opdefs = do
499 let fname = mkName "loadOpCode"
502 opid = mkName "op_id"
503 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
504 (JSON.readJSON $(varE arg1)) |]
505 st2 <- bindS (varP opid) [| $(varNameE "fromObj")
506 $(varE objname) $(stringE "OP_ID") |]
507 -- the match results (per-constructor blocks)
508 mexps <- mapM (uncurry loadConstructor) opdefs
509 fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
510 let mpats = map (\(me, c) ->
511 let mp = LitP . StringL . deCamelCase . fst $ c
512 in Match mp (NormalB me) []
514 defmatch = Match WildP (NormalB fails) []
515 cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
516 body = DoE [st1, st2, cst]
517 sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
518 return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
520 -- * Template code for luxi
522 -- | Constructor-to-string for LuxiOp.
523 genStrOfOp :: Name -> String -> Q [Dec]
524 genStrOfOp = genConstrToStr id
526 -- | Constructor-to-string for MsgKeys.
527 genStrOfKey :: Name -> String -> Q [Dec]
528 genStrOfKey = genConstrToStr ensureLower
530 -- | LuxiOp parameter type.
531 type LuxiParam = (String, Q Type, Q Exp)
533 -- | Generates the LuxiOp data type.
535 -- This takes a Luxi operation definition and builds both the
536 -- datatype and the function trnasforming the arguments to JSON.
537 -- We can't use anything less generic, because the way different
538 -- operations are serialized differs on both parameter- and top-level.
540 -- There are three things to be defined for each parameter:
546 -- * operation; this is the operation performed on the parameter before
549 genLuxiOp :: String -> [(String, [LuxiParam])] -> Q [Dec]
550 genLuxiOp name cons = do
551 decl_d <- mapM (\(cname, fields) -> do
552 fields' <- mapM (\(_, qt, _) ->
553 qt >>= \t -> return (NotStrict, t))
555 return $ NormalC (mkName cname) fields')
557 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
558 (savesig, savefn) <- genSaveLuxiOp cons
559 req_defs <- declareSADT "LuxiReq" .
560 map (\(str, _) -> ("Req" ++ str, mkName ("luxiReq" ++ str))) $
562 return $ [declD, savesig, savefn] ++ req_defs
564 -- | Generates the \"save\" expression for a single luxi parameter.
565 saveLuxiField :: Name -> LuxiParam -> Q Exp
566 saveLuxiField fvar (_, qt, fn) =
567 [| JSON.showJSON ( $(liftM2 appFn fn $ varE fvar) ) |]
569 -- | Generates the \"save\" clause for entire LuxiOp constructor.
570 saveLuxiConstructor :: (String, [LuxiParam]) -> Q Clause
571 saveLuxiConstructor (sname, fields) = do
572 let cname = mkName sname
573 fnames = map (\(nm, _, _) -> mkName nm) fields
574 pat = conP cname (map varP fnames)
575 flist = map (uncurry saveLuxiField) (zip fnames fields)
576 finval = if null flist
577 then [| JSON.showJSON () |]
578 else [| JSON.showJSON $(listE flist) |]
579 clause [pat] (normalB finval) []
581 -- | Generates the main save LuxiOp function.
582 genSaveLuxiOp :: [(String, [LuxiParam])]-> Q (Dec, Dec)
583 genSaveLuxiOp opdefs = do
584 sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
585 let fname = mkName "opToArgs"
586 cclauses <- mapM saveLuxiConstructor opdefs
587 return $ (SigD fname sigt, FunD fname cclauses)
589 -- * "Objects" functionality
591 -- | Extract the field's declaration from a Field structure.
592 fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
593 fieldTypeInfo field_pfx fd = do
594 t <- actualFieldType fd
595 let n = mkName . (field_pfx ++) . fieldRecordName $ fd
596 return (n, NotStrict, t)
598 -- | Build an object declaration.
599 buildObject :: String -> String -> [Field] -> Q [Dec]
600 buildObject sname field_pfx fields = do
601 let name = mkName sname
602 fields_d <- mapM (fieldTypeInfo field_pfx) fields
603 let decl_d = RecC name fields_d
604 let declD = DataD [] name [] [decl_d] [''Show, ''Read, ''Eq]
605 ser_decls <- buildObjectSerialisation sname fields
606 return $ declD:ser_decls
608 buildObjectSerialisation :: String -> [Field] -> Q [Dec]
609 buildObjectSerialisation sname fields = do
610 let name = mkName sname
611 savedecls <- genSaveObject saveObjectField sname fields
612 (loadsig, loadfn) <- genLoadObject loadObjectField sname fields
613 shjson <- objectShowJSON sname
614 rdjson <- objectReadJSON sname
615 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
617 return $ savedecls ++ [loadsig, loadfn, instdecl]
619 genSaveObject :: (Name -> Field -> Q Exp)
620 -> String -> [Field] -> Q [Dec]
621 genSaveObject save_fn sname fields = do
622 let name = mkName sname
623 let fnames = map (mkName . fieldVariable) fields
624 let pat = conP name (map varP fnames)
625 let tdname = mkName ("toDict" ++ sname)
626 tdsigt <- [t| $(conT name) -> [(String, JSON.JSValue)] |]
628 let felems = map (uncurry save_fn) (zip fnames fields)
630 -- and finally convert all this to a json object
631 tdlist = [| concat $flist |]
633 tclause <- clause [pat] (normalB tdlist) []
634 cclause <- [| $(varNameE "makeObj") . $(varE tdname) |]
635 let fname = mkName ("save" ++ sname)
636 sigt <- [t| $(conT name) -> JSON.JSValue |]
637 return [SigD tdname tdsigt, FunD tdname [tclause],
638 SigD fname sigt, ValD (VarP fname) (NormalB cclause) []]
640 saveObjectField :: Name -> Field -> Q Exp
641 saveObjectField fvar field
642 | isContainer = [| [( $nameE , JSON.showJSON . showContainer $ $fvarE)] |]
643 | fisOptional = [| case $(varE fvar) of
645 Just v -> [( $nameE, JSON.showJSON v)]
647 | otherwise = case fieldShow field of
648 Nothing -> [| [( $nameE, JSON.showJSON $fvarE)] |]
649 Just fn -> [| let (actual, extra) = $fn $fvarE
650 in extra ++ [( $nameE, JSON.showJSON actual)]
652 where isContainer = fieldIsContainer field
653 fisOptional = fieldIsOptional field
654 nameE = stringE (fieldName field)
657 objectShowJSON :: String -> Q Dec
658 objectShowJSON name = do
659 body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |]
660 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
662 genLoadObject :: (Field -> Q (Name, Stmt))
663 -> String -> [Field] -> Q (Dec, Dec)
664 genLoadObject load_fn sname fields = do
665 let name = mkName sname
666 funname = mkName $ "load" ++ sname
669 opid = mkName "op_id"
670 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
671 (JSON.readJSON $(varE arg1)) |]
672 fbinds <- mapM load_fn fields
673 let (fnames, fstmts) = unzip fbinds
674 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
675 fstmts' = st1:fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
676 sigt <- [t| JSON.JSValue -> JSON.Result $(conT name) |]
677 return $ (SigD funname sigt,
678 FunD funname [Clause [VarP arg1] (NormalB (DoE fstmts')) []])
680 loadObjectField :: Field -> Q (Name, Stmt)
681 loadObjectField field = do
682 let name = fieldVariable field
684 -- these are used in all patterns below
685 let objvar = varNameE "o"
686 objfield = stringE (fieldName field)
688 if fieldIsOptional field
689 then [| $(varNameE "maybeFromObj") $objvar $objfield |]
690 else case fieldDefault field of
692 [| $(varNameE "fromObjWithDefault") $objvar
694 Nothing -> [| $(varNameE "fromObj") $objvar $objfield |]
695 bexp <- loadFn field loadexp objvar
697 return (fvar, BindS (VarP fvar) bexp)
699 objectReadJSON :: String -> Q Dec
700 objectReadJSON name = do
702 body <- [| case JSON.readJSON $(varE s) of
703 JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s'
705 JSON.Error $ "Can't parse value for type " ++
706 $(stringE name) ++ ": " ++ e
708 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
710 -- * Inheritable parameter tables implementation
712 -- | Compute parameter type names.
713 paramTypeNames :: String -> (String, String)
714 paramTypeNames root = ("Filled" ++ root ++ "Params",
715 "Partial" ++ root ++ "Params")
717 -- | Compute information about the type of a parameter field.
718 paramFieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
719 paramFieldTypeInfo field_pfx fd = do
720 t <- actualFieldType fd
721 let n = mkName . (++ "P") . (field_pfx ++) .
723 return (n, NotStrict, AppT (ConT ''Maybe) t)
725 -- | Build a parameter declaration.
727 -- This function builds two different data structures: a /filled/ one,
728 -- in which all fields are required, and a /partial/ one, in which all
729 -- fields are optional. Due to the current record syntax issues, the
730 -- fields need to be named differrently for the two structures, so the
731 -- partial ones get a /P/ suffix.
732 buildParam :: String -> String -> [Field] -> Q [Dec]
733 buildParam sname field_pfx fields = do
734 let (sname_f, sname_p) = paramTypeNames sname
735 name_f = mkName sname_f
736 name_p = mkName sname_p
737 fields_f <- mapM (fieldTypeInfo field_pfx) fields
738 fields_p <- mapM (paramFieldTypeInfo field_pfx) fields
739 let decl_f = RecC name_f fields_f
740 decl_p = RecC name_p fields_p
741 let declF = DataD [] name_f [] [decl_f] [''Show, ''Read, ''Eq]
742 declP = DataD [] name_p [] [decl_p] [''Show, ''Read, ''Eq]
743 ser_decls_f <- buildObjectSerialisation sname_f fields
744 ser_decls_p <- buildPParamSerialisation sname_p fields
745 fill_decls <- fillParam sname field_pfx fields
746 return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls
748 buildPParamSerialisation :: String -> [Field] -> Q [Dec]
749 buildPParamSerialisation sname fields = do
750 let name = mkName sname
751 savedecls <- genSaveObject savePParamField sname fields
752 (loadsig, loadfn) <- genLoadObject loadPParamField sname fields
753 shjson <- objectShowJSON sname
754 rdjson <- objectReadJSON sname
755 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
757 return $ savedecls ++ [loadsig, loadfn, instdecl]
759 savePParamField :: Name -> Field -> Q Exp
760 savePParamField fvar field = do
762 let actualVal = mkName "v"
763 normalexpr <- saveObjectField actualVal field
764 -- we have to construct the block here manually, because we can't
766 return $ CaseE (VarE fvar) [ Match (ConP 'Nothing [])
767 (NormalB (ConE '[])) []
768 , Match (ConP 'Just [VarP actualVal])
769 (NormalB normalexpr) []
771 loadPParamField :: Field -> Q (Name, Stmt)
772 loadPParamField field = do
774 let name = fieldName field
776 -- these are used in all patterns below
777 let objvar = varNameE "o"
778 objfield = stringE name
779 loadexp = [| $(varNameE "maybeFromObj") $objvar $objfield |]
780 bexp <- loadFn field loadexp objvar
781 return (fvar, BindS (VarP fvar) bexp)
783 -- | Builds a simple declaration of type @n_x = fromMaybe f_x p_x@.
784 buildFromMaybe :: String -> Q Dec
785 buildFromMaybe fname =
786 valD (varP (mkName $ "n_" ++ fname))
787 (normalB [| $(varNameE "fromMaybe")
788 $(varNameE $ "f_" ++ fname)
789 $(varNameE $ "p_" ++ fname) |]) []
791 fillParam :: String -> String -> [Field] -> Q [Dec]
792 fillParam sname field_pfx fields = do
793 let fnames = map (\fd -> field_pfx ++ fieldRecordName fd) fields
794 (sname_f, sname_p) = paramTypeNames sname
797 name_f = mkName sname_f
798 name_p = mkName sname_p
799 fun_name = mkName $ "fill" ++ sname ++ "Params"
800 le_full = ValD (ConP name_f (map (VarP . mkName . ("f_" ++)) fnames))
801 (NormalB . VarE . mkName $ oname_f) []
802 le_part = ValD (ConP name_p (map (VarP . mkName . ("p_" ++)) fnames))
803 (NormalB . VarE . mkName $ oname_p) []
804 obj_new = foldl (\accu vname -> AppE accu (VarE vname)) (ConE name_f)
805 $ map (mkName . ("n_" ++)) fnames
806 le_new <- mapM buildFromMaybe fnames
807 funt <- [t| $(conT name_f) -> $(conT name_p) -> $(conT name_f) |]
808 let sig = SigD fun_name funt
809 fclause = Clause [VarP (mkName oname_f), VarP (mkName oname_p)]
810 (NormalB $ LetE (le_full:le_part:le_new) obj_new) []
811 fun = FunD fun_name [fclause]