1 {-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
3 {-| TemplateHaskell helper for HTools.
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).
13 Copyright (C) 2011 Google Inc.
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.
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.
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
32 module Ganeti.THH ( declareSADT
44 import Control.Monad (liftM, liftM2)
47 import Language.Haskell.TH
49 import qualified Text.JSON as JSON
53 -- | Ensure first letter is lowercase.
55 -- Used to convert type name to function prefix, e.g. in @data Aa ->
57 ensureLower :: String -> String
59 ensureLower (x:xs) = toLower x:xs
61 -- | Helper for quoted expressions.
62 varNameE :: String -> Q Exp
63 varNameE = varE . mkName
65 -- | showJSON as an expression, for reuse.
67 showJSONE = varNameE "showJSON"
69 -- | ToString function name.
70 toStrName :: String -> Name
71 toStrName = mkName . (++ "ToString") . ensureLower
73 -- | ToInt function name.
74 toIntName :: String -> Name
75 toIntName= mkName . (++ "ToInt") . ensureLower
77 -- | FromString function name.
78 fromStrName :: String -> Name
79 fromStrName = mkName . (++ "FromString") . ensureLower
81 -- | FromInt function name.
82 fromIntName:: String -> Name
83 fromIntName = mkName . (++ "FromInt") . ensureLower
85 -- | Converts a name to it's varE/litE representations.
87 reprE :: Either String Name -> Q Exp
88 reprE = either stringE varE
90 -- | Smarter function application.
92 -- This does simply f x, except that if is 'id', it will skip it, in
93 -- order to generate more readable code when using -ddump-splices.
94 appFn :: Exp -> Exp -> Exp
95 appFn f x | f == VarE 'id = x
96 | otherwise = AppE f x
98 -- * Template code for simple integer-equivalent ADTs
100 -- | Generates a data type declaration.
102 -- The type will have a fixed list of instances.
103 intADTDecl :: Name -> [String] -> Dec
104 intADTDecl name constructors =
106 (map (flip NormalC [] . mkName) constructors)
109 -- | Generates a toInt function.
110 genToInt :: Name -> Name -> [(String, Name)] -> Q [Dec]
111 genToInt fname tname constructors = do
112 sigt <- [t| $(conT tname) -> Int |]
113 clauses <- mapM (\(c, v) -> clause [recP (mkName c) []]
114 (normalB (varE v)) []) constructors
115 return [SigD fname sigt, FunD fname clauses]
117 -- | Generates a fromInt function.
118 genFromInt :: Name -> Name -> [(String, Name)] -> Q [Dec]
119 genFromInt fname tname constructors = do
120 sigt <- [t| (Monad m) => Int-> m $(conT tname) |]
121 let varp = mkName "s"
123 clauses <- mapM (\(c, v) -> do
124 g <- normalG [| $varpe == $(varE v) |]
125 r <- [| return $(conE (mkName c)) |]
126 return (g, r)) constructors
128 g <- normalG [| otherwise |]
129 r <- [|fail ("Invalid int value for type " ++
130 $(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |]
132 let fun = FunD fname [Clause [VarP varp]
133 (GuardedB (clauses++[oth_clause])) []]
134 return [SigD fname sigt, fun]
136 -- | Generates a data type from a given string format.
137 declareIADT:: String -> [(String, Name)] -> Q [Dec]
138 declareIADT sname cons = do
139 let name = mkName sname
140 ddecl = intADTDecl name (map fst cons)
141 tostr <- genToInt (toIntName sname) name cons
142 fromstr <- genFromInt (fromIntName sname) name cons
143 return $ ddecl:tostr ++ fromstr
145 -- | Creates the showJSON member of a JSON instance declaration.
146 genShowJSONInt :: String -> Q [Dec]
147 genShowJSONInt name = [d| showJSON = JSON.showJSON . $(varE (toIntName name)) |]
149 -- | Creates the readJSON member of a JSON instance declaration.
150 genReadJSONInt :: String -> Q Dec
151 genReadJSONInt name = do
153 body <- [| case JSON.readJSON $(varE s) of
154 JSON.Ok s' -> $(varE (fromIntName name)) s'
156 JSON.Error $ "Can't parse int value for type " ++
157 $(stringE name) ++ ": " ++ e
159 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
161 -- | Generates a JSON instance for a given type.
162 makeJSONInstanceInt :: Name -> Q [Dec]
163 makeJSONInstanceInt name = do
164 let base = nameBase name
165 showJ <- genShowJSONInt base
166 readJ <- genReadJSONInt base
167 return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) (readJ:showJ)]
169 -- * Template code for simple string-equivalent ADTs
171 -- | Generates a data type declaration.
173 -- The type will have a fixed list of instances.
174 strADTDecl :: Name -> [String] -> Dec
175 strADTDecl name constructors =
177 (map (flip NormalC [] . mkName) constructors)
178 [''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord]
180 -- | Generates a toString function.
182 -- This generates a simple function of the form:
185 -- nameToString :: Name -> String
186 -- nameToString Cons1 = var1
187 -- nameToString Cons2 = \"value2\"
189 genToString :: Name -> Name -> [(String, Either String Name)] -> Q [Dec]
190 genToString fname tname constructors = do
191 sigt <- [t| $(conT tname) -> String |]
192 -- the body clauses, matching on the constructor and returning the
194 clauses <- mapM (\(c, v) -> clause [recP (mkName c) []]
195 (normalB (reprE v)) []) constructors
196 return [SigD fname sigt, FunD fname clauses]
198 -- | Generates a fromString function.
200 -- The function generated is monadic and can fail parsing the
201 -- string. It is of the form:
204 -- nameFromString :: (Monad m) => String -> m Name
205 -- nameFromString s | s == var1 = Cons1
206 -- | s == \"value2\" = Cons2
207 -- | otherwise = fail /.../
209 genFromString :: Name -> Name -> [(String, Name)] -> Q [Dec]
210 genFromString fname tname constructors = do
211 -- signature of form (Monad m) => String -> m $name
212 sigt <- [t| (Monad m) => String -> m $(conT tname) |]
213 -- clauses for a guarded pattern
214 let varp = mkName "s"
216 clauses <- mapM (\(c, v) -> do
217 -- the clause match condition
218 g <- normalG [| $varpe == $(varE v) |]
220 r <- [| return $(conE (mkName c)) |]
221 return (g, r)) constructors
222 -- the otherwise clause (fallback)
224 g <- normalG [| otherwise |]
225 r <- [|fail ("Invalid string value for type " ++
226 $(litE (stringL (nameBase tname))) ++ ": " ++ $varpe) |]
228 let fun = FunD fname [Clause [VarP varp]
229 (GuardedB (clauses++[oth_clause])) []]
230 return [SigD fname sigt, fun]
232 -- | Generates a data type from a given string format.
234 -- The format is expected to multiline. The first line contains the
235 -- type name, and the rest of the lines must contain two words: the
236 -- constructor name and then the string representation of the
237 -- respective constructor.
239 -- The function will generate the data type declaration, and then two
242 -- * /name/ToString, which converts the type to a string
244 -- * /name/FromString, which (monadically) converts from a string to the type
246 -- Note that this is basically just a custom show/read instance,
248 declareSADT :: String -> [(String, Name)] -> Q [Dec]
249 declareSADT sname cons = do
250 let name = mkName sname
251 ddecl = strADTDecl name (map fst cons)
252 -- process cons in the format expected by genToString
253 cons' = map (\(a, b) -> (a, Right b)) cons
254 tostr <- genToString (toStrName sname) name cons'
255 fromstr <- genFromString (fromStrName sname) name cons
256 return $ ddecl:tostr ++ fromstr
259 -- | Creates the showJSON member of a JSON instance declaration.
261 -- This will create what is the equivalent of:
264 -- showJSON = showJSON . /name/ToString
267 -- in an instance JSON /name/ declaration
268 genShowJSON :: String -> Q [Dec]
269 genShowJSON name = [d| showJSON = JSON.showJSON . $(varE (toStrName name)) |]
271 -- | Creates the readJSON member of a JSON instance declaration.
273 -- This will create what is the equivalent of:
276 -- readJSON s = case readJSON s of
277 -- Ok s' -> /name/FromString s'
278 -- Error e -> Error /description/
281 -- in an instance JSON /name/ declaration
282 genReadJSON :: String -> Q Dec
283 genReadJSON name = do
285 body <- [| case JSON.readJSON $(varE s) of
286 JSON.Ok s' -> $(varE (fromStrName name)) s'
288 JSON.Error $ "Can't parse string value for type " ++
289 $(stringE name) ++ ": " ++ e
291 return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []]
293 -- | Generates a JSON instance for a given type.
295 -- This assumes that the /name/ToString and /name/FromString functions
296 -- have been defined as by the 'declareSADT' function.
297 makeJSONInstance :: Name -> Q [Dec]
298 makeJSONInstance name = do
299 let base = nameBase name
300 showJ <- genShowJSON base
301 readJ <- genReadJSON base
302 return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) (readJ:showJ)]
304 -- * Template code for opcodes
306 -- | Transforms a CamelCase string into an_underscore_based_one.
307 deCamelCase :: String -> String
309 intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b)
311 -- | Computes the name of a given constructor.
312 constructorName :: Con -> Q Name
313 constructorName (NormalC name _) = return name
314 constructorName (RecC name _) = return name
315 constructorName x = fail $ "Unhandled constructor " ++ show x
317 -- | Builds the generic constructor-to-string function.
319 -- This generates a simple function of the following form:
322 -- fname (ConStructorOne {}) = trans_fun("ConStructorOne")
323 -- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo")
326 -- This builds a custom list of name/string pairs and then uses
327 -- 'genToString' to actually generate the function
328 genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec]
329 genConstrToStr trans_fun name fname = do
330 TyConI (DataD _ _ _ cons _) <- reify name
331 cnames <- mapM (liftM nameBase . constructorName) cons
332 let svalues = map (Left . trans_fun) cnames
333 genToString (mkName fname) name $ zip cnames svalues
335 -- | Constructor-to-string for OpCode.
336 genOpID :: Name -> String -> Q [Dec]
337 genOpID = genConstrToStr deCamelCase
339 -- | OpCode parameter (field) type.
340 type OpParam = (String, Q Type, Q Exp)
342 -- | Generates the OpCode data type.
344 -- This takes an opcode logical definition, and builds both the
345 -- datatype and the JSON serialisation out of it. We can't use a
346 -- generic serialisation since we need to be compatible with Ganeti's
347 -- own, so we have a few quirks to work around.
349 -- There are three things to be defined for each parameter:
353 -- * type; if this is 'Maybe', will only be serialised if it's a
356 -- * default; if missing, won't raise an exception, but will instead
359 genOpCode :: String -- ^ Type name to use
360 -> [(String, [OpParam])] -- ^ Constructor name and parameters
362 genOpCode name cons = do
363 decl_d <- mapM (\(cname, fields) -> do
364 -- we only need the type of the field, without Q
365 fields' <- mapM (\(_, qt, _) ->
366 qt >>= \t -> return (NotStrict, t))
368 return $ NormalC (mkName cname) fields')
370 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq]
372 (savesig, savefn) <- genSaveOpCode cons
373 (loadsig, loadfn) <- genLoadOpCode cons
374 return [declD, loadsig, loadfn, savesig, savefn]
376 -- | Checks whether a given parameter is options.
378 -- This requires that it's a 'Maybe'.
379 isOptional :: Type -> Bool
380 isOptional (AppT (ConT dt) _) | dt == ''Maybe = True
383 -- | Generates the \"save\" expression for a single opcode parameter.
385 -- There is only one special handling mode: if the parameter is of
386 -- 'Maybe' type, then we only save it if it's a 'Just' value,
387 -- otherwise we skip it.
388 saveField :: Name -- ^ The name of variable that contains the value
389 -> OpParam -- ^ Parameter definition
391 saveField fvar (fname, qt, _) = do
393 let fnexp = stringE fname
396 then [| case $fvare of
397 Just v' -> [( $fnexp, $showJSONE v')]
400 else [| [( $fnexp, $showJSONE $fvare )] |])
402 -- | Generates the \"save\" clause for an entire opcode constructor.
404 -- This matches the opcode with variables named the same as the
405 -- constructor fields (just so that the spliced in code looks nicer),
406 -- and passes those name plus the parameter definition to 'saveField'.
407 saveConstructor :: String -- ^ The constructor name
408 -> [OpParam] -- ^ The parameter definitions for this
410 -> Q Clause -- ^ Resulting clause
411 saveConstructor sname fields = do
412 let cname = mkName sname
413 let fnames = map (\(n, _, _) -> mkName n) fields
414 let pat = conP cname (map varP fnames)
415 let felems = map (uncurry saveField) (zip fnames fields)
416 -- now build the OP_ID serialisation
417 opid = [| [( $(stringE "OP_ID"),
418 $showJSONE $(stringE . deCamelCase $ sname) )] |]
419 flist = listE (opid:felems)
420 -- and finally convert all this to a json object
421 flist' = [| $(varNameE "makeObj") (concat $flist) |]
422 clause [pat] (normalB flist') []
424 -- | Generates the main save opcode function.
426 -- This builds a per-constructor match clause that contains the
427 -- respective constructor-serialisation code.
428 genSaveOpCode :: [(String, [OpParam])] -> Q (Dec, Dec)
429 genSaveOpCode opdefs = do
430 cclauses <- mapM (uncurry saveConstructor) opdefs
431 let fname = mkName "saveOpCode"
432 sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |]
433 return $ (SigD fname sigt, FunD fname cclauses)
435 -- | Generates the \"load\" field for a single parameter.
437 -- There is custom handling, depending on how the parameter is
438 -- specified. For a 'Maybe' type parameter, we allow that it is not
439 -- present (via 'Utils.maybeFromObj'). Otherwise, if there is a
440 -- default value, we allow the parameter to be abset, and finally if
441 -- there is no default value, we require its presence.
442 loadField :: OpParam -> Q (Name, Stmt)
443 loadField (fname, qt, qdefa) = do
444 let fvar = mkName fname
447 -- these are used in all patterns below
448 let objvar = varNameE "o"
449 objfield = stringE fname
450 bexp <- if isOptional t
451 then [| $((varNameE "maybeFromObj")) $objvar $objfield |]
453 AppE (ConE dt) defval | dt == 'Just ->
454 -- but has a default value
455 [| $(varNameE "fromObjWithDefault")
456 $objvar $objfield $(return defval) |]
457 ConE dt | dt == 'Nothing ->
458 [| $(varNameE "fromObj") $objvar $objfield |]
459 s -> fail $ "Invalid default value " ++ show s ++
460 ", expecting either 'Nothing' or a 'Just defval'"
461 return (fvar, BindS (VarP fvar) bexp)
463 loadConstructor :: String -> [OpParam] -> Q Exp
464 loadConstructor sname fields = do
465 let name = mkName sname
466 fbinds <- mapM loadField fields
467 let (fnames, fstmts) = unzip fbinds
468 let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames
469 fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)]
472 genLoadOpCode :: [(String, [OpParam])] -> Q (Dec, Dec)
473 genLoadOpCode opdefs = do
474 let fname = mkName "loadOpCode"
477 opid = mkName "op_id"
478 st1 <- bindS (varP objname) [| liftM JSON.fromJSObject
479 (JSON.readJSON $(varE arg1)) |]
480 st2 <- bindS (varP opid) [| $(varNameE "fromObj")
481 $(varE objname) $(stringE "OP_ID") |]
482 -- the match results (per-constructor blocks)
483 mexps <- mapM (uncurry loadConstructor) opdefs
484 fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |]
485 let mpats = map (\(me, c) ->
486 let mp = LitP . StringL . deCamelCase . fst $ c
487 in Match mp (NormalB me) []
489 defmatch = Match WildP (NormalB fails) []
490 cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch]
491 body = DoE [st1, st2, cst]
492 sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |]
493 return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []])
495 -- | No default type.
497 noDefault = conE 'Nothing
499 -- * Template code for luxi
501 -- | Constructor-to-string for LuxiOp.
502 genStrOfOp :: Name -> String -> Q [Dec]
503 genStrOfOp = genConstrToStr id
505 -- | Constructor-to-string for MsgKeys.
506 genStrOfKey :: Name -> String -> Q [Dec]
507 genStrOfKey = genConstrToStr ensureLower
509 -- | LuxiOp parameter type.
510 type LuxiParam = (String, Q Type, Q Exp)
512 -- | Generates the LuxiOp data type.
514 -- This takes a Luxi operation definition and builds both the
515 -- datatype and the function trnasforming the arguments to JSON.
516 -- We can't use anything less generic, because the way different
517 -- operations are serialized differs on both parameter- and top-level.
519 -- There are three things to be defined for each parameter:
525 -- * operation; this is the operation performed on the parameter before
528 genLuxiOp :: String -> [(String, [LuxiParam])] -> Q [Dec]
529 genLuxiOp name cons = do
530 decl_d <- mapM (\(cname, fields) -> do
531 fields' <- mapM (\(_, qt, _) ->
532 qt >>= \t -> return (NotStrict, t))
534 return $ NormalC (mkName cname) fields')
536 let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read]
537 (savesig, savefn) <- genSaveLuxiOp cons
538 return [declD, savesig, savefn]
540 -- | Generates the \"save\" expression for a single luxi parameter.
541 saveLuxiField :: Name -> LuxiParam -> Q Exp
542 saveLuxiField fvar (_, qt, fn) =
543 [| JSON.showJSON ( $(liftM2 appFn fn $ varE fvar) ) |]
545 -- | Generates the \"save\" clause for entire LuxiOp constructor.
546 saveLuxiConstructor :: (String, [LuxiParam]) -> Q Clause
547 saveLuxiConstructor (sname, fields) = do
548 let cname = mkName sname
549 fnames = map (\(nm, _, _) -> mkName nm) fields
550 pat = conP cname (map varP fnames)
551 flist = map (uncurry saveLuxiField) (zip fnames fields)
552 finval = if null flist
553 then [| JSON.showJSON () |]
554 else [| JSON.showJSON $(listE flist) |]
555 clause [pat] (normalB finval) []
557 -- | Generates the main save LuxiOp function.
558 genSaveLuxiOp :: [(String, [LuxiParam])]-> Q (Dec, Dec)
559 genSaveLuxiOp opdefs = do
560 sigt <- [t| $(conT (mkName "LuxiOp")) -> JSON.JSValue |]
561 let fname = mkName "opToArgs"
562 cclauses <- mapM saveLuxiConstructor opdefs
563 return $ (SigD fname sigt, FunD fname cclauses)