Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / THH.hs @ 92678b3c

History | View | Annotate | Download (17.6 kB)

1
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
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 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 ( Store(..)
33
                  , declareSADT
34
                  , makeJSONInstance
35
                  , genOpID
36
                  , genOpCode
37
                  , noDefault
38
                  , genStrOfOp
39
                  , genStrOfKey
40
                  , genLuxiOp
41
                  ) where
42

    
43
import Control.Monad (liftM, liftM2)
44
import Data.Char
45
import Data.List
46
import Language.Haskell.TH
47

    
48
import qualified Text.JSON as JSON
49

    
50
-- * Helper functions
51

    
52
-- | Ensure first letter is lowercase.
53
--
54
-- Used to convert type name to function prefix, e.g. in @data Aa ->
55
-- aaToString@.
56
ensureLower :: String -> String
57
ensureLower [] = []
58
ensureLower (x:xs) = toLower x:xs
59

    
60
-- | Helper for quoted expressions.
61
varNameE :: String -> Q Exp
62
varNameE = varE . mkName
63

    
64
-- | showJSON as an expression, for reuse.
65
showJSONE :: Q Exp
66
showJSONE = varNameE "showJSON"
67

    
68
-- | ToString function name.
69
toStrName :: String -> Name
70
toStrName = mkName . (++ "ToString") . ensureLower
71

    
72
-- | FromString function name.
73
fromStrName :: String -> Name
74
fromStrName = mkName . (++ "FromString") . ensureLower
75

    
76
-- | Converts a name to it's varE/litE representations.
77
--
78
reprE :: Either String Name -> Q Exp
79
reprE = either stringE varE
80

    
81
-- | Smarter function application.
82
--
83
-- This does simply f x, except that if is 'id', it will skip it, in
84
-- order to generate more readable code when using -ddump-splices.
85
appFn :: Exp -> Exp -> Exp
86
appFn f x | f == VarE 'id = x
87
          | otherwise = AppE f x
88

    
89
-- * Template code for simple string-equivalent ADTs
90

    
91
-- | Generates a data type declaration.
92
--
93
-- The type will have a fixed list of instances.
94
strADTDecl :: Name -> [String] -> Dec
95
strADTDecl name constructors =
96
    DataD [] name []
97
              (map (flip NormalC [] . mkName) constructors)
98
              [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
99

    
100
-- | Generates a toString function.
101
--
102
-- This generates a simple function of the form:
103
--
104
-- @
105
-- nameToString :: Name -> String
106
-- nameToString Cons1 = var1
107
-- nameToString Cons2 = \"value2\"
108
-- @
109
genToString :: Name -> Name -> [(String, Either String Name)] -> Q [Dec]
110
genToString fname tname constructors = do
111
  sigt <- [t| $(conT tname) -> String |]
112
  -- the body clauses, matching on the constructor and returning the
113
  -- string value
114
  clauses <- mapM  (\(c, v) -> clause [recP (mkName c) []]
115
                             (normalB (reprE v)) []) constructors
116
  return [SigD fname sigt, FunD fname clauses]
117

    
118
-- | Generates a fromString function.
119
--
120
-- The function generated is monadic and can fail parsing the
121
-- string. It is of the form:
122
--
123
-- @
124
-- nameFromString :: (Monad m) => String -> m Name
125
-- nameFromString s | s == var1       = Cons1
126
--                  | s == \"value2\" = Cons2
127
--                  | otherwise = fail /.../
128
-- @
129
genFromString :: Name -> Name -> [(String, Name)] -> Q [Dec]
130
genFromString fname tname constructors = do
131
  -- signature of form (Monad m) => String -> m $name
132
  sigt <- [t| (Monad m) => String -> m $(conT tname) |]
133
  -- clauses for a guarded pattern
134
  let varp = mkName "s"
135
      varpe = varE varp
136
  clauses <- mapM (\(c, v) -> do
137
                     -- the clause match condition
138
                     g <- normalG [| $varpe == $(varE v) |]
139
                     -- the clause result
140
                     r <- [| return $(conE (mkName c)) |]
141
                     return (g, r)) constructors
142
  -- the otherwise clause (fallback)
143
  oth_clause <- do
144
    g <- normalG [| otherwise |]
145
    r <- [|fail ("Invalid string value for type " ++
146
                 $(litE (stringL (nameBase tname))) ++ ": " ++ $varpe) |]
147
    return (g, r)
148
  let fun = FunD fname [Clause [VarP varp]
149
                        (GuardedB (clauses++[oth_clause])) []]
150
  return [SigD fname sigt, fun]
151

    
152
-- | Generates a data type from a given string format.
153
--
154
-- The format is expected to multiline. The first line contains the
155
-- type name, and the rest of the lines must contain two words: the
156
-- constructor name and then the string representation of the
157
-- respective constructor.
158
--
159
-- The function will generate the data type declaration, and then two
160
-- functions:
161
--
162
-- * /name/ToString, which converts the type to a string
163
--
164
-- * /name/FromString, which (monadically) converts from a string to the type
165
--
166
-- Note that this is basically just a custom show/read instance,
167
-- nothing else.
168
declareSADT :: String -> [(String, Name)] -> Q [Dec]
169
declareSADT sname cons = do
170
  let name = mkName sname
171
      ddecl = strADTDecl name (map fst cons)
172
      -- process cons in the format expected by genToString
173
      cons' = map (\(a, b) -> (a, Right b)) cons
174
  tostr <- genToString (toStrName sname) name cons'
175
  fromstr <- genFromString (fromStrName sname) name cons
176
  return $ ddecl:tostr ++ fromstr
177

    
178

    
179
-- | Creates the showJSON member of a JSON instance declaration.
180
--
181
-- This will create what is the equivalent of:
182
--
183
-- @
184
-- showJSON = showJSON . /name/ToString
185
-- @
186
--
187
-- in an instance JSON /name/ declaration
188
genShowJSON :: String -> Q [Dec]
189
genShowJSON name = [d| showJSON = JSON.showJSON . $(varE (toStrName name)) |]
190

    
191
-- | Creates the readJSON member of a JSON instance declaration.
192
--
193
-- This will create what is the equivalent of:
194
--
195
-- @
196
-- readJSON s = case readJSON s of
197
--                Ok s' -> /name/FromString s'
198
--                Error e -> Error /description/
199
-- @
200
--
201
-- in an instance JSON /name/ declaration
202
genReadJSON :: String -> Q Dec
203
genReadJSON name = do
204
  let s = mkName "s"
205
  body <- [| case JSON.readJSON $(varE s) of
206
               JSON.Ok s' -> $(varE (fromStrName name)) s'
207
               JSON.Error e ->
208
                   JSON.Error $ "Can't parse string value for type " ++
209
                           $(stringE name) ++ ": " ++ e
210
           |]
211
  return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
212

    
213
-- | Generates a JSON instance for a given type.
214
--
215
-- This assumes that the /name/ToString and /name/FromString functions
216
-- have been defined as by the 'declareSADT' function.
217
makeJSONInstance :: Name -> Q [Dec]
218
makeJSONInstance name = do
219
  let base = nameBase name
220
  showJ <- genShowJSON base
221
  readJ <- genReadJSON base
222
  return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) (readJ:showJ)]
223

    
224
-- * Template code for opcodes
225

    
226
-- | Transforms a CamelCase string into an_underscore_based_one.
227
deCamelCase :: String -> String
228
deCamelCase =
229
    intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
230

    
231
-- | Computes the name of a given constructor.
232
constructorName :: Con -> Q Name
233
constructorName (NormalC name _) = return name
234
constructorName (RecC name _)    = return name
235
constructorName x                = fail $ "Unhandled constructor " ++ show x
236

    
237
-- | Builds the generic constructor-to-string function.
238
--
239
-- This generates a simple function of the following form:
240
--
241
-- @
242
-- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
243
-- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
244
-- @
245
--
246
-- This builds a custom list of name/string pairs and then uses
247
-- 'genToString' to actually generate the function
248
genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
249
genConstrToStr trans_fun name fname = do
250
  TyConI (DataD _ _ _ cons _) <- reify name
251
  cnames <- mapM (liftM nameBase . constructorName) cons
252
  let svalues = map (Left . trans_fun) cnames
253
  genToString (mkName fname) name $ zip cnames svalues
254

    
255
-- | Constructor-to-string for OpCode.
256
genOpID :: Name -> String -> Q [Dec]
257
genOpID = genConstrToStr deCamelCase
258

    
259
-- | OpCode parameter (field) type.
260
type OpParam = (String, Q Type, Q Exp)
261

    
262
-- | Generates the OpCode data type.
263
--
264
-- This takes an opcode logical definition, and builds both the
265
-- datatype and the JSON serialisation out of it. We can't use a
266
-- generic serialisation since we need to be compatible with Ganeti's
267
-- own, so we have a few quirks to work around.
268
--
269
-- There are three things to be defined for each parameter:
270
--
271
-- * name
272
--
273
-- * type; if this is 'Maybe', will only be serialised if it's a
274
--   'Just' value
275
--
276
-- * default; if missing, won't raise an exception, but will instead
277
--   use the default
278
--
279
genOpCode :: String                -- ^ Type name to use
280
          -> [(String, [OpParam])] -- ^ Constructor name and parameters
281
          -> Q [Dec]
282
genOpCode name cons = do
283
  decl_d <- mapM (\(cname, fields) -> do
284
                    -- we only need the type of the field, without Q
285
                    fields' <- mapM (\(_, qt, _) ->
286
                                         qt >>= \t -> return (NotStrict, t))
287
                               fields
288
                    return $ NormalC (mkName cname) fields')
289
            cons
290
  let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
291

    
292
  (savesig, savefn) <- genSaveOpCode cons
293
  (loadsig, loadfn) <- genLoadOpCode cons
294
  return [declD, loadsig, loadfn, savesig, savefn]
295

    
296
-- | Checks whether a given parameter is options.
297
--
298
-- This requires that it's a 'Maybe'.
299
isOptional :: Type -> Bool
300
isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
301
isOptional _ = False
302

    
303
-- | Generates the \"save\" expression for a single opcode parameter.
304
--
305
-- There is only one special handling mode: if the parameter is of
306
-- 'Maybe' type, then we only save it if it's a 'Just' value,
307
-- otherwise we skip it.
308
saveField :: Name    -- ^ The name of variable that contains the value
309
          -> OpParam -- ^ Parameter definition
310
          -> Q Exp
311
saveField fvar (fname, qt, _) = do
312
  t <- qt
313
  let fnexp = stringE fname
314
      fvare = varE fvar
315
  (if isOptional t
316
   then [| case $fvare of
317
             Just v' -> [( $fnexp, $showJSONE v')]
318
             Nothing -> []
319
         |]
320
   else [| [( $fnexp, $showJSONE $fvare )] |])
321

    
322
-- | Generates the \"save\" clause for an entire opcode constructor.
323
--
324
-- This matches the opcode with variables named the same as the
325
-- constructor fields (just so that the spliced in code looks nicer),
326
-- and passes those name plus the parameter definition to 'saveField'.
327
saveConstructor :: String    -- ^ The constructor name
328
                -> [OpParam] -- ^ The parameter definitions for this
329
                             -- constructor
330
                -> Q Clause  -- ^ Resulting clause
331
saveConstructor sname fields = do
332
  let cname = mkName sname
333
  let fnames = map (\(n, _, _) -> mkName n) fields
334
  let pat = conP cname (map varP fnames)
335
  let felems = map (uncurry saveField) (zip fnames fields)
336
      -- now build the OP_ID serialisation
337
      opid = [| [( $(stringE "OP_ID"),
338
                   $showJSONE $(stringE . deCamelCase $ sname) )] |]
339
      flist = listE (opid:felems)
340
      -- and finally convert all this to a json object
341
      flist' = [| $(varNameE "makeObj") (concat $flist) |]
342
  clause [pat] (normalB flist') []
343

    
344
-- | Generates the main save opcode function.
345
--
346
-- This builds a per-constructor match clause that contains the
347
-- respective constructor-serialisation code.
348
genSaveOpCode :: [(String, [OpParam])] -> Q (Dec, Dec)
349
genSaveOpCode opdefs = do
350
  cclauses <- mapM (uncurry saveConstructor) opdefs
351
  let fname = mkName "saveOpCode"
352
  sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |]
353
  return $ (SigD fname sigt, FunD fname cclauses)
354

    
355
-- | Generates the \"load\" field for a single parameter.
356
--
357
-- There is custom handling, depending on how the parameter is
358
-- specified. For a 'Maybe' type parameter, we allow that it is not
359
-- present (via 'Utils.maybeFromObj'). Otherwise, if there is a
360
-- default value, we allow the parameter to be abset, and finally if
361
-- there is no default value, we require its presence.
362
loadField :: OpParam -> Q (Name, Stmt)
363
loadField (fname, qt, qdefa) = do
364
  let fvar = mkName fname
365
  t <- qt
366
  defa <- qdefa
367
  -- these are used in all patterns below
368
  let objvar = varNameE "o"
369
      objfield = stringE fname
370
  bexp <- if isOptional t
371
          then [| $((varNameE "maybeFromObj")) $objvar $objfield |]
372
          else case defa of
373
                 AppE (ConE dt) defval | dt == 'Just ->
374
                   -- but has a default value
375
                   [| $(varNameE "fromObjWithDefault")
376
                      $objvar $objfield $(return defval) |]
377
                 ConE dt | dt == 'Nothing ->
378
                     [| $(varNameE "fromObj") $objvar $objfield |]
379
                 s -> fail $ "Invalid default value " ++ show s ++
380
                      ", expecting either 'Nothing' or a 'Just defval'"
381
  return (fvar, BindS (VarP fvar) bexp)
382

    
383
loadConstructor :: String -> [OpParam] -> Q Exp
384
loadConstructor sname fields = do
385
  let name = mkName sname
386
  fbinds <- mapM loadField fields
387
  let (fnames, fstmts) = unzip fbinds
388
  let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
389
      fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
390
  return $ DoE fstmts'
391

    
392
genLoadOpCode :: [(String, [OpParam])] -> Q (Dec, Dec)
393
genLoadOpCode opdefs = do
394
  let fname = mkName "loadOpCode"
395
      arg1 = mkName "v"
396
      objname = mkName "o"
397
      opid = mkName "op_id"
398
  st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
399
                                 (JSON.readJSON $(varE arg1)) |]
400
  st2 <- bindS (varP opid) [| $(varNameE "fromObj")
401
                              $(varE objname) $(stringE "OP_ID") |]
402
  -- the match results (per-constructor blocks)
403
  mexps <- mapM (uncurry loadConstructor) opdefs
404
  fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
405
  let mpats = map (\(me, c) ->
406
                       let mp = LitP . StringL . deCamelCase . fst $ c
407
                       in Match mp (NormalB me) []
408
                  ) $ zip mexps opdefs
409
      defmatch = Match WildP (NormalB fails) []
410
      cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
411
      body = DoE [st1, st2, cst]
412
  sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
413
  return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
414

    
415
-- | No default type.
416
noDefault :: Q Exp
417
noDefault = conE 'Nothing
418

    
419
-- * Template code for luxi
420

    
421
-- | Constructor-to-string for LuxiOp.
422
genStrOfOp :: Name -> String -> Q [Dec]
423
genStrOfOp = genConstrToStr id
424

    
425
-- | Constructor-to-string for MsgKeys.
426
genStrOfKey :: Name -> String -> Q [Dec]
427
genStrOfKey = genConstrToStr ensureLower
428

    
429
-- | LuxiOp parameter type.
430
type LuxiParam = (String, Q Type, Q Exp)
431

    
432
-- | Storage options for JSON.
433
data Store = SList | SDict
434

    
435
-- | Generates the LuxiOp data type.
436
--
437
-- This takes a Luxi operation definition and builds both the
438
-- datatype and the function trnasforming the arguments to JSON.
439
-- We can't use anything less generic, because the way different
440
-- operations are serialized differs on both parameter- and top-level.
441
--
442
-- There are three things to be defined for each parameter:
443
--
444
-- * name
445
--
446
-- * type
447
--
448
-- * operation; this is the operation performed on the parameter before
449
--   serialization
450
--
451
genLuxiOp :: String -> [(String, [LuxiParam], Store)] -> Q [Dec]
452
genLuxiOp name cons = do
453
  decl_d <- mapM (\(cname, fields, _) -> do
454
                    fields' <- mapM (\(_, qt, _) ->
455
                                         qt >>= \t -> return (NotStrict, t))
456
                               fields
457
                    return $ NormalC (mkName cname) fields')
458
            cons
459
  let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read]
460
  (savesig, savefn) <- genSaveLuxiOp cons
461
  return [declD, savesig, savefn]
462

    
463
-- | Generates a Q Exp for an element, depending of the JSON return type.
464
helperLuxiField :: Store -> String -> Q Exp -> Q Exp
465
helperLuxiField SList name val = [| [ JSON.showJSON $val ] |]
466
helperLuxiField SDict name val = [| [(name, JSON.showJSON $val)] |]
467

    
468
-- | Generates the \"save\" expression for a single luxi parameter.
469
saveLuxiField :: Store -> Name -> LuxiParam -> Q Exp
470
saveLuxiField store fvar (fname, qt, fn) = do
471
  t <- qt
472
  let fvare = varE fvar
473
  (if isOptional t
474
   then [| case $fvare of
475
             Just v' ->
476
                 $(helperLuxiField store fname $ liftM2 appFn fn [| v' |])
477
             Nothing -> []
478
         |]
479
   else helperLuxiField store fname $ liftM2 appFn fn fvare)
480

    
481
-- | Generates final JSON Q Exp for constructor.
482
helperLuxiConstructor :: Store -> Q Exp -> Q Exp
483
helperLuxiConstructor SDict val = [| JSON.showJSON $ JSON.makeObj $val |]
484
helperLuxiConstructor SList val = [| JSON.JSArray $val |]
485

    
486
-- | Generates the \"save\" clause for entire LuxiOp constructor.
487
saveLuxiConstructor :: (String, [LuxiParam], Store) -> Q Clause
488
saveLuxiConstructor (sname, fields, store) = do
489
  let cname = mkName sname
490
      fnames = map (\(nm, _, _) -> mkName nm) fields
491
      pat = conP cname (map varP fnames)
492
      flist = map (uncurry $ saveLuxiField store) (zip fnames fields)
493
      flist' = appE [| concat |] (listE flist)
494
      finval = helperLuxiConstructor store flist'
495
  clause [pat] (normalB finval) []
496

    
497
-- | Generates the main save LuxiOp function.
498
genSaveLuxiOp :: [(String, [LuxiParam], Store)]-> Q (Dec, Dec)
499
genSaveLuxiOp opdefs = do
500
  sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
501
  let fname = mkName "opToArgs"
502
  cclauses <- mapM saveLuxiConstructor opdefs
503
  return $ (SigD fname sigt, FunD fname cclauses)