Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / THH.hs @ 53664e15

History | View | Annotate | Download (13.9 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
                  ) where
38

    
39
import Control.Monad (liftM)
40
import Data.Char
41
import Data.List
42
import Language.Haskell.TH
43

    
44
import qualified Text.JSON as JSON
45

    
46
-- * Helper functions
47

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

    
56
-- | Helper for quoted expressions.
57
varNameE :: String -> Q Exp
58
varNameE = varE . mkName
59

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

    
64
-- | ToString function name.
65
toStrName :: String -> Name
66
toStrName = mkName . (++ "ToString") . ensureLower
67

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

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

    
77
-- * Template code for simple string-equivalent ADTs
78

    
79
-- | Generates a data type declaration.
80
--
81
-- The type will have a fixed list of instances.
82
strADTDecl :: Name -> [String] -> Dec
83
strADTDecl name constructors =
84
    DataD [] name []
85
              (map (flip NormalC [] . mkName) constructors)
86
              [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
87

    
88
-- | Generates a toString function.
89
--
90
-- This generates a simple function of the form:
91
--
92
-- @
93
-- nameToString :: Name -> String
94
-- nameToString Cons1 = var1
95
-- nameToString Cons2 = \"value2\"
96
-- @
97
genToString :: Name -> Name -> [(String, Either String Name)] -> Q [Dec]
98
genToString fname tname constructors = do
99
  sigt <- [t| $(conT tname) -> String |]
100
  -- the body clauses, matching on the constructor and returning the
101
  -- string value
102
  clauses <- mapM  (\(c, v) -> clause [recP (mkName c) []]
103
                             (normalB (reprE v)) []) constructors
104
  return [SigD fname sigt, FunD fname clauses]
105

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

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

    
166

    
167
-- | Creates the showJSON member of a JSON instance declaration.
168
--
169
-- This will create what is the equivalent of:
170
--
171
-- @
172
-- showJSON = showJSON . /name/ToString
173
-- @
174
--
175
-- in an instance JSON /name/ declaration
176
genShowJSON :: String -> Q [Dec]
177
genShowJSON name = [d| showJSON = JSON.showJSON . $(varE (toStrName name)) |]
178

    
179
-- | Creates the readJSON member of a JSON instance declaration.
180
--
181
-- This will create what is the equivalent of:
182
--
183
-- @
184
-- readJSON s = case readJSON s of
185
--                Ok s' -> /name/FromString s'
186
--                Error e -> Error /description/
187
-- @
188
--
189
-- in an instance JSON /name/ declaration
190
genReadJSON :: String -> Q Dec
191
genReadJSON name = do
192
  let s = mkName "s"
193
  body <- [| case JSON.readJSON $(varE s) of
194
               JSON.Ok s' -> $(varE (fromStrName name)) s'
195
               JSON.Error e ->
196
                   JSON.Error $ "Can't parse string value for type " ++
197
                           $(stringE name) ++ ": " ++ e
198
           |]
199
  return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
200

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

    
212
-- * Template code for opcodes
213

    
214
-- | Transforms a CamelCase string into an_underscore_based_one.
215
deCamelCase :: String -> String
216
deCamelCase =
217
    intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
218

    
219
-- | Computes the name of a given constructor
220
constructorName :: Con -> Q Name
221
constructorName (NormalC name _) = return name
222
constructorName (RecC name _)    = return name
223
constructorName x                = fail $ "Unhandled constructor " ++ show x
224

    
225
-- | Builds the constructor-to-string function.
226
--
227
-- This generates a simple function of the following form:
228
--
229
-- @
230
-- fname (ConStructorOne {}) = "CON_STRUCTOR_ONE"
231
-- fname (ConStructorTwo {}) = "CON_STRUCTOR_TWO"
232
-- @
233
--
234
-- This builds a custom list of name/string pairs and then uses
235
-- 'genToString' to actually generate the function
236
genOpID :: Name -> String -> Q [Dec]
237
genOpID name fname = do
238
  TyConI (DataD _ _ _ cons _) <- reify name
239
  cnames <- mapM (liftM nameBase . constructorName) cons
240
  let svalues = map (Left . deCamelCase) cnames
241
  genToString (mkName fname) name $ zip cnames svalues
242

    
243

    
244
-- | OpCode parameter (field) type
245
type OpParam = (String, Q Type, Q Exp)
246

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

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

    
281
-- | Checks whether a given parameter is options
282
--
283
-- This requires that it's a 'Maybe'.
284
isOptional :: Type -> Bool
285
isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
286
isOptional _ = False
287

    
288
-- | Generates the \"save\" expression for a single opcode parameter.
289
--
290
-- There is only one special handling mode: if the parameter is of
291
-- 'Maybe' type, then we only save it if it's a 'Just' value,
292
-- otherwise we skip it.
293
saveField :: Name    -- ^ The name of variable that contains the value
294
          -> OpParam -- ^ Parameter definition
295
          -> Q Exp
296
saveField fvar (fname, qt, _) = do
297
  t <- qt
298
  let fnexp = stringE fname
299
      fvare = varE fvar
300
  (if isOptional t
301
   then [| case $fvare of
302
             Just v' -> [( $fnexp, $showJSONE v')]
303
             Nothing -> []
304
         |]
305
   else [| [( $fnexp, $showJSONE $fvare )] |])
306

    
307
-- | Generates the \"save\" clause for an entire opcode constructor.
308
--
309
-- This matches the opcode with variables named the same as the
310
-- constructor fields (just so that the spliced in code looks nicer),
311
-- and passes those name plus the parameter definition to 'saveField'.
312
saveConstructor :: String    -- ^ The constructor name
313
                -> [OpParam] -- ^ The parameter definitions for this
314
                             -- constructor
315
                -> Q Clause  -- ^ Resulting clause
316
saveConstructor sname fields = do
317
  let cname = mkName sname
318
  let fnames = map (\(n, _, _) -> mkName n) fields
319
  let pat = conP cname (map varP fnames)
320
  let felems = map (uncurry saveField) (zip fnames fields)
321
      -- now build the OP_ID serialisation
322
      opid = [| [( $(stringE "OP_ID"),
323
                   $showJSONE $(stringE . deCamelCase $ sname) )] |]
324
      flist = listE (opid:felems)
325
      -- and finally convert all this to a json object
326
      flist' = [| $(varNameE "makeObj") (concat $flist) |]
327
  clause [pat] (normalB flist') []
328

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

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

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

    
377
genLoadOpCode :: [(String, [OpParam])] -> Q (Dec, Dec)
378
genLoadOpCode opdefs = do
379
  let fname = mkName "loadOpCode"
380
      arg1 = mkName "v"
381
      objname = mkName "o"
382
      opid = mkName "op_id"
383
  st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
384
                                 (JSON.readJSON $(varE arg1)) |]
385
  st2 <- bindS (varP opid) [| $(varNameE "fromObj")
386
                              $(varE objname) $(stringE "OP_ID") |]
387
  -- the match results (per-constructor blocks)
388
  mexps <- mapM (uncurry loadConstructor) opdefs
389
  fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
390
  let mpats = map (\(me, c) ->
391
                       let mp = LitP . StringL . deCamelCase . fst $ c
392
                       in Match mp (NormalB me) []
393
                  ) $ zip mexps opdefs
394
      defmatch = Match WildP (NormalB fails) []
395
      cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
396
      body = DoE [st1, st2, cst]
397
  sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
398
  return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
399

    
400
-- | No default type.
401
noDefault :: Q Exp
402
noDefault = conE 'Nothing