Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / THH.hs @ 05ff7a00

History | View | Annotate | Download (16.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 ( declareSADT
33
                  , makeJSONInstance
34
                  , genOpID
35
                  , genOpCode
36
                  , noDefault
37
                  , genStrOfOp
38
                  , genStrOfKey
39
                  , genLuxiOp
40
                  ) where
41

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

    
47
import qualified Text.JSON as JSON
48

    
49
-- * Helper functions
50

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

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

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

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

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

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

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

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

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

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

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

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

    
177

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

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

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

    
223
-- * Template code for opcodes
224

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
418
-- * Template code for luxi
419

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

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

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

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

    
459
-- | Generates the \"save\" clause for entire LuxiOp constructor.
460
saveLuxiConstructor :: (String, [LuxiParam], Q Exp) -> Q Clause
461
saveLuxiConstructor (sname, fields, finfn) =
462
  let cname = mkName sname
463
      fnames = map (\(nm, _, _) -> mkName nm) fields
464
      pat = conP cname (map varP fnames)
465
      flist = map (\(nm, _, fn) -> liftM2 appFn fn $ varNameE nm) fields
466
      finval = appE finfn (tupE flist)
467
  in
468
    clause [pat] (normalB finval) []
469

    
470
-- | Generates the main save LuxiOp function.
471
genSaveLuxiOp :: [(String, [LuxiParam], Q Exp)] -> Q (Dec, Dec)
472
genSaveLuxiOp opdefs = do
473
  sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
474
  let fname = mkName "opToArgs"
475
  cclauses <- mapM saveLuxiConstructor opdefs
476
  return $ (SigD fname sigt, FunD fname cclauses)