1 {-# LANGUAGE TemplateHaskell #-}
3 {-| TemplateHaskell helper for Ganeti Haskell code.
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
53 , buildObjectSerialisation
58 import Control.Monad (liftM)
61 import Data.Maybe (fromMaybe)
62 import qualified Data.Set as Set
63 import Language.Haskell.TH
65 import qualified Text.JSON as JSON
69 -- | Class of objects that can be converted to 'JSObject'
71 class DictObject a where
72 toDict :: a -> [(String, JSON.JSValue)]
74 -- | Serialised field data type.
75 data Field = Field { fieldName :: String
77 , fieldRead :: Maybe (Q Exp)
78 , fieldShow :: Maybe (Q Exp)
79 , fieldDefault :: Maybe (Q Exp)
80 , fieldConstr :: Maybe String
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 , fieldIsOptional = False
96 -- | Sets the renamed constructor field.
97 renameField :: String -> Field -> Field
98 renameField constrName field = field { fieldConstr = Just constrName }
100 -- | Sets the default value on a field (makes it optional with a
102 defaultField :: Q Exp -> Field -> Field
103 defaultField defval field = field { fieldDefault = Just defval }
105 -- | Marks a field optional (turning its base type into a Maybe).
106 optionalField :: Field -> Field
107 optionalField field = field { fieldIsOptional = True }
109 -- | Sets custom functions on a field.
110 customField :: Name -- ^ The name of the read function
111 -> Name -- ^ The name of the show function
112 -> Field -- ^ The original field
113 -> Field -- ^ Updated field
114 customField readfn showfn field =
115 field { fieldRead = Just (varE readfn), fieldShow = Just (varE showfn) }
117 -- | Computes the record name for a given field, based on either the
118 -- string value in the JSON serialisation or the custom named if any
120 fieldRecordName :: Field -> String
121 fieldRecordName (Field { fieldName = name, fieldConstr = alias }) =
122 fromMaybe (camelCase name) 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
132 _ -> map (\c -> if c == '-' then '_' else c) $ fieldName f
134 actualFieldType :: Field -> Q Type
135 actualFieldType f | fieldIsOptional f = [t| Maybe $t |]
137 where t = fieldType f
139 checkNonOptDef :: (Monad m) => Field -> m ()
140 checkNonOptDef (Field { fieldIsOptional = True, fieldName = name }) =
141 fail $ "Optional field " ++ name ++ " used in parameter declaration"
142 checkNonOptDef (Field { fieldDefault = (Just _), fieldName = name }) =
143 fail $ "Default field " ++ name ++ " used in parameter declaration"
144 checkNonOptDef _ = return ()
146 -- | Produces the expression that will de-serialise a given
147 -- field. Since some custom parsing functions might need to use the
148 -- entire object, we do take and pass the object to any custom read
150 loadFn :: Field -- ^ The field definition
151 -> Q Exp -- ^ The value of the field as existing in the JSON message
152 -> Q Exp -- ^ The entire object in JSON object format
153 -> Q Exp -- ^ Resulting expression
154 loadFn (Field { fieldRead = Just readfn }) expr o = [| $expr >>= $readfn $o |]
155 loadFn _ expr _ = expr
157 -- * Common field declarations
159 -- | Timestamp fields description.
160 timeStampFields :: [Field]
162 [ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |]
163 , defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |]
166 -- | Serial number fields description.
167 serialFields :: [Field]
169 [ renameField "Serial" $ simpleField "serial_no" [t| Int |] ]
171 -- | UUID fields description.
172 uuidFields :: [Field]
173 uuidFields = [ simpleField "uuid" [t| String |] ]
175 -- | Tag set type alias.
176 type TagSet = Set.Set String
178 -- | Tag field description.
179 tagsFields :: [Field]
180 tagsFields = [ defaultField [| Set.empty |] $
181 simpleField "tags" [t| TagSet |] ]
183 -- * Helper functions
185 -- | Ensure first letter is lowercase.
187 -- Used to convert type name to function prefix, e.g. in @data Aa ->
189 ensureLower :: String -> String
191 ensureLower (x:xs) = toLower x:xs
193 -- | Ensure first letter is uppercase.
195 -- Used to convert constructor name to component
196 ensureUpper :: String -> String
198 ensureUpper (x:xs) = toUpper x:xs
200 -- | Helper for quoted expressions.
201 varNameE :: String -> Q Exp
202 varNameE = varE . mkName
204 -- | showJSON as an expression, for reuse.
206 showJSONE = varNameE "showJSON"
208 -- | ToRaw function name.
209 toRawName :: String -> Name
210 toRawName = mkName . (++ "ToRaw") . ensureLower
212 -- | FromRaw function name.
213 fromRawName :: String -> Name
214 fromRawName = mkName . (++ "FromRaw") . ensureLower
216 -- | 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 -- * Template code for simple raw type-equivalent ADTs
230 -- | Generates a data type declaration.
232 -- The type will have a fixed list of instances.
233 strADTDecl :: Name -> [String] -> Dec
234 strADTDecl name constructors =
236 (map (flip NormalC [] . mkName) constructors)
237 [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
239 -- | Generates a toRaw function.
241 -- This generates a simple function of the form:
244 -- nameToRaw :: Name -> /traw/
245 -- nameToRaw Cons1 = var1
246 -- nameToRaw Cons2 = \"value2\"
248 genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec]
249 genToRaw traw fname tname constructors = do
250 let sigt = AppT (AppT ArrowT (ConT tname)) (ConT traw)
251 -- the body clauses, matching on the constructor and returning the
253 clauses <- mapM (\(c, v) -> clause [recP (mkName c) []]
254 (normalB (reprE v)) []) constructors
255 return [SigD fname sigt, FunD fname clauses]
257 -- | Generates a fromRaw function.
259 -- The function generated is monadic and can fail parsing the
260 -- raw value. It is of the form:
263 -- nameFromRaw :: (Monad m) => /traw/ -> m Name
264 -- nameFromRaw s | s == var1 = Cons1
265 -- | s == \"value2\" = Cons2
266 -- | otherwise = fail /.../
268 genFromRaw :: Name -> Name -> Name -> [(String, Name)] -> Q [Dec]
269 genFromRaw traw fname tname constructors = do
270 -- signature of form (Monad m) => String -> m $name
271 sigt <- [t| (Monad m) => $(conT traw) -> m $(conT tname) |]
272 -- clauses for a guarded pattern
273 let varp = mkName "s"
275 clauses <- mapM (\(c, v) -> do
276 -- the clause match condition
277 g <- normalG [| $varpe == $(varE v) |]
279 r <- [| return $(conE (mkName c)) |]
280 return (g, r)) constructors
281 -- the otherwise clause (fallback)
283 g <- normalG [| otherwise |]
284 r <- [|fail ("Invalid string value for type " ++
285 $(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
287 let fun = FunD fname [Clause [VarP varp]
288 (GuardedB (clauses++[oth_clause])) []]
289 return [SigD fname sigt, fun]
291 -- | Generates a data type from a given raw format.
293 -- The format is expected to multiline. The first line contains the
294 -- type name, and the rest of the lines must contain two words: the
295 -- constructor name and then the string representation of the
296 -- respective constructor.
298 -- The function will generate the data type declaration, and then two
301 -- * /name/ToRaw, which converts the type to a raw type
303 -- * /name/FromRaw, which (monadically) converts from a raw type to the type
305 -- Note that this is basically just a custom show\/read instance,
307 declareADT :: Name -> String -> [(String, Name)] -> Q [Dec]
308 declareADT traw sname cons = do
309 let name = mkName sname
310 ddecl = strADTDecl name (map fst cons)
311 -- process cons in the format expected by genToRaw
312 cons' = map (\(a, b) -> (a, Right b)) cons
313 toraw <- genToRaw traw (toRawName sname) name cons'
314 fromraw <- genFromRaw traw (fromRawName sname) name cons
315 return $ ddecl:toraw ++ fromraw
317 declareIADT :: String -> [(String, Name)] -> Q [Dec]
318 declareIADT = declareADT ''Int
320 declareSADT :: String -> [(String, Name)] -> Q [Dec]
321 declareSADT = declareADT ''String
323 -- | Creates the showJSON member of a JSON instance declaration.
325 -- This will create what is the equivalent of:
328 -- showJSON = showJSON . /name/ToRaw
331 -- in an instance JSON /name/ declaration
332 genShowJSON :: String -> Q Dec
333 genShowJSON name = do
334 body <- [| JSON.showJSON . $(varE (toRawName name)) |]
335 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
337 -- | Creates the readJSON member of a JSON instance declaration.
339 -- This will create what is the equivalent of:
342 -- readJSON s = case readJSON s of
343 -- Ok s' -> /name/FromRaw s'
344 -- Error e -> Error /description/
347 -- in an instance JSON /name/ declaration
348 genReadJSON :: String -> Q Dec
349 genReadJSON name = do
351 body <- [| case JSON.readJSON $(varE s) of
352 JSON.Ok s' -> $(varE (fromRawName name)) s'
354 JSON.Error $ "Can't parse raw value for type " ++
355 $(stringE name) ++ ": " ++ e ++ " from " ++
358 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
360 -- | Generates a JSON instance for a given type.
362 -- This assumes that the /name/ToRaw and /name/FromRaw functions
363 -- have been defined as by the 'declareSADT' function.
364 makeJSONInstance :: Name -> Q [Dec]
365 makeJSONInstance name = do
366 let base = nameBase name
367 showJ <- genShowJSON base
368 readJ <- genReadJSON base
369 return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [readJ,showJ]]
371 -- * Template code for opcodes
373 -- | Transforms a CamelCase string into an_underscore_based_one.
374 deCamelCase :: String -> String
376 intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
378 -- | Transform an underscore_name into a CamelCase one.
379 camelCase :: String -> String
380 camelCase = concatMap (ensureUpper . drop 1) .
381 groupBy (\_ b -> b /= '_' && b /= '-') . ('_':)
383 -- | Computes the name of a given constructor.
384 constructorName :: Con -> Q Name
385 constructorName (NormalC name _) = return name
386 constructorName (RecC name _) = return name
387 constructorName x = fail $ "Unhandled constructor " ++ show x
389 -- | Extract all constructor names from a given type.
390 reifyConsNames :: Name -> Q [String]
391 reifyConsNames name = do
392 reify_result <- reify name
394 TyConI (DataD _ _ _ cons _) -> mapM (liftM nameBase . constructorName) cons
395 o -> fail $ "Unhandled name passed to reifyConsNames, expected\
396 \ type constructor but got '" ++ show o ++ "'"
398 -- | Builds the generic constructor-to-string function.
400 -- This generates a simple function of the following form:
403 -- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
404 -- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
407 -- This builds a custom list of name\/string pairs and then uses
408 -- 'genToRaw' to actually generate the function.
409 genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
410 genConstrToStr trans_fun name fname = do
411 cnames <- reifyConsNames name
412 let svalues = map (Left . trans_fun) cnames
413 genToRaw ''String (mkName fname) name $ zip cnames svalues
415 -- | Constructor-to-string for OpCode.
416 genOpID :: Name -> String -> Q [Dec]
417 genOpID = genConstrToStr deCamelCase
419 -- | Builds a list with all defined constructor names for a type.
426 -- Where the actual values of the string are the constructor names
427 -- mapped via @trans_fun@.
428 genAllConstr :: (String -> String) -> Name -> String -> Q [Dec]
429 genAllConstr trans_fun name vstr = do
430 cnames <- reifyConsNames name
431 let svalues = sort $ map trans_fun cnames
433 sig = SigD vname (AppT ListT (ConT ''String))
434 body = NormalB (ListE (map (LitE . StringL) svalues))
435 return $ [sig, ValD (VarP vname) body []]
437 -- | Generates a list of all defined opcode IDs.
438 genAllOpIDs :: Name -> String -> Q [Dec]
439 genAllOpIDs = genAllConstr deCamelCase
441 -- | OpCode parameter (field) type.
442 type OpParam = (String, Q Type, Q Exp)
444 -- | Generates the OpCode data type.
446 -- This takes an opcode logical definition, and builds both the
447 -- datatype and the JSON serialisation out of it. We can't use a
448 -- generic serialisation since we need to be compatible with Ganeti's
449 -- own, so we have a few quirks to work around.
450 genOpCode :: String -- ^ Type name to use
451 -> [(String, [Field])] -- ^ Constructor name and parameters
453 genOpCode name cons = do
454 decl_d <- mapM (\(cname, fields) -> do
455 -- we only need the type of the field, without Q
456 fields' <- mapM actualFieldType fields
457 let fields'' = zip (repeat NotStrict) fields'
458 return $ NormalC (mkName cname) fields'')
460 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
462 (savesig, savefn) <- genSaveOpCode cons
463 (loadsig, loadfn) <- genLoadOpCode cons
464 return [declD, loadsig, loadfn, savesig, savefn]
466 -- | Checks whether a given parameter is options.
468 -- This requires that it's a 'Maybe'.
469 isOptional :: Type -> Bool
470 isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
473 -- | Generates the \"save\" clause for an entire opcode constructor.
475 -- This matches the opcode with variables named the same as the
476 -- constructor fields (just so that the spliced in code looks nicer),
477 -- and passes those name plus the parameter definition to 'saveObjectField'.
478 saveConstructor :: String -- ^ The constructor name
479 -> [Field] -- ^ The parameter definitions for this
481 -> Q Clause -- ^ Resulting clause
482 saveConstructor sname fields = do
483 let cname = mkName sname
484 fnames <- mapM (newName . fieldVariable) fields
485 let pat = conP cname (map varP fnames)
486 let felems = map (uncurry saveObjectField) (zip fnames fields)
487 -- now build the OP_ID serialisation
488 opid = [| [( $(stringE "OP_ID"),
489 JSON.showJSON $(stringE . deCamelCase $ sname) )] |]
490 flist = listE (opid:felems)
491 -- and finally convert all this to a json object
492 flist' = [| $(varNameE "makeObj") (concat $flist) |]
493 clause [pat] (normalB flist') []
495 -- | Generates the main save opcode function.
497 -- This builds a per-constructor match clause that contains the
498 -- respective constructor-serialisation code.
499 genSaveOpCode :: [(String, [Field])] -> Q (Dec, Dec)
500 genSaveOpCode opdefs = do
501 cclauses <- mapM (uncurry saveConstructor) opdefs
502 let fname = mkName "saveOpCode"
503 sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |]
504 return $ (SigD fname sigt, FunD fname cclauses)
506 -- | Generates load code for a single constructor of the opcode data type.
507 loadConstructor :: String -> [Field] -> Q Exp
508 loadConstructor sname fields = do
509 let name = mkName sname
510 fbinds <- mapM loadObjectField fields
511 let (fnames, fstmts) = unzip fbinds
512 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
513 fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
516 -- | Generates the loadOpCode function.
517 genLoadOpCode :: [(String, [Field])] -> Q (Dec, Dec)
518 genLoadOpCode opdefs = do
519 let fname = mkName "loadOpCode"
522 opid = mkName "op_id"
523 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
524 (JSON.readJSON $(varE arg1)) |]
525 st2 <- bindS (varP opid) [| $(varNameE "fromObj")
526 $(varE objname) $(stringE "OP_ID") |]
527 -- the match results (per-constructor blocks)
528 mexps <- mapM (uncurry loadConstructor) opdefs
529 fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
530 let mpats = map (\(me, c) ->
531 let mp = LitP . StringL . deCamelCase . fst $ c
532 in Match mp (NormalB me) []
534 defmatch = Match WildP (NormalB fails) []
535 cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
536 body = DoE [st1, st2, cst]
537 sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
538 return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
540 -- * Template code for luxi
542 -- | Constructor-to-string for LuxiOp.
543 genStrOfOp :: Name -> String -> Q [Dec]
544 genStrOfOp = genConstrToStr id
546 -- | Constructor-to-string for MsgKeys.
547 genStrOfKey :: Name -> String -> Q [Dec]
548 genStrOfKey = genConstrToStr ensureLower
550 -- | LuxiOp parameter type.
551 type LuxiParam = (String, Q Type)
553 -- | Generates the LuxiOp data type.
555 -- This takes a Luxi operation definition and builds both the
556 -- datatype and the function trnasforming the arguments to JSON.
557 -- We can't use anything less generic, because the way different
558 -- operations are serialized differs on both parameter- and top-level.
560 -- There are two things to be defined for each parameter:
566 genLuxiOp :: String -> [(String, [LuxiParam])] -> Q [Dec]
567 genLuxiOp name cons = do
568 decl_d <- mapM (\(cname, fields) -> do
569 fields' <- mapM (\(_, qt) ->
570 qt >>= \t -> return (NotStrict, t))
572 return $ NormalC (mkName cname) fields')
574 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
575 (savesig, savefn) <- genSaveLuxiOp cons
576 req_defs <- declareSADT "LuxiReq" .
577 map (\(str, _) -> ("Req" ++ str, mkName ("luxiReq" ++ str))) $
579 return $ [declD, savesig, savefn] ++ req_defs
581 -- | Generates the \"save\" expression for a single luxi parameter.
582 saveLuxiField :: Name -> LuxiParam -> Q Exp
583 saveLuxiField fvar (_, qt) =
584 [| JSON.showJSON $(varE fvar) |]
586 -- | Generates the \"save\" clause for entire LuxiOp constructor.
587 saveLuxiConstructor :: (String, [LuxiParam]) -> Q Clause
588 saveLuxiConstructor (sname, fields) = do
589 let cname = mkName sname
590 fnames = map (mkName . fst) fields
591 pat = conP cname (map varP fnames)
592 flist = map (uncurry saveLuxiField) (zip fnames fields)
593 finval = if null flist
594 then [| JSON.showJSON () |]
595 else [| JSON.showJSON $(listE flist) |]
596 clause [pat] (normalB finval) []
598 -- | Generates the main save LuxiOp function.
599 genSaveLuxiOp :: [(String, [LuxiParam])]-> Q (Dec, Dec)
600 genSaveLuxiOp opdefs = do
601 sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
602 let fname = mkName "opToArgs"
603 cclauses <- mapM saveLuxiConstructor opdefs
604 return $ (SigD fname sigt, FunD fname cclauses)
606 -- * "Objects" functionality
608 -- | Extract the field's declaration from a Field structure.
609 fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
610 fieldTypeInfo field_pfx fd = do
611 t <- actualFieldType fd
612 let n = mkName . (field_pfx ++) . fieldRecordName $ fd
613 return (n, NotStrict, t)
615 -- | Build an object declaration.
616 buildObject :: String -> String -> [Field] -> Q [Dec]
617 buildObject sname field_pfx fields = do
618 let name = mkName sname
619 fields_d <- mapM (fieldTypeInfo field_pfx) fields
620 let decl_d = RecC name fields_d
621 let declD = DataD [] name [] [decl_d] [''Show, ''Read, ''Eq]
622 ser_decls <- buildObjectSerialisation sname fields
623 return $ declD:ser_decls
625 -- | Generates an object definition: data type and its JSON instance.
626 buildObjectSerialisation :: String -> [Field] -> Q [Dec]
627 buildObjectSerialisation sname fields = do
628 let name = mkName sname
629 savedecls <- genSaveObject saveObjectField sname fields
630 (loadsig, loadfn) <- genLoadObject loadObjectField sname fields
631 shjson <- objectShowJSON sname
632 rdjson <- objectReadJSON sname
633 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
635 return $ savedecls ++ [loadsig, loadfn, instdecl]
637 -- | The toDict function name for a given type.
638 toDictName :: String -> Name
639 toDictName sname = mkName ("toDict" ++ sname)
641 -- | Generates the save object functionality.
642 genSaveObject :: (Name -> Field -> Q Exp)
643 -> String -> [Field] -> Q [Dec]
644 genSaveObject save_fn sname fields = do
645 let name = mkName sname
646 fnames <- mapM (newName . fieldVariable) fields
647 let pat = conP name (map varP fnames)
648 let tdname = toDictName sname
649 tdsigt <- [t| $(conT name) -> [(String, JSON.JSValue)] |]
651 let felems = map (uncurry save_fn) (zip fnames fields)
653 -- and finally convert all this to a json object
654 tdlist = [| concat $flist |]
656 tclause <- clause [pat] (normalB tdlist) []
657 cclause <- [| $(varNameE "makeObj") . $(varE tdname) |]
658 let fname = mkName ("save" ++ sname)
659 sigt <- [t| $(conT name) -> JSON.JSValue |]
660 return [SigD tdname tdsigt, FunD tdname [tclause],
661 SigD fname sigt, ValD (VarP fname) (NormalB cclause) []]
663 -- | Generates the code for saving an object's field, handling the
664 -- various types of fields that we have.
665 saveObjectField :: Name -> Field -> Q Exp
666 saveObjectField fvar field
667 | fisOptional = [| case $(varE fvar) of
669 Just v -> [( $nameE, JSON.showJSON v)]
671 | otherwise = case fieldShow field of
672 Nothing -> [| [( $nameE, JSON.showJSON $fvarE)] |]
673 Just fn -> [| let (actual, extra) = $fn $fvarE
674 in extra ++ [( $nameE, JSON.showJSON actual)]
676 where fisOptional = fieldIsOptional field
677 nameE = stringE (fieldName field)
680 -- | Generates the showJSON clause for a given object name.
681 objectShowJSON :: String -> Q Dec
682 objectShowJSON name = do
683 body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |]
684 return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
686 -- | Generates the load object functionality.
687 genLoadObject :: (Field -> Q (Name, Stmt))
688 -> String -> [Field] -> Q (Dec, Dec)
689 genLoadObject load_fn sname fields = do
690 let name = mkName sname
691 funname = mkName $ "load" ++ sname
694 opid = mkName "op_id"
695 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
696 (JSON.readJSON $(varE arg1)) |]
697 fbinds <- mapM load_fn fields
698 let (fnames, fstmts) = unzip fbinds
699 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
700 fstmts' = st1:fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
701 sigt <- [t| JSON.JSValue -> JSON.Result $(conT name) |]
702 return $ (SigD funname sigt,
703 FunD funname [Clause [VarP arg1] (NormalB (DoE fstmts')) []])
705 -- | Generates code for loading an object's field.
706 loadObjectField :: Field -> Q (Name, Stmt)
707 loadObjectField field = do
708 let name = fieldVariable field
710 -- these are used in all patterns below
711 let objvar = varNameE "o"
712 objfield = stringE (fieldName field)
714 if fieldIsOptional field
715 then [| $(varNameE "maybeFromObj") $objvar $objfield |]
716 else case fieldDefault field of
718 [| $(varNameE "fromObjWithDefault") $objvar
720 Nothing -> [| $(varNameE "fromObj") $objvar $objfield |]
721 bexp <- loadFn field loadexp objvar
723 return (fvar, BindS (VarP fvar) bexp)
725 -- | Builds the readJSON instance for a given object name.
726 objectReadJSON :: String -> Q Dec
727 objectReadJSON name = do
729 body <- [| case JSON.readJSON $(varE s) of
730 JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s'
732 JSON.Error $ "Can't parse value for type " ++
733 $(stringE name) ++ ": " ++ e
735 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
737 -- * Inheritable parameter tables implementation
739 -- | Compute parameter type names.
740 paramTypeNames :: String -> (String, String)
741 paramTypeNames root = ("Filled" ++ root ++ "Params",
742 "Partial" ++ root ++ "Params")
744 -- | Compute information about the type of a parameter field.
745 paramFieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
746 paramFieldTypeInfo field_pfx fd = do
747 t <- actualFieldType fd
748 let n = mkName . (++ "P") . (field_pfx ++) .
750 return (n, NotStrict, AppT (ConT ''Maybe) t)
752 -- | Build a parameter declaration.
754 -- This function builds two different data structures: a /filled/ one,
755 -- in which all fields are required, and a /partial/ one, in which all
756 -- fields are optional. Due to the current record syntax issues, the
757 -- fields need to be named differrently for the two structures, so the
758 -- partial ones get a /P/ suffix.
759 buildParam :: String -> String -> [Field] -> Q [Dec]
760 buildParam sname field_pfx fields = do
761 let (sname_f, sname_p) = paramTypeNames sname
762 name_f = mkName sname_f
763 name_p = mkName sname_p
764 fields_f <- mapM (fieldTypeInfo field_pfx) fields
765 fields_p <- mapM (paramFieldTypeInfo field_pfx) fields
766 let decl_f = RecC name_f fields_f
767 decl_p = RecC name_p fields_p
768 let declF = DataD [] name_f [] [decl_f] [''Show, ''Read, ''Eq]
769 declP = DataD [] name_p [] [decl_p] [''Show, ''Read, ''Eq]
770 ser_decls_f <- buildObjectSerialisation sname_f fields
771 ser_decls_p <- buildPParamSerialisation sname_p fields
772 fill_decls <- fillParam sname field_pfx fields
773 return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls ++
774 buildParamAllFields sname fields ++
775 buildDictObjectInst name_f sname_f
777 -- | Builds a list of all fields of a parameter.
778 buildParamAllFields :: String -> [Field] -> [Dec]
779 buildParamAllFields sname fields =
780 let vname = mkName ("all" ++ sname ++ "ParamFields")
781 sig = SigD vname (AppT ListT (ConT ''String))
782 val = ListE $ map (LitE . StringL . fieldName) fields
783 in [sig, ValD (VarP vname) (NormalB val) []]
785 -- | Builds the 'DictObject' instance for a filled parameter.
786 buildDictObjectInst :: Name -> String -> [Dec]
787 buildDictObjectInst name sname =
788 [InstanceD [] (AppT (ConT ''DictObject) (ConT name))
789 [ValD (VarP 'toDict) (NormalB (VarE (toDictName sname))) []]]
791 -- | Generates the serialisation for a partial parameter.
792 buildPParamSerialisation :: String -> [Field] -> Q [Dec]
793 buildPParamSerialisation sname fields = do
794 let name = mkName sname
795 savedecls <- genSaveObject savePParamField sname fields
796 (loadsig, loadfn) <- genLoadObject loadPParamField sname fields
797 shjson <- objectShowJSON sname
798 rdjson <- objectReadJSON sname
799 let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
801 return $ savedecls ++ [loadsig, loadfn, instdecl]
803 -- | Generates code to save an optional parameter field.
804 savePParamField :: Name -> Field -> Q Exp
805 savePParamField fvar field = do
807 let actualVal = mkName "v"
808 normalexpr <- saveObjectField actualVal field
809 -- we have to construct the block here manually, because we can't
811 return $ CaseE (VarE fvar) [ Match (ConP 'Nothing [])
812 (NormalB (ConE '[])) []
813 , Match (ConP 'Just [VarP actualVal])
814 (NormalB normalexpr) []
817 -- | Generates code to load an optional parameter field.
818 loadPParamField :: Field -> Q (Name, Stmt)
819 loadPParamField field = do
821 let name = fieldName field
823 -- these are used in all patterns below
824 let objvar = varNameE "o"
825 objfield = stringE name
826 loadexp = [| $(varNameE "maybeFromObj") $objvar $objfield |]
827 bexp <- loadFn field loadexp objvar
828 return (fvar, BindS (VarP fvar) bexp)
830 -- | Builds a simple declaration of type @n_x = fromMaybe f_x p_x@.
831 buildFromMaybe :: String -> Q Dec
832 buildFromMaybe fname =
833 valD (varP (mkName $ "n_" ++ fname))
834 (normalB [| $(varNameE "fromMaybe")
835 $(varNameE $ "f_" ++ fname)
836 $(varNameE $ "p_" ++ fname) |]) []
838 -- | Builds a function that executes the filling of partial parameter
839 -- from a full copy (similar to Python's fillDict).
840 fillParam :: String -> String -> [Field] -> Q [Dec]
841 fillParam sname field_pfx fields = do
842 let fnames = map (\fd -> field_pfx ++ fieldRecordName fd) fields
843 (sname_f, sname_p) = paramTypeNames sname
846 name_f = mkName sname_f
847 name_p = mkName sname_p
848 fun_name = mkName $ "fill" ++ sname ++ "Params"
849 le_full = ValD (ConP name_f (map (VarP . mkName . ("f_" ++)) fnames))
850 (NormalB . VarE . mkName $ oname_f) []
851 le_part = ValD (ConP name_p (map (VarP . mkName . ("p_" ++)) fnames))
852 (NormalB . VarE . mkName $ oname_p) []
853 obj_new = foldl (\accu vname -> AppE accu (VarE vname)) (ConE name_f)
854 $ map (mkName . ("n_" ++)) fnames
855 le_new <- mapM buildFromMaybe fnames
856 funt <- [t| $(conT name_f) -> $(conT name_p) -> $(conT name_f) |]
857 let sig = SigD fun_name funt
858 fclause = Clause [VarP (mkName oname_f), VarP (mkName oname_p)]
859 (NormalB $ LetE (le_full:le_part:le_new) obj_new) []
860 fun = FunD fun_name [fclause]