Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / THH.hs @ c2e60027

History | View | Annotate | Download (28.8 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 :: 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
loadFn :: Field -> Q Exp -> Q Exp
148
loadFn (Field { fieldIsContainer = True }) expr = [| $expr >>= readContainer |]
149
loadFn (Field { fieldRead = Just readfn }) expr = [| $expr >>= $readfn |]
150
loadFn _ expr = expr
151

    
152

    
153
-- * Common field declarations
154

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

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

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

    
168
-- * Helper functions
169

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
369
-- * Template code for opcodes
370

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

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

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

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

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

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

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

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

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

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

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

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

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

    
506
-- * Template code for luxi
507

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

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

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

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

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

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

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

    
575
-- * "Objects" functionality
576

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

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

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

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

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

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

    
641
objectShowJSON :: String -> Q Dec
642
objectShowJSON name = do
643
  body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |]
644
  return $ FunD (mkName "showJSON") [Clause [] (NormalB body) []]
645

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

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

    
681
  return (fvar, BindS (VarP fvar) bexp)
682

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

    
694
-- * Inheritable parameter tables implementation
695

    
696
-- | Compute parameter type names.
697
paramTypeNames :: String -> (String, String)
698
paramTypeNames root = ("Filled"  ++ root ++ "Params",
699
                       "Partial" ++ root ++ "Params")
700

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

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

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

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

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

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