THH.hs 16.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}

{-| TemplateHaskell helper for HTools.

As TemplateHaskell require that splices be defined in a separate
module, we combine all the TemplateHaskell functionality that HTools
needs in this module (except the one for unittests).

-}

{-

Copyright (C) 2011 Google Inc.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.

-}

module Ganeti.THH ( declareSADT
                  , makeJSONInstance
34
                  , genOpID
35
36
                  , genOpCode
                  , noDefault
37
38
39
                  , genStrOfOp
                  , genStrOfKey
                  , genLuxiOp
40
41
                  ) where

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

import qualified Text.JSON as JSON

Iustin Pop's avatar
Iustin Pop committed
49
50
-- * Helper functions

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

Iustin Pop's avatar
Iustin Pop committed
59
60
61
62
63
64
65
66
-- | Helper for quoted expressions.
varNameE :: String -> Q Exp
varNameE = varE . mkName

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

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

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

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

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

Iustin Pop's avatar
Iustin Pop committed
88
-- * Template code for simple string-equivalent ADTs
89

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

-- | Generates a toString function.
--
-- This generates a simple function of the form:
--
-- @
-- nameToString :: Name -> String
-- nameToString Cons1 = var1
-- nameToString Cons2 = \"value2\"
-- @
108
genToString :: Name -> Name -> [(String, Either String Name)] -> Q [Dec]
109
110
111
112
113
genToString fname tname constructors = do
  sigt <- [t| $(conT tname) -> String |]
  -- the body clauses, matching on the constructor and returning the
  -- string value
  clauses <- mapM  (\(c, v) -> clause [recP (mkName c) []]
114
                             (normalB (reprE v)) []) constructors
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
  return [SigD fname sigt, FunD fname clauses]

-- | Generates a fromString function.
--
-- The function generated is monadic and can fail parsing the
-- string. It is of the form:
--
-- @
-- nameFromString :: (Monad m) => String -> m Name
-- nameFromString s | s == var1       = Cons1
--                  | s == \"value2\" = Cons2
--                  | otherwise = fail /.../
-- @
genFromString :: Name -> Name -> [(String, Name)] -> Q [Dec]
genFromString fname tname constructors = do
  -- signature of form (Monad m) => String -> m $name
  sigt <- [t| (Monad m) => String -> m $(conT tname) |]
  -- clauses for a guarded pattern
  let varp = mkName "s"
      varpe = varE varp
  clauses <- mapM (\(c, v) -> do
                     -- the clause match condition
                     g <- normalG [| $varpe == $(varE v) |]
                     -- the clause result
                     r <- [| return $(conE (mkName c)) |]
                     return (g, r)) constructors
  -- the otherwise clause (fallback)
  oth_clause <- do
    g <- normalG [| otherwise |]
    r <- [|fail ("Invalid string value for type " ++
                 $(litE (stringL (nameBase tname))) ++ ": " ++ $varpe) |]
    return (g, r)
  let fun = FunD fname [Clause [VarP varp]
                        (GuardedB (clauses++[oth_clause])) []]
  return [SigD fname sigt, fun]

-- | Generates a data type from a given string format.
--
-- The format is expected to multiline. The first line contains the
-- type name, and the rest of the lines must contain two words: the
-- constructor name and then the string representation of the
-- respective constructor.
--
-- The function will generate the data type declaration, and then two
-- functions:
--
-- * /name/ToString, which converts the type to a string
--
-- * /name/FromString, which (monadically) converts from a string to the type
--
-- Note that this is basically just a custom show/read instance,
-- nothing else.
declareSADT :: String -> [(String, Name)] -> Q [Dec]
declareSADT sname cons = do
  let name = mkName sname
      ddecl = strADTDecl name (map fst cons)
171
172
173
      -- process cons in the format expected by genToString
      cons' = map (\(a, b) -> (a, Right b)) cons
  tostr <- genToString (toStrName sname) name cons'
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
  fromstr <- genFromString (fromStrName sname) name cons
  return $ ddecl:tostr ++ fromstr


-- | Creates the showJSON member of a JSON instance declaration.
--
-- This will create what is the equivalent of:
--
-- @
-- showJSON = showJSON . /name/ToString
-- @
--
-- in an instance JSON /name/ declaration
genShowJSON :: String -> Q [Dec]
genShowJSON name = [d| showJSON = JSON.showJSON . $(varE (toStrName name)) |]

-- | Creates the readJSON member of a JSON instance declaration.
--
-- This will create what is the equivalent of:
--
-- @
-- readJSON s = case readJSON s of
--                Ok s' -> /name/FromString s'
--                Error e -> Error /description/
-- @
--
-- in an instance JSON /name/ declaration
genReadJSON :: String -> Q Dec
genReadJSON name = do
  let s = mkName "s"
  body <- [| case JSON.readJSON $(varE s) of
               JSON.Ok s' -> $(varE (fromStrName name)) s'
               JSON.Error e ->
                   JSON.Error $ "Can't parse string value for type " ++
Iustin Pop's avatar
Iustin Pop committed
208
                           $(stringE name) ++ ": " ++ e
209
210
211
212
213
214
215
216
217
218
219
220
221
           |]
  return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]

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

Iustin Pop's avatar
Iustin Pop committed
223
224
-- * Template code for opcodes

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

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

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

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

258
-- | OpCode parameter (field) type.
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
type OpParam = (String, Q Type, Q Exp)

-- | Generates the OpCode data type.
--
-- This takes an opcode logical definition, and builds both the
-- datatype and the JSON serialisation out of it. We can't use a
-- generic serialisation since we need to be compatible with Ganeti's
-- own, so we have a few quirks to work around.
--
-- There are three things to be defined for each parameter:
--
-- * name
--
-- * type; if this is 'Maybe', will only be serialised if it's a
--   'Just' value
--
-- * default; if missing, won't raise an exception, but will instead
--   use the default
--
genOpCode :: String                -- ^ Type name to use
          -> [(String, [OpParam])] -- ^ Constructor name and parameters
          -> Q [Dec]
genOpCode name cons = do
  decl_d <- mapM (\(cname, fields) -> do
                    -- we only need the type of the field, without Q
                    fields' <- mapM (\(_, qt, _) ->
                                         qt >>= \t -> return (NotStrict, t))
                               fields
                    return $ NormalC (mkName cname) fields')
            cons
  let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]

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

295
-- | Checks whether a given parameter is options.
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
--
-- This requires that it's a 'Maybe'.
isOptional :: Type -> Bool
isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
isOptional _ = False

-- | Generates the \"save\" expression for a single opcode parameter.
--
-- There is only one special handling mode: if the parameter is of
-- 'Maybe' type, then we only save it if it's a 'Just' value,
-- otherwise we skip it.
saveField :: Name    -- ^ The name of variable that contains the value
          -> OpParam -- ^ Parameter definition
          -> Q Exp
saveField fvar (fname, qt, _) = do
  t <- qt
Iustin Pop's avatar
Iustin Pop committed
312
  let fnexp = stringE fname
313
314
315
      fvare = varE fvar
  (if isOptional t
   then [| case $fvare of
Iustin Pop's avatar
Iustin Pop committed
316
             Just v' -> [( $fnexp, $showJSONE v')]
317
318
             Nothing -> []
         |]
Iustin Pop's avatar
Iustin Pop committed
319
   else [| [( $fnexp, $showJSONE $fvare )] |])
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335

-- | Generates the \"save\" clause for an entire opcode constructor.
--
-- This matches the opcode with variables named the same as the
-- constructor fields (just so that the spliced in code looks nicer),
-- and passes those name plus the parameter definition to 'saveField'.
saveConstructor :: String    -- ^ The constructor name
                -> [OpParam] -- ^ The parameter definitions for this
                             -- constructor
                -> Q Clause  -- ^ Resulting clause
saveConstructor sname fields = do
  let cname = mkName sname
  let fnames = map (\(n, _, _) -> mkName n) fields
  let pat = conP cname (map varP fnames)
  let felems = map (uncurry saveField) (zip fnames fields)
      -- now build the OP_ID serialisation
Iustin Pop's avatar
Iustin Pop committed
336
337
      opid = [| [( $(stringE "OP_ID"),
                   $showJSONE $(stringE . deCamelCase $ sname) )] |]
338
339
      flist = listE (opid:felems)
      -- and finally convert all this to a json object
Iustin Pop's avatar
Iustin Pop committed
340
      flist' = [| $(varNameE "makeObj") (concat $flist) |]
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
  clause [pat] (normalB flist') []

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

-- | Generates the \"load\" field for a single parameter.
--
-- There is custom handling, depending on how the parameter is
-- specified. For a 'Maybe' type parameter, we allow that it is not
-- present (via 'Utils.maybeFromObj'). Otherwise, if there is a
-- default value, we allow the parameter to be abset, and finally if
-- there is no default value, we require its presence.
loadField :: OpParam -> Q (Name, Stmt)
loadField (fname, qt, qdefa) = do
  let fvar = mkName fname
  t <- qt
  defa <- qdefa
  -- these are used in all patterns below
Iustin Pop's avatar
Iustin Pop committed
367
368
  let objvar = varNameE "o"
      objfield = stringE fname
369
  bexp <- if isOptional t
Iustin Pop's avatar
Iustin Pop committed
370
          then [| $((varNameE "maybeFromObj")) $objvar $objfield |]
371
372
373
          else case defa of
                 AppE (ConE dt) defval | dt == 'Just ->
                   -- but has a default value
Iustin Pop's avatar
Iustin Pop committed
374
                   [| $(varNameE "fromObjWithDefault")
375
376
                      $objvar $objfield $(return defval) |]
                 ConE dt | dt == 'Nothing ->
Iustin Pop's avatar
Iustin Pop committed
377
                     [| $(varNameE "fromObj") $objvar $objfield |]
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
                 s -> fail $ "Invalid default value " ++ show s ++
                      ", expecting either 'Nothing' or a 'Just defval'"
  return (fvar, BindS (VarP fvar) bexp)

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

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

-- | No default type.
noDefault :: Q Exp
noDefault = conE 'Nothing
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446

-- * Template code for luxi

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

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

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

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

-- | Generates the \"save\" clause for entire LuxiOp constructor.
Agata Murawska's avatar
Agata Murawska committed
460
461
saveLuxiConstructor :: (String, [LuxiParam]) -> Q Clause
saveLuxiConstructor (sname, fields) =
462
463
464
  let cname = mkName sname
      fnames = map (\(nm, _, _) -> mkName nm) fields
      pat = conP cname (map varP fnames)
Agata Murawska's avatar
Agata Murawska committed
465
466
467
468
469
470
      flist = map (\(nm, _, fn) -> liftM2 appFn fn $ (varNameE nm)) fields
      showlist = map (\x -> [| JSON.showJSON $x |]) flist
      finval = case showlist of
                 [] -> [| JSON.showJSON () |]
                 _ -> [| JSON.showJSON $(listE showlist) |]
  in clause [pat] (normalB finval) []
471
472

-- | Generates the main save LuxiOp function.
Agata Murawska's avatar
Agata Murawska committed
473
genSaveLuxiOp :: [(String, [LuxiParam])] -> Q (Dec, Dec)
474
475
476
477
478
genSaveLuxiOp opdefs = do
  sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
  let fname = mkName "opToArgs"
  cclauses <- mapM saveLuxiConstructor opdefs
  return $ (SigD fname sigt, FunD fname cclauses)