Expand TH with tags field
[ganeti-local] / htools / Ganeti / THH.hs
1 {-# LANGUAGE TemplateHaskell #-}
2
3 {-| TemplateHaskell helper for HTools.
4
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).
8
9 -}
10
11 {-
12
13 Copyright (C) 2011, 2012 Google Inc.
14
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.
19
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.
24
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
28 02110-1301, USA.
29
30 -}
31
32 module Ganeti.THH ( declareSADT
33                   , declareIADT
34                   , makeJSONInstance
35                   , genOpID
36                   , genOpCode
37                   , genStrOfOp
38                   , genStrOfKey
39                   , genLuxiOp
40                   , Field
41                   , simpleField
42                   , defaultField
43                   , optionalField
44                   , renameField
45                   , containerField
46                   , customField
47                   , timeStampFields
48                   , uuidFields
49                   , serialFields
50                   , tagsFields
51                   , buildObject
52                   , buildObjectSerialisation
53                   , buildParam
54                   , Container
55                   ) where
56
57 import Control.Arrow
58 import Control.Monad (liftM, liftM2)
59 import Data.Char
60 import Data.List
61 import qualified Data.Map as M
62 import qualified Data.Set as Set
63 import Language.Haskell.TH
64
65 import qualified Text.JSON as JSON
66
67 import Ganeti.HTools.JSON
68
69 -- * Exported types
70
71 type Container = M.Map String
72
73 -- | Serialised field data type.
74 data Field = Field { fieldName        :: String
75                    , fieldType        :: Q Type
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
82                    }
83
84 -- | Generates a simple field.
85 simpleField :: String -> Q Type -> Field
86 simpleField fname ftype =
87   Field { fieldName        = fname
88         , fieldType        = ftype
89         , fieldRead        = Nothing
90         , fieldShow        = Nothing
91         , fieldDefault     = Nothing
92         , fieldConstr      = Nothing
93         , fieldIsContainer = False
94         , fieldIsOptional  = False
95         }
96
97 -- | Sets the renamed constructor field.
98 renameField :: String -> Field -> Field
99 renameField constrName field = field { fieldConstr = Just constrName }
100
101 -- | Sets the default value on a field (makes it optional with a
102 -- default value).
103 defaultField :: Q Exp -> Field -> Field
104 defaultField defval field = field { fieldDefault = Just defval }
105
106 -- | Marks a field optional (turning its base type into a Maybe).
107 optionalField :: Field -> Field
108 optionalField field = field { fieldIsOptional = True }
109
110 -- | Marks a field as a container.
111 containerField :: Field -> Field
112 containerField field = field { fieldIsContainer = True }
113
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) }
121
122 fieldRecordName :: Field -> String
123 fieldRecordName (Field { fieldName = name, fieldConstr = alias }) =
124   maybe (camelCase name) id alias
125
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
131 fieldVariable f =
132   case (fieldConstr f) of
133     Just name -> ensureLower name
134     _ -> fieldName f
135
136 actualFieldType :: Field -> Q Type
137 actualFieldType f | fieldIsContainer f = [t| Container $t |]
138                   | fieldIsOptional f  = [t| Maybe $t     |]
139                   | otherwise = t
140                   where t = fieldType f
141
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 ()
148
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
152 -- functions.
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
161
162 -- * Common field declarations
163
164 timeStampFields :: [Field]
165 timeStampFields =
166     [ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |]
167     , defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |]
168     ]
169
170 serialFields :: [Field]
171 serialFields =
172     [ renameField  "Serial" $ simpleField "serial_no" [t| Int |] ]
173
174 uuidFields :: [Field]
175 uuidFields = [ simpleField "uuid" [t| String |] ]
176
177 -- | Tag field description.
178 tagsFields :: [Field]
179 tagsFields = [ defaultField [| Set.empty |] $
180                simpleField "tags" [t| Set.Set String |] ]
181
182 -- * Helper functions
183
184 -- | Ensure first letter is lowercase.
185 --
186 -- Used to convert type name to function prefix, e.g. in @data Aa ->
187 -- aaToRaw@.
188 ensureLower :: String -> String
189 ensureLower [] = []
190 ensureLower (x:xs) = toLower x:xs
191
192 -- | Ensure first letter is uppercase.
193 --
194 -- Used to convert constructor name to component
195 ensureUpper :: String -> String
196 ensureUpper [] = []
197 ensureUpper (x:xs) = toUpper x:xs
198
199 -- | Helper for quoted expressions.
200 varNameE :: String -> Q Exp
201 varNameE = varE . mkName
202
203 -- | showJSON as an expression, for reuse.
204 showJSONE :: Q Exp
205 showJSONE = varNameE "showJSON"
206
207 -- | ToRaw function name.
208 toRawName :: String -> Name
209 toRawName = mkName . (++ "ToRaw") . ensureLower
210
211 -- | FromRaw function name.
212 fromRawName :: String -> Name
213 fromRawName = mkName . (++ "FromRaw") . ensureLower
214
215 -- | Converts a name to it's varE/litE representations.
216 --
217 reprE :: Either String Name -> Q Exp
218 reprE = either stringE varE
219
220 -- | Smarter function application.
221 --
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
227
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
235
236 -- | Container dumper
237 showContainer :: (JSON.JSON a) => Container a -> JSON.JSValue
238 showContainer = JSON.makeObj . map (second JSON.showJSON) . M.toList
239
240 -- * Template code for simple raw type-equivalent ADTs
241
242 -- | Generates a data type declaration.
243 --
244 -- The type will have a fixed list of instances.
245 strADTDecl :: Name -> [String] -> Dec
246 strADTDecl name constructors =
247   DataD [] name []
248           (map (flip NormalC [] . mkName) constructors)
249           [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
250
251 -- | Generates a toRaw function.
252 --
253 -- This generates a simple function of the form:
254 --
255 -- @
256 -- nameToRaw :: Name -> /traw/
257 -- nameToRaw Cons1 = var1
258 -- nameToRaw Cons2 = \"value2\"
259 -- @
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
264   -- raw value
265   clauses <- mapM  (\(c, v) -> clause [recP (mkName c) []]
266                              (normalB (reprE v)) []) constructors
267   return [SigD fname sigt, FunD fname clauses]
268
269 -- | Generates a fromRaw function.
270 --
271 -- The function generated is monadic and can fail parsing the
272 -- raw value. It is of the form:
273 --
274 -- @
275 -- nameFromRaw :: (Monad m) => /traw/ -> m Name
276 -- nameFromRaw s | s == var1       = Cons1
277 --               | s == \"value2\" = Cons2
278 --               | otherwise = fail /.../
279 -- @
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"
286       varpe = varE varp
287   clauses <- mapM (\(c, v) -> do
288                      -- the clause match condition
289                      g <- normalG [| $varpe == $(varE v) |]
290                      -- the clause result
291                      r <- [| return $(conE (mkName c)) |]
292                      return (g, r)) constructors
293   -- the otherwise clause (fallback)
294   oth_clause <- do
295     g <- normalG [| otherwise |]
296     r <- [|fail ("Invalid string value for type " ++
297                  $(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
298     return (g, r)
299   let fun = FunD fname [Clause [VarP varp]
300                         (GuardedB (clauses++[oth_clause])) []]
301   return [SigD fname sigt, fun]
302
303 -- | Generates a data type from a given raw format.
304 --
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.
309 --
310 -- The function will generate the data type declaration, and then two
311 -- functions:
312 --
313 -- * /name/ToRaw, which converts the type to a raw type
314 --
315 -- * /name/FromRaw, which (monadically) converts from a raw type to the type
316 --
317 -- Note that this is basically just a custom show/read instance,
318 -- nothing else.
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
328
329 declareIADT :: String -> [(String, Name)] -> Q [Dec]
330 declareIADT = declareADT ''Int
331
332 declareSADT :: String -> [(String, Name)] -> Q [Dec]
333 declareSADT = declareADT ''String
334
335 -- | Creates the showJSON member of a JSON instance declaration.
336 --
337 -- This will create what is the equivalent of:
338 --
339 -- @
340 -- showJSON = showJSON . /name/ToRaw
341 -- @
342 --
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) []]
348
349 -- | Creates the readJSON member of a JSON instance declaration.
350 --
351 -- This will create what is the equivalent of:
352 --
353 -- @
354 -- readJSON s = case readJSON s of
355 --                Ok s' -> /name/FromRaw s'
356 --                Error e -> Error /description/
357 -- @
358 --
359 -- in an instance JSON /name/ declaration
360 genReadJSON :: String -> Q Dec
361 genReadJSON name = do
362   let s = mkName "s"
363   body <- [| case JSON.readJSON $(varE s) of
364                JSON.Ok s' -> $(varE (fromRawName name)) s'
365                JSON.Error e ->
366                    JSON.Error $ "Can't parse raw value for type " ++
367                            $(stringE name) ++ ": " ++ e ++ " from " ++
368                            show $(varE s)
369            |]
370   return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
371
372 -- | Generates a JSON instance for a given type.
373 --
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]]
382
383 -- * Template code for opcodes
384
385 -- | Transforms a CamelCase string into an_underscore_based_one.
386 deCamelCase :: String -> String
387 deCamelCase =
388     intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
389
390 -- | Transform an underscore_name into a CamelCase one.
391 camelCase :: String -> String
392 camelCase = concatMap (ensureUpper . drop 1) .
393             groupBy (\_ b -> b /= '_') . ('_':)
394
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
400
401 -- | Builds the generic constructor-to-string function.
402 --
403 -- This generates a simple function of the following form:
404 --
405 -- @
406 -- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
407 -- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
408 -- @
409 --
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
418
419 -- | Constructor-to-string for OpCode.
420 genOpID :: Name -> String -> Q [Dec]
421 genOpID = genConstrToStr deCamelCase
422
423 -- | OpCode parameter (field) type.
424 type OpParam = (String, Q Type, Q Exp)
425
426 -- | Generates the OpCode data type.
427 --
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
434           -> Q [Dec]
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'')
441             cons
442   let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
443
444   (savesig, savefn) <- genSaveOpCode cons
445   (loadsig, loadfn) <- genLoadOpCode cons
446   return [declD, loadsig, loadfn, savesig, savefn]
447
448 -- | Checks whether a given parameter is options.
449 --
450 -- This requires that it's a 'Maybe'.
451 isOptional :: Type -> Bool
452 isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
453 isOptional _ = False
454
455 -- | Generates the \"save\" clause for an entire opcode constructor.
456 --
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
462                              -- constructor
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') []
476
477 -- | Generates the main save opcode function.
478 --
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)
487
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)]
495   return $ DoE fstmts'
496
497 genLoadOpCode :: [(String, [Field])] -> Q (Dec, Dec)
498 genLoadOpCode opdefs = do
499   let fname = mkName "loadOpCode"
500       arg1 = mkName "v"
501       objname = mkName "o"
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) []
513                   ) $ zip mexps opdefs
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) []])
519
520 -- * Template code for luxi
521
522 -- | Constructor-to-string for LuxiOp.
523 genStrOfOp :: Name -> String -> Q [Dec]
524 genStrOfOp = genConstrToStr id
525
526 -- | Constructor-to-string for MsgKeys.
527 genStrOfKey :: Name -> String -> Q [Dec]
528 genStrOfKey = genConstrToStr ensureLower
529
530 -- | LuxiOp parameter type.
531 type LuxiParam = (String, Q Type, Q Exp)
532
533 -- | Generates the LuxiOp data type.
534 --
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.
539 --
540 -- There are three things to be defined for each parameter:
541 --
542 -- * name
543 --
544 -- * type
545 --
546 -- * operation; this is the operation performed on the parameter before
547 --   serialization
548 --
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))
554                                fields
555                     return $ NormalC (mkName cname) fields')
556             cons
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))) $
561                   cons
562   return $ [declD, savesig, savefn] ++ req_defs
563
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) ) |]
568
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) []
580
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)
588
589 -- * "Objects" functionality
590
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)
597
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
607
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))
616                  [rdjson, shjson]
617   return $ savedecls ++ [loadsig, loadfn, instdecl]
618
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)] |]
627
628   let felems = map (uncurry save_fn) (zip fnames fields)
629       flist = listE felems
630       -- and finally convert all this to a json object
631       tdlist = [| concat $flist |]
632       iname = mkName "i"
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) []]
639
640 saveObjectField :: Name -> Field -> Q Exp
641 saveObjectField fvar field
642   | isContainer = [| [( $nameE , JSON.showJSON . showContainer $ $fvarE)] |]
643   | fisOptional = [| case $(varE fvar) of
644                       Nothing -> []
645                       Just v -> [( $nameE, JSON.showJSON v)]
646                   |]
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)]
651                   |]
652   where isContainer = fieldIsContainer field
653         fisOptional  = fieldIsOptional field
654         nameE = stringE (fieldName field)
655         fvarE = varE fvar
656
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) []]
661
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
667       arg1 = mkName "v"
668       objname = mkName "o"
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')) []])
679
680 loadObjectField :: Field -> Q (Name, Stmt)
681 loadObjectField field = do
682   let name = fieldVariable field
683       fvar = mkName name
684   -- these are used in all patterns below
685   let objvar = varNameE "o"
686       objfield = stringE (fieldName field)
687       loadexp =
688         if fieldIsOptional field
689           then [| $(varNameE "maybeFromObj") $objvar $objfield |]
690           else case fieldDefault field of
691                  Just defv ->
692                    [| $(varNameE "fromObjWithDefault") $objvar
693                       $objfield $defv |]
694                  Nothing -> [| $(varNameE "fromObj") $objvar $objfield |]
695   bexp <- loadFn field loadexp objvar
696
697   return (fvar, BindS (VarP fvar) bexp)
698
699 objectReadJSON :: String -> Q Dec
700 objectReadJSON name = do
701   let s = mkName "s"
702   body <- [| case JSON.readJSON $(varE s) of
703                JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s'
704                JSON.Error e ->
705                  JSON.Error $ "Can't parse value for type " ++
706                        $(stringE name) ++ ": " ++ e
707            |]
708   return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
709
710 -- * Inheritable parameter tables implementation
711
712 -- | Compute parameter type names.
713 paramTypeNames :: String -> (String, String)
714 paramTypeNames root = ("Filled"  ++ root ++ "Params",
715                        "Partial" ++ root ++ "Params")
716
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 ++) .
722           fieldRecordName $ fd
723   return (n, NotStrict, AppT (ConT ''Maybe) t)
724
725 -- | Build a parameter declaration.
726 --
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
747
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))
756                  [rdjson, shjson]
757   return $ savedecls ++ [loadsig, loadfn, instdecl]
758
759 savePParamField :: Name -> Field -> Q Exp
760 savePParamField fvar field = do
761   checkNonOptDef field
762   let actualVal = mkName "v"
763   normalexpr <- saveObjectField actualVal field
764   -- we have to construct the block here manually, because we can't
765   -- splice-in-splice
766   return $ CaseE (VarE fvar) [ Match (ConP 'Nothing [])
767                                        (NormalB (ConE '[])) []
768                              , Match (ConP 'Just [VarP actualVal])
769                                        (NormalB normalexpr) []
770                              ]
771 loadPParamField :: Field -> Q (Name, Stmt)
772 loadPParamField field = do
773   checkNonOptDef field
774   let name = fieldName field
775       fvar = mkName name
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)
782
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) |]) []
790
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
795       oname_f = "fobj"
796       oname_p = "pobj"
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]
812   return [sig, fun]