Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / THH.hs @ b1e81520

History | View | Annotate | Download (28.6 kB)

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 :: Q Exp -> Q Exp -> Field -> Field
114
customField readfn showfn field =
115
  field { fieldRead = Just readfn, fieldShow = Just showfn }
116

    
117
fieldRecordName :: Field -> String
118
fieldRecordName (Field { fieldName = name, fieldConstr = alias }) =
119
  maybe (camelCase name) id alias
120

    
121
-- | Computes the preferred variable name to use for the value of this
122
-- field. If the field has a specific constructor name, then we use a
123
-- first-letter-lowercased version of that; otherwise, we simply use
124
-- the field name. See also 'fieldRecordName'.
125
fieldVariable :: Field -> String
126
fieldVariable f =
127
  case (fieldConstr f) of
128
    Just name -> ensureLower name
129
    _ -> fieldName f
130

    
131
actualFieldType :: Field -> Q Type
132
actualFieldType f | fieldIsContainer f = [t| Container $t |]
133
                  | fieldIsOptional f  = [t| Maybe $t     |]
134
                  | otherwise = t
135
                  where t = fieldType f
136

    
137
checkNonOptDef :: (Monad m) => Field -> m ()
138
checkNonOptDef (Field { fieldIsOptional = True, fieldName = name }) =
139
  fail $ "Optional field " ++ name ++ " used in parameter declaration"
140
checkNonOptDef (Field { fieldDefault = (Just _), fieldName = name }) =
141
  fail $ "Default field " ++ name ++ " used in parameter declaration"
142
checkNonOptDef _ = return ()
143

    
144
loadFn :: Field -> Q Exp -> Q Exp
145
loadFn (Field { fieldIsContainer = True }) expr = [| $expr >>= readContainer |]
146
loadFn (Field { fieldRead = Just readfn }) expr = [| $expr >>= $readfn |]
147
loadFn _ expr = expr
148

    
149
saveFn :: Field -> Q Exp -> Q Exp
150
saveFn (Field { fieldIsContainer = True }) expr = [| showContainer $expr |]
151
saveFn (Field { fieldRead = Just readfn }) expr = [| $readfn $expr |]
152
saveFn _ expr = expr
153

    
154
-- * Common field declarations
155

    
156
timeStampFields :: [Field]
157
timeStampFields =
158
    [ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |]
159
    , defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |]
160
    ]
161

    
162
serialFields :: [Field]
163
serialFields =
164
    [ renameField  "Serial" $ simpleField "serial_no" [t| Int |] ]
165

    
166
uuidFields :: [Field]
167
uuidFields = [ simpleField "uuid" [t| String |] ]
168

    
169
-- * Helper functions
170

    
171
-- | Ensure first letter is lowercase.
172
--
173
-- Used to convert type name to function prefix, e.g. in @data Aa ->
174
-- aaToRaw@.
175
ensureLower :: String -> String
176
ensureLower [] = []
177
ensureLower (x:xs) = toLower x:xs
178

    
179
-- | Ensure first letter is uppercase.
180
--
181
-- Used to convert constructor name to component
182
ensureUpper :: String -> String
183
ensureUpper [] = []
184
ensureUpper (x:xs) = toUpper x:xs
185

    
186
-- | Helper for quoted expressions.
187
varNameE :: String -> Q Exp
188
varNameE = varE . mkName
189

    
190
-- | showJSON as an expression, for reuse.
191
showJSONE :: Q Exp
192
showJSONE = varNameE "showJSON"
193

    
194
-- | ToRaw function name.
195
toRawName :: String -> Name
196
toRawName = mkName . (++ "ToRaw") . ensureLower
197

    
198
-- | FromRaw function name.
199
fromRawName :: String -> Name
200
fromRawName = mkName . (++ "FromRaw") . ensureLower
201

    
202
-- | Converts a name to it's varE/litE representations.
203
--
204
reprE :: Either String Name -> Q Exp
205
reprE = either stringE varE
206

    
207
-- | Smarter function application.
208
--
209
-- This does simply f x, except that if is 'id', it will skip it, in
210
-- order to generate more readable code when using -ddump-splices.
211
appFn :: Exp -> Exp -> Exp
212
appFn f x | f == VarE 'id = x
213
          | otherwise = AppE f x
214

    
215
-- | Container loader
216
readContainer :: (Monad m, JSON.JSON a) =>
217
                 JSON.JSObject JSON.JSValue -> m (Container a)
218
readContainer obj = do
219
  let kjvlist = JSON.fromJSObject obj
220
  kalist <- mapM (\(k, v) -> fromKeyValue k v >>= \a -> return (k, a)) kjvlist
221
  return $ M.fromList kalist
222

    
223
-- | Container dumper
224
showContainer :: (JSON.JSON a) => Container a -> JSON.JSValue
225
showContainer = JSON.makeObj . map (second JSON.showJSON) . M.toList
226

    
227
-- * Template code for simple raw type-equivalent ADTs
228

    
229
-- | Generates a data type declaration.
230
--
231
-- The type will have a fixed list of instances.
232
strADTDecl :: Name -> [String] -> Dec
233
strADTDecl name constructors =
234
  DataD [] name []
235
          (map (flip NormalC [] . mkName) constructors)
236
          [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
237

    
238
-- | Generates a toRaw function.
239
--
240
-- This generates a simple function of the form:
241
--
242
-- @
243
-- nameToRaw :: Name -> /traw/
244
-- nameToRaw Cons1 = var1
245
-- nameToRaw Cons2 = \"value2\"
246
-- @
247
genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec]
248
genToRaw traw fname tname constructors = do
249
  sigt <- [t| $(conT tname) -> $(conT traw) |]
250
  -- the body clauses, matching on the constructor and returning the
251
  -- raw value
252
  clauses <- mapM  (\(c, v) -> clause [recP (mkName c) []]
253
                             (normalB (reprE v)) []) constructors
254
  return [SigD fname sigt, FunD fname clauses]
255

    
256
-- | Generates a fromRaw function.
257
--
258
-- The function generated is monadic and can fail parsing the
259
-- raw value. It is of the form:
260
--
261
-- @
262
-- nameFromRaw :: (Monad m) => /traw/ -> m Name
263
-- nameFromRaw s | s == var1       = Cons1
264
--               | s == \"value2\" = Cons2
265
--               | otherwise = fail /.../
266
-- @
267
genFromRaw :: Name -> Name -> Name -> [(String, Name)] -> Q [Dec]
268
genFromRaw traw fname tname constructors = do
269
  -- signature of form (Monad m) => String -> m $name
270
  sigt <- [t| (Monad m) => $(conT traw) -> m $(conT tname) |]
271
  -- clauses for a guarded pattern
272
  let varp = mkName "s"
273
      varpe = varE varp
274
  clauses <- mapM (\(c, v) -> do
275
                     -- the clause match condition
276
                     g <- normalG [| $varpe == $(varE v) |]
277
                     -- the clause result
278
                     r <- [| return $(conE (mkName c)) |]
279
                     return (g, r)) constructors
280
  -- the otherwise clause (fallback)
281
  oth_clause <- do
282
    g <- normalG [| otherwise |]
283
    r <- [|fail ("Invalid string value for type " ++
284
                 $(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
285
    return (g, r)
286
  let fun = FunD fname [Clause [VarP varp]
287
                        (GuardedB (clauses++[oth_clause])) []]
288
  return [SigD fname sigt, fun]
289

    
290
-- | Generates a data type from a given raw format.
291
--
292
-- The format is expected to multiline. The first line contains the
293
-- type name, and the rest of the lines must contain two words: the
294
-- constructor name and then the string representation of the
295
-- respective constructor.
296
--
297
-- The function will generate the data type declaration, and then two
298
-- functions:
299
--
300
-- * /name/ToRaw, which converts the type to a raw type
301
--
302
-- * /name/FromRaw, which (monadically) converts from a raw type to the type
303
--
304
-- Note that this is basically just a custom show/read instance,
305
-- nothing else.
306
declareADT :: Name -> String -> [(String, Name)] -> Q [Dec]
307
declareADT traw sname cons = do
308
  let name = mkName sname
309
      ddecl = strADTDecl name (map fst cons)
310
      -- process cons in the format expected by genToRaw
311
      cons' = map (\(a, b) -> (a, Right b)) cons
312
  toraw <- genToRaw traw (toRawName sname) name cons'
313
  fromraw <- genFromRaw traw (fromRawName sname) name cons
314
  return $ ddecl:toraw ++ fromraw
315

    
316
declareIADT :: String -> [(String, Name)] -> Q [Dec]
317
declareIADT = declareADT ''Int
318

    
319
declareSADT :: String -> [(String, Name)] -> Q [Dec]
320
declareSADT = declareADT ''String
321

    
322
-- | Creates the showJSON member of a JSON instance declaration.
323
--
324
-- This will create what is the equivalent of:
325
--
326
-- @
327
-- showJSON = showJSON . /name/ToRaw
328
-- @
329
--
330
-- in an instance JSON /name/ declaration
331
genShowJSON :: String -> Q [Dec]
332
genShowJSON name = [d| showJSON = JSON.showJSON . $(varE (toRawName name)) |]
333

    
334
-- | Creates the readJSON member of a JSON instance declaration.
335
--
336
-- This will create what is the equivalent of:
337
--
338
-- @
339
-- readJSON s = case readJSON s of
340
--                Ok s' -> /name/FromRaw s'
341
--                Error e -> Error /description/
342
-- @
343
--
344
-- in an instance JSON /name/ declaration
345
genReadJSON :: String -> Q Dec
346
genReadJSON name = do
347
  let s = mkName "s"
348
  body <- [| case JSON.readJSON $(varE s) of
349
               JSON.Ok s' -> $(varE (fromRawName name)) s'
350
               JSON.Error e ->
351
                   JSON.Error $ "Can't parse raw value for type " ++
352
                           $(stringE name) ++ ": " ++ e ++ " from " ++
353
                           show $(varE s)
354
           |]
355
  return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
356

    
357
-- | Generates a JSON instance for a given type.
358
--
359
-- This assumes that the /name/ToRaw and /name/FromRaw functions
360
-- have been defined as by the 'declareSADT' function.
361
makeJSONInstance :: Name -> Q [Dec]
362
makeJSONInstance name = do
363
  let base = nameBase name
364
  showJ <- genShowJSON base
365
  readJ <- genReadJSON base
366
  return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) (readJ:showJ)]
367

    
368
-- * Template code for opcodes
369

    
370
-- | Transforms a CamelCase string into an_underscore_based_one.
371
deCamelCase :: String -> String
372
deCamelCase =
373
    intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
374

    
375
-- | Transform an underscore_name into a CamelCase one.
376
camelCase :: String -> String
377
camelCase = concatMap (ensureUpper . drop 1) .
378
            groupBy (\_ b -> b /= '_') . ('_':)
379

    
380
-- | Computes the name of a given constructor.
381
constructorName :: Con -> Q Name
382
constructorName (NormalC name _) = return name
383
constructorName (RecC name _)    = return name
384
constructorName x                = fail $ "Unhandled constructor " ++ show x
385

    
386
-- | Builds the generic constructor-to-string function.
387
--
388
-- This generates a simple function of the following form:
389
--
390
-- @
391
-- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
392
-- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
393
-- @
394
--
395
-- This builds a custom list of name/string pairs and then uses
396
-- 'genToRaw' to actually generate the function
397
genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
398
genConstrToStr trans_fun name fname = do
399
  TyConI (DataD _ _ _ cons _) <- reify name
400
  cnames <- mapM (liftM nameBase . constructorName) cons
401
  let svalues = map (Left . trans_fun) cnames
402
  genToRaw ''String (mkName fname) name $ zip cnames svalues
403

    
404
-- | Constructor-to-string for OpCode.
405
genOpID :: Name -> String -> Q [Dec]
406
genOpID = genConstrToStr deCamelCase
407

    
408
-- | OpCode parameter (field) type.
409
type OpParam = (String, Q Type, Q Exp)
410

    
411
-- | Generates the OpCode data type.
412
--
413
-- This takes an opcode logical definition, and builds both the
414
-- datatype and the JSON serialisation out of it. We can't use a
415
-- generic serialisation since we need to be compatible with Ganeti's
416
-- own, so we have a few quirks to work around.
417
genOpCode :: String                -- ^ Type name to use
418
          -> [(String, [Field])]   -- ^ Constructor name and parameters
419
          -> Q [Dec]
420
genOpCode name cons = do
421
  decl_d <- mapM (\(cname, fields) -> do
422
                    -- we only need the type of the field, without Q
423
                    fields' <- mapM actualFieldType fields
424
                    let fields'' = zip (repeat NotStrict) fields'
425
                    return $ NormalC (mkName cname) fields'')
426
            cons
427
  let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
428

    
429
  (savesig, savefn) <- genSaveOpCode cons
430
  (loadsig, loadfn) <- genLoadOpCode cons
431
  return [declD, loadsig, loadfn, savesig, savefn]
432

    
433
-- | Checks whether a given parameter is options.
434
--
435
-- This requires that it's a 'Maybe'.
436
isOptional :: Type -> Bool
437
isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
438
isOptional _ = False
439

    
440
-- | Generates the \"save\" clause for an entire opcode constructor.
441
--
442
-- This matches the opcode with variables named the same as the
443
-- constructor fields (just so that the spliced in code looks nicer),
444
-- and passes those name plus the parameter definition to 'saveObjectField'.
445
saveConstructor :: String    -- ^ The constructor name
446
                -> [Field]   -- ^ The parameter definitions for this
447
                             -- constructor
448
                -> Q Clause  -- ^ Resulting clause
449
saveConstructor sname fields = do
450
  let cname = mkName sname
451
  let fnames = map (mkName . fieldVariable) fields
452
  let pat = conP cname (map varP fnames)
453
  let felems = map (uncurry saveObjectField) (zip fnames fields)
454
      -- now build the OP_ID serialisation
455
      opid = [| [( $(stringE "OP_ID"),
456
                   JSON.showJSON $(stringE . deCamelCase $ sname) )] |]
457
      flist = listE (opid:felems)
458
      -- and finally convert all this to a json object
459
      flist' = [| $(varNameE "makeObj") (concat $flist) |]
460
  clause [pat] (normalB flist') []
461

    
462
-- | Generates the main save opcode function.
463
--
464
-- This builds a per-constructor match clause that contains the
465
-- respective constructor-serialisation code.
466
genSaveOpCode :: [(String, [Field])] -> Q (Dec, Dec)
467
genSaveOpCode opdefs = do
468
  cclauses <- mapM (uncurry saveConstructor) opdefs
469
  let fname = mkName "saveOpCode"
470
  sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |]
471
  return $ (SigD fname sigt, FunD fname cclauses)
472

    
473
loadConstructor :: String -> [Field] -> Q Exp
474
loadConstructor sname fields = do
475
  let name = mkName sname
476
  fbinds <- mapM loadObjectField fields
477
  let (fnames, fstmts) = unzip fbinds
478
  let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
479
      fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
480
  return $ DoE fstmts'
481

    
482
genLoadOpCode :: [(String, [Field])] -> Q (Dec, Dec)
483
genLoadOpCode opdefs = do
484
  let fname = mkName "loadOpCode"
485
      arg1 = mkName "v"
486
      objname = mkName "o"
487
      opid = mkName "op_id"
488
  st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
489
                                 (JSON.readJSON $(varE arg1)) |]
490
  st2 <- bindS (varP opid) [| $(varNameE "fromObj")
491
                              $(varE objname) $(stringE "OP_ID") |]
492
  -- the match results (per-constructor blocks)
493
  mexps <- mapM (uncurry loadConstructor) opdefs
494
  fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
495
  let mpats = map (\(me, c) ->
496
                       let mp = LitP . StringL . deCamelCase . fst $ c
497
                       in Match mp (NormalB me) []
498
                  ) $ zip mexps opdefs
499
      defmatch = Match WildP (NormalB fails) []
500
      cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
501
      body = DoE [st1, st2, cst]
502
  sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
503
  return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
504

    
505
-- * Template code for luxi
506

    
507
-- | Constructor-to-string for LuxiOp.
508
genStrOfOp :: Name -> String -> Q [Dec]
509
genStrOfOp = genConstrToStr id
510

    
511
-- | Constructor-to-string for MsgKeys.
512
genStrOfKey :: Name -> String -> Q [Dec]
513
genStrOfKey = genConstrToStr ensureLower
514

    
515
-- | LuxiOp parameter type.
516
type LuxiParam = (String, Q Type, Q Exp)
517

    
518
-- | Generates the LuxiOp data type.
519
--
520
-- This takes a Luxi operation definition and builds both the
521
-- datatype and the function trnasforming the arguments to JSON.
522
-- We can't use anything less generic, because the way different
523
-- operations are serialized differs on both parameter- and top-level.
524
--
525
-- There are three things to be defined for each parameter:
526
--
527
-- * name
528
--
529
-- * type
530
--
531
-- * operation; this is the operation performed on the parameter before
532
--   serialization
533
--
534
genLuxiOp :: String -> [(String, [LuxiParam])] -> Q [Dec]
535
genLuxiOp name cons = do
536
  decl_d <- mapM (\(cname, fields) -> do
537
                    fields' <- mapM (\(_, qt, _) ->
538
                                         qt >>= \t -> return (NotStrict, t))
539
                               fields
540
                    return $ NormalC (mkName cname) fields')
541
            cons
542
  let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read]
543
  (savesig, savefn) <- genSaveLuxiOp cons
544
  return [declD, savesig, savefn]
545

    
546
-- | Generates the \"save\" expression for a single luxi parameter.
547
saveLuxiField :: Name -> LuxiParam -> Q Exp
548
saveLuxiField fvar (_, qt, fn) =
549
    [| JSON.showJSON ( $(liftM2 appFn fn $ varE fvar) ) |]
550

    
551
-- | Generates the \"save\" clause for entire LuxiOp constructor.
552
saveLuxiConstructor :: (String, [LuxiParam]) -> Q Clause
553
saveLuxiConstructor (sname, fields) = do
554
  let cname = mkName sname
555
      fnames = map (\(nm, _, _) -> mkName nm) fields
556
      pat = conP cname (map varP fnames)
557
      flist = map (uncurry saveLuxiField) (zip fnames fields)
558
      finval = if null flist
559
               then [| JSON.showJSON ()    |]
560
               else [| JSON.showJSON $(listE flist) |]
561
  clause [pat] (normalB finval) []
562

    
563
-- | Generates the main save LuxiOp function.
564
genSaveLuxiOp :: [(String, [LuxiParam])]-> Q (Dec, Dec)
565
genSaveLuxiOp opdefs = do
566
  sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
567
  let fname = mkName "opToArgs"
568
  cclauses <- mapM saveLuxiConstructor opdefs
569
  return $ (SigD fname sigt, FunD fname cclauses)
570

    
571
-- * "Objects" functionality
572

    
573
-- | Extract the field's declaration from a Field structure.
574
fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
575
fieldTypeInfo field_pfx fd = do
576
  t <- actualFieldType fd
577
  let n = mkName . (field_pfx ++) . fieldRecordName $ fd
578
  return (n, NotStrict, t)
579

    
580
-- | Build an object declaration.
581
buildObject :: String -> String -> [Field] -> Q [Dec]
582
buildObject sname field_pfx fields = do
583
  let name = mkName sname
584
  fields_d <- mapM (fieldTypeInfo field_pfx) fields
585
  let decl_d = RecC name fields_d
586
  let declD = DataD [] name [] [decl_d] [''Show, ''Read, ''Eq]
587
  ser_decls <- buildObjectSerialisation sname fields
588
  return $ declD:ser_decls
589

    
590
buildObjectSerialisation :: String -> [Field] -> Q [Dec]
591
buildObjectSerialisation sname fields = do
592
  let name = mkName sname
593
  savedecls <- genSaveObject saveObjectField sname fields
594
  (loadsig, loadfn) <- genLoadObject loadObjectField sname fields
595
  shjson <- objectShowJSON sname
596
  rdjson <- objectReadJSON sname
597
  let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
598
                 (rdjson:shjson)
599
  return $ savedecls ++ [loadsig, loadfn, instdecl]
600

    
601
genSaveObject :: (Name -> Field -> Q Exp)
602
              -> String -> [Field] -> Q [Dec]
603
genSaveObject save_fn sname fields = do
604
  let name = mkName sname
605
  let fnames = map (mkName . fieldVariable) fields
606
  let pat = conP name (map varP fnames)
607
  let tdname = mkName ("toDict" ++ sname)
608
  tdsigt <- [t| $(conT name) -> [(String, JSON.JSValue)] |]
609

    
610
  let felems = map (uncurry save_fn) (zip fnames fields)
611
      flist = listE felems
612
      -- and finally convert all this to a json object
613
      tdlist = [| concat $flist |]
614
      iname = mkName "i"
615
  tclause <- clause [pat] (normalB tdlist) []
616
  cclause <- [| $(varNameE "makeObj") . $(varE tdname) |]
617
  let fname = mkName ("save" ++ sname)
618
  sigt <- [t| $(conT name) -> JSON.JSValue |]
619
  return [SigD tdname tdsigt, FunD tdname [tclause],
620
          SigD fname sigt, ValD (VarP fname) (NormalB cclause) []]
621

    
622
saveObjectField :: Name -> Field -> Q Exp
623
saveObjectField fvar field
624
  | isContainer = [| [( $nameE , JSON.showJSON . showContainer $ $fvarE)] |]
625
  | fisOptional = [| case $(varE fvar) of
626
                      Nothing -> []
627
                      Just v -> [( $nameE, JSON.showJSON v)]
628
                  |]
629
  | otherwise = case fieldShow field of
630
      Nothing -> [| [( $nameE, JSON.showJSON $fvarE)] |]
631
      Just fn -> [| [( $nameE, JSON.showJSON . $fn $ $fvarE)] |]
632
  where isContainer = fieldIsContainer field
633
        fisOptional  = fieldIsOptional field
634
        nameE = stringE (fieldName field)
635
        fvarE = varE fvar
636

    
637
objectShowJSON :: String -> Q [Dec]
638
objectShowJSON name =
639
  [d| showJSON = JSON.showJSON . $(varE . mkName $ "save" ++ name) |]
640

    
641
genLoadObject :: (Field -> Q (Name, Stmt))
642
              -> String -> [Field] -> Q (Dec, Dec)
643
genLoadObject load_fn sname fields = do
644
  let name = mkName sname
645
      funname = mkName $ "load" ++ sname
646
      arg1 = mkName "v"
647
      objname = mkName "o"
648
      opid = mkName "op_id"
649
  st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
650
                                 (JSON.readJSON $(varE arg1)) |]
651
  fbinds <- mapM load_fn fields
652
  let (fnames, fstmts) = unzip fbinds
653
  let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
654
      fstmts' = st1:fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
655
  sigt <- [t| JSON.JSValue -> JSON.Result $(conT name) |]
656
  return $ (SigD funname sigt,
657
            FunD funname [Clause [VarP arg1] (NormalB (DoE fstmts')) []])
658

    
659
loadObjectField :: Field -> Q (Name, Stmt)
660
loadObjectField field = do
661
  let name = fieldVariable field
662
      fvar = mkName name
663
  -- these are used in all patterns below
664
  let objvar = varNameE "o"
665
      objfield = stringE (fieldName field)
666
      loadexp =
667
        if fieldIsOptional field
668
          then [| $(varNameE "maybeFromObj") $objvar $objfield |]
669
          else case fieldDefault field of
670
                 Just defv ->
671
                   [| $(varNameE "fromObjWithDefault") $objvar
672
                      $objfield $defv |]
673
                 Nothing -> [| $(varNameE "fromObj") $objvar $objfield |]
674
  bexp <- loadFn field loadexp
675

    
676
  return (fvar, BindS (VarP fvar) bexp)
677

    
678
objectReadJSON :: String -> Q Dec
679
objectReadJSON name = do
680
  let s = mkName "s"
681
  body <- [| case JSON.readJSON $(varE s) of
682
               JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s'
683
               JSON.Error e ->
684
                 JSON.Error $ "Can't parse value for type " ++
685
                       $(stringE name) ++ ": " ++ e
686
           |]
687
  return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
688

    
689
-- * Inheritable parameter tables implementation
690

    
691
-- | Compute parameter type names.
692
paramTypeNames :: String -> (String, String)
693
paramTypeNames root = ("Filled"  ++ root ++ "Params",
694
                       "Partial" ++ root ++ "Params")
695

    
696
-- | Compute information about the type of a parameter field.
697
paramFieldTypeInfo :: String -> Field -> Q (Name, Strict, Type)
698
paramFieldTypeInfo field_pfx fd = do
699
  t <- actualFieldType fd
700
  let n = mkName . (++ "P") . (field_pfx ++) .
701
          fieldRecordName $ fd
702
  return (n, NotStrict, AppT (ConT ''Maybe) t)
703

    
704
-- | Build a parameter declaration.
705
--
706
-- This function builds two different data structures: a /filled/ one,
707
-- in which all fields are required, and a /partial/ one, in which all
708
-- fields are optional. Due to the current record syntax issues, the
709
-- fields need to be named differrently for the two structures, so the
710
-- partial ones get a /P/ suffix.
711
buildParam :: String -> String -> [Field] -> Q [Dec]
712
buildParam sname field_pfx fields = do
713
  let (sname_f, sname_p) = paramTypeNames sname
714
      name_f = mkName sname_f
715
      name_p = mkName sname_p
716
  fields_f <- mapM (fieldTypeInfo field_pfx) fields
717
  fields_p <- mapM (paramFieldTypeInfo field_pfx) fields
718
  let decl_f = RecC name_f fields_f
719
      decl_p = RecC name_p fields_p
720
  let declF = DataD [] name_f [] [decl_f] [''Show, ''Read, ''Eq]
721
      declP = DataD [] name_p [] [decl_p] [''Show, ''Read, ''Eq]
722
  ser_decls_f <- buildObjectSerialisation sname_f fields
723
  ser_decls_p <- buildPParamSerialisation sname_p fields
724
  fill_decls <- fillParam sname field_pfx fields
725
  return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls
726

    
727
buildPParamSerialisation :: String -> [Field] -> Q [Dec]
728
buildPParamSerialisation sname fields = do
729
  let name = mkName sname
730
  savedecls <- genSaveObject savePParamField sname fields
731
  (loadsig, loadfn) <- genLoadObject loadPParamField sname fields
732
  shjson <- objectShowJSON sname
733
  rdjson <- objectReadJSON sname
734
  let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name))
735
                 (rdjson:shjson)
736
  return $ savedecls ++ [loadsig, loadfn, instdecl]
737

    
738
savePParamField :: Name -> Field -> Q Exp
739
savePParamField fvar field = do
740
  checkNonOptDef field
741
  let actualVal = mkName "v"
742
  normalexpr <- saveObjectField actualVal field
743
  -- we have to construct the block here manually, because we can't
744
  -- splice-in-splice
745
  return $ CaseE (VarE fvar) [ Match (ConP 'Nothing [])
746
                                       (NormalB (ConE '[])) []
747
                             , Match (ConP 'Just [VarP actualVal])
748
                                       (NormalB normalexpr) []
749
                             ]
750
loadPParamField :: Field -> Q (Name, Stmt)
751
loadPParamField field = do
752
  checkNonOptDef field
753
  let name = fieldName field
754
      fvar = mkName name
755
  -- these are used in all patterns below
756
  let objvar = varNameE "o"
757
      objfield = stringE name
758
      loadexp = [| $(varNameE "maybeFromObj") $objvar $objfield |]
759
  bexp <- loadFn field loadexp
760
  return (fvar, BindS (VarP fvar) bexp)
761

    
762
-- | Builds a simple declaration of type @n_x = fromMaybe f_x p_x@.
763
buildFromMaybe :: String -> Q Dec
764
buildFromMaybe fname =
765
  valD (varP (mkName $ "n_" ++ fname))
766
         (normalB [| $(varNameE "fromMaybe")
767
                        $(varNameE $ "f_" ++ fname)
768
                        $(varNameE $ "p_" ++ fname) |]) []
769

    
770
fillParam :: String -> String -> [Field] -> Q [Dec]
771
fillParam sname field_pfx fields = do
772
  let fnames = map (\fd -> field_pfx ++ fieldRecordName fd) fields
773
      (sname_f, sname_p) = paramTypeNames sname
774
      oname_f = "fobj"
775
      oname_p = "pobj"
776
      name_f = mkName sname_f
777
      name_p = mkName sname_p
778
      fun_name = mkName $ "fill" ++ sname ++ "Params"
779
      le_full = ValD (ConP name_f (map (VarP . mkName . ("f_" ++)) fnames))
780
                (NormalB . VarE . mkName $ oname_f) []
781
      le_part = ValD (ConP name_p (map (VarP . mkName . ("p_" ++)) fnames))
782
                (NormalB . VarE . mkName $ oname_p) []
783
      obj_new = foldl (\accu vname -> AppE accu (VarE vname)) (ConE name_f)
784
                $ map (mkName . ("n_" ++)) fnames
785
  le_new <- mapM buildFromMaybe fnames
786
  funt <- [t| $(conT name_f) -> $(conT name_p) -> $(conT name_f) |]
787
  let sig = SigD fun_name funt
788
      fclause = Clause [VarP (mkName oname_f), VarP (mkName oname_p)]
789
                (NormalB $ LetE (le_full:le_part:le_new) obj_new) []
790
      fun = FunD fun_name [fclause]
791
  return [sig, fun]