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