root / htools / Ganeti / THH.hs @ 72bb6b4e
History | View | Annotate | Download (13.8 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 |
-- | Ensure first letter is lowercase. |
47 |
-- |
48 |
-- Used to convert type name to function prefix, e.g. in @data Aa -> |
49 |
-- aaToString@. |
50 |
ensureLower :: String -> String |
51 |
ensureLower [] = [] |
52 |
ensureLower (x:xs) = toLower x:xs |
53 |
|
54 |
-- | ToString function name. |
55 |
toStrName :: String -> Name |
56 |
toStrName = mkName . (++ "ToString") . ensureLower |
57 |
|
58 |
-- | FromString function name. |
59 |
fromStrName :: String -> Name |
60 |
fromStrName = mkName . (++ "FromString") . ensureLower |
61 |
|
62 |
-- | Converts a name to it's varE/litE representations. |
63 |
-- |
64 |
reprE :: Either String Name -> Q Exp |
65 |
reprE (Left name) = litE (StringL name) |
66 |
reprE (Right name) = varE name |
67 |
|
68 |
-- | Generates a data type declaration. |
69 |
-- |
70 |
-- The type will have a fixed list of instances. |
71 |
strADTDecl :: Name -> [String] -> Dec |
72 |
strADTDecl name constructors = |
73 |
DataD [] name [] |
74 |
(map (flip NormalC [] . mkName) constructors) |
75 |
[''Show, ''Read, ''Eq, ''Enum, ''Bounded, ''Ord] |
76 |
|
77 |
-- | Generates a toString function. |
78 |
-- |
79 |
-- This generates a simple function of the form: |
80 |
-- |
81 |
-- @ |
82 |
-- nameToString :: Name -> String |
83 |
-- nameToString Cons1 = var1 |
84 |
-- nameToString Cons2 = \"value2\" |
85 |
-- @ |
86 |
genToString :: Name -> Name -> [(String, Either String Name)] -> Q [Dec] |
87 |
genToString fname tname constructors = do |
88 |
sigt <- [t| $(conT tname) -> String |] |
89 |
-- the body clauses, matching on the constructor and returning the |
90 |
-- string value |
91 |
clauses <- mapM (\(c, v) -> clause [recP (mkName c) []] |
92 |
(normalB (reprE v)) []) constructors |
93 |
return [SigD fname sigt, FunD fname clauses] |
94 |
|
95 |
-- | Generates a fromString function. |
96 |
-- |
97 |
-- The function generated is monadic and can fail parsing the |
98 |
-- string. It is of the form: |
99 |
-- |
100 |
-- @ |
101 |
-- nameFromString :: (Monad m) => String -> m Name |
102 |
-- nameFromString s | s == var1 = Cons1 |
103 |
-- | s == \"value2\" = Cons2 |
104 |
-- | otherwise = fail /.../ |
105 |
-- @ |
106 |
genFromString :: Name -> Name -> [(String, Name)] -> Q [Dec] |
107 |
genFromString fname tname constructors = do |
108 |
-- signature of form (Monad m) => String -> m $name |
109 |
sigt <- [t| (Monad m) => String -> m $(conT tname) |] |
110 |
-- clauses for a guarded pattern |
111 |
let varp = mkName "s" |
112 |
varpe = varE varp |
113 |
clauses <- mapM (\(c, v) -> do |
114 |
-- the clause match condition |
115 |
g <- normalG [| $varpe == $(varE v) |] |
116 |
-- the clause result |
117 |
r <- [| return $(conE (mkName c)) |] |
118 |
return (g, r)) constructors |
119 |
-- the otherwise clause (fallback) |
120 |
oth_clause <- do |
121 |
g <- normalG [| otherwise |] |
122 |
r <- [|fail ("Invalid string value for type " ++ |
123 |
$(litE (stringL (nameBase tname))) ++ ": " ++ $varpe) |] |
124 |
return (g, r) |
125 |
let fun = FunD fname [Clause [VarP varp] |
126 |
(GuardedB (clauses++[oth_clause])) []] |
127 |
return [SigD fname sigt, fun] |
128 |
|
129 |
-- | Generates a data type from a given string format. |
130 |
-- |
131 |
-- The format is expected to multiline. The first line contains the |
132 |
-- type name, and the rest of the lines must contain two words: the |
133 |
-- constructor name and then the string representation of the |
134 |
-- respective constructor. |
135 |
-- |
136 |
-- The function will generate the data type declaration, and then two |
137 |
-- functions: |
138 |
-- |
139 |
-- * /name/ToString, which converts the type to a string |
140 |
-- |
141 |
-- * /name/FromString, which (monadically) converts from a string to the type |
142 |
-- |
143 |
-- Note that this is basically just a custom show/read instance, |
144 |
-- nothing else. |
145 |
declareSADT :: String -> [(String, Name)] -> Q [Dec] |
146 |
declareSADT sname cons = do |
147 |
let name = mkName sname |
148 |
ddecl = strADTDecl name (map fst cons) |
149 |
-- process cons in the format expected by genToString |
150 |
cons' = map (\(a, b) -> (a, Right b)) cons |
151 |
tostr <- genToString (toStrName sname) name cons' |
152 |
fromstr <- genFromString (fromStrName sname) name cons |
153 |
return $ ddecl:tostr ++ fromstr |
154 |
|
155 |
|
156 |
-- | Creates the showJSON member of a JSON instance declaration. |
157 |
-- |
158 |
-- This will create what is the equivalent of: |
159 |
-- |
160 |
-- @ |
161 |
-- showJSON = showJSON . /name/ToString |
162 |
-- @ |
163 |
-- |
164 |
-- in an instance JSON /name/ declaration |
165 |
genShowJSON :: String -> Q [Dec] |
166 |
genShowJSON name = [d| showJSON = JSON.showJSON . $(varE (toStrName name)) |] |
167 |
|
168 |
-- | Creates the readJSON member of a JSON instance declaration. |
169 |
-- |
170 |
-- This will create what is the equivalent of: |
171 |
-- |
172 |
-- @ |
173 |
-- readJSON s = case readJSON s of |
174 |
-- Ok s' -> /name/FromString s' |
175 |
-- Error e -> Error /description/ |
176 |
-- @ |
177 |
-- |
178 |
-- in an instance JSON /name/ declaration |
179 |
genReadJSON :: String -> Q Dec |
180 |
genReadJSON name = do |
181 |
let s = mkName "s" |
182 |
body <- [| case JSON.readJSON $(varE s) of |
183 |
JSON.Ok s' -> $(varE (fromStrName name)) s' |
184 |
JSON.Error e -> |
185 |
JSON.Error $ "Can't parse string value for type " ++ |
186 |
$(litE (StringL name)) ++ ": " ++ e |
187 |
|] |
188 |
return $ FunD (mkName "readJSON") [Clause [VarP s] (NormalB body) []] |
189 |
|
190 |
-- | Generates a JSON instance for a given type. |
191 |
-- |
192 |
-- This assumes that the /name/ToString and /name/FromString functions |
193 |
-- have been defined as by the 'declareSADT' function. |
194 |
makeJSONInstance :: Name -> Q [Dec] |
195 |
makeJSONInstance name = do |
196 |
let base = nameBase name |
197 |
showJ <- genShowJSON base |
198 |
readJ <- genReadJSON base |
199 |
return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) (readJ:showJ)] |
200 |
|
201 |
-- | Transforms a CamelCase string into an_underscore_based_one. |
202 |
deCamelCase :: String -> String |
203 |
deCamelCase = |
204 |
intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b) |
205 |
|
206 |
-- | Computes the name of a given constructor |
207 |
constructorName :: Con -> Q Name |
208 |
constructorName (NormalC name _) = return name |
209 |
constructorName (RecC name _) = return name |
210 |
constructorName x = fail $ "Unhandled constructor " ++ show x |
211 |
|
212 |
-- | Builds the constructor-to-string function. |
213 |
-- |
214 |
-- This generates a simple function of the following form: |
215 |
-- |
216 |
-- @ |
217 |
-- fname (ConStructorOne {}) = "CON_STRUCTOR_ONE" |
218 |
-- fname (ConStructorTwo {}) = "CON_STRUCTOR_TWO" |
219 |
-- @ |
220 |
-- |
221 |
-- This builds a custom list of name/string pairs and then uses |
222 |
-- 'genToString' to actually generate the function |
223 |
genOpID :: Name -> String -> Q [Dec] |
224 |
genOpID name fname = do |
225 |
TyConI (DataD _ _ _ cons _) <- reify name |
226 |
cnames <- mapM (liftM nameBase . constructorName) cons |
227 |
let svalues = map (Left . deCamelCase) cnames |
228 |
genToString (mkName fname) name $ zip cnames svalues |
229 |
|
230 |
|
231 |
-- | OpCode parameter (field) type |
232 |
type OpParam = (String, Q Type, Q Exp) |
233 |
|
234 |
-- | Generates the OpCode data type. |
235 |
-- |
236 |
-- This takes an opcode logical definition, and builds both the |
237 |
-- datatype and the JSON serialisation out of it. We can't use a |
238 |
-- generic serialisation since we need to be compatible with Ganeti's |
239 |
-- own, so we have a few quirks to work around. |
240 |
-- |
241 |
-- There are three things to be defined for each parameter: |
242 |
-- |
243 |
-- * name |
244 |
-- |
245 |
-- * type; if this is 'Maybe', will only be serialised if it's a |
246 |
-- 'Just' value |
247 |
-- |
248 |
-- * default; if missing, won't raise an exception, but will instead |
249 |
-- use the default |
250 |
-- |
251 |
genOpCode :: String -- ^ Type name to use |
252 |
-> [(String, [OpParam])] -- ^ Constructor name and parameters |
253 |
-> Q [Dec] |
254 |
genOpCode name cons = do |
255 |
decl_d <- mapM (\(cname, fields) -> do |
256 |
-- we only need the type of the field, without Q |
257 |
fields' <- mapM (\(_, qt, _) -> |
258 |
qt >>= \t -> return (NotStrict, t)) |
259 |
fields |
260 |
return $ NormalC (mkName cname) fields') |
261 |
cons |
262 |
let declD = DataD [] (mkName name) [] decl_d [''Show, ''Read, ''Eq] |
263 |
|
264 |
(savesig, savefn) <- genSaveOpCode cons |
265 |
(loadsig, loadfn) <- genLoadOpCode cons |
266 |
return [declD, loadsig, loadfn, savesig, savefn] |
267 |
|
268 |
-- | Checks whether a given parameter is options |
269 |
-- |
270 |
-- This requires that it's a 'Maybe'. |
271 |
isOptional :: Type -> Bool |
272 |
isOptional (AppT (ConT dt) _) | dt == ''Maybe = True |
273 |
isOptional _ = False |
274 |
|
275 |
-- | Generates the \"save\" expression for a single opcode parameter. |
276 |
-- |
277 |
-- There is only one special handling mode: if the parameter is of |
278 |
-- 'Maybe' type, then we only save it if it's a 'Just' value, |
279 |
-- otherwise we skip it. |
280 |
saveField :: Name -- ^ The name of variable that contains the value |
281 |
-> OpParam -- ^ Parameter definition |
282 |
-> Q Exp |
283 |
saveField fvar (fname, qt, _) = do |
284 |
t <- qt |
285 |
let showJ = varE (mkName "showJSON") |
286 |
fnexp = litE (stringL fname) |
287 |
fvare = varE fvar |
288 |
(if isOptional t |
289 |
then [| case $fvare of |
290 |
Just v' -> [( $fnexp, $showJ v')] |
291 |
Nothing -> [] |
292 |
|] |
293 |
else [| [( $fnexp, $showJ $fvare )] |]) |
294 |
|
295 |
-- | Generates the \"save\" clause for an entire opcode constructor. |
296 |
-- |
297 |
-- This matches the opcode with variables named the same as the |
298 |
-- constructor fields (just so that the spliced in code looks nicer), |
299 |
-- and passes those name plus the parameter definition to 'saveField'. |
300 |
saveConstructor :: String -- ^ The constructor name |
301 |
-> [OpParam] -- ^ The parameter definitions for this |
302 |
-- constructor |
303 |
-> Q Clause -- ^ Resulting clause |
304 |
saveConstructor sname fields = do |
305 |
let cname = mkName sname |
306 |
let fnames = map (\(n, _, _) -> mkName n) fields |
307 |
let pat = conP cname (map varP fnames) |
308 |
let felems = map (uncurry saveField) (zip fnames fields) |
309 |
-- now build the OP_ID serialisation |
310 |
opid = [| [( $(litE (stringL "OP_ID")), |
311 |
$(varE (mkName "showJSON")) |
312 |
$(litE . stringL . deCamelCase $ sname) )] |] |
313 |
flist = listE (opid:felems) |
314 |
-- and finally convert all this to a json object |
315 |
flist' = [| $(varE (mkName "makeObj")) (concat $flist) |] |
316 |
clause [pat] (normalB flist') [] |
317 |
|
318 |
-- | Generates the main save opcode function. |
319 |
-- |
320 |
-- This builds a per-constructor match clause that contains the |
321 |
-- respective constructor-serialisation code. |
322 |
genSaveOpCode :: [(String, [OpParam])] -> Q (Dec, Dec) |
323 |
genSaveOpCode opdefs = do |
324 |
cclauses <- mapM (uncurry saveConstructor) opdefs |
325 |
let fname = mkName "saveOpCode" |
326 |
sigt <- [t| $(conT (mkName "OpCode")) -> JSON.JSValue |] |
327 |
return $ (SigD fname sigt, FunD fname cclauses) |
328 |
|
329 |
-- | Generates the \"load\" field for a single parameter. |
330 |
-- |
331 |
-- There is custom handling, depending on how the parameter is |
332 |
-- specified. For a 'Maybe' type parameter, we allow that it is not |
333 |
-- present (via 'Utils.maybeFromObj'). Otherwise, if there is a |
334 |
-- default value, we allow the parameter to be abset, and finally if |
335 |
-- there is no default value, we require its presence. |
336 |
loadField :: OpParam -> Q (Name, Stmt) |
337 |
loadField (fname, qt, qdefa) = do |
338 |
let fvar = mkName fname |
339 |
t <- qt |
340 |
defa <- qdefa |
341 |
-- these are used in all patterns below |
342 |
let objvar = varE (mkName "o") |
343 |
objfield = litE (StringL fname) |
344 |
bexp <- if isOptional t |
345 |
then [| $((varE (mkName "maybeFromObj"))) $objvar $objfield |] |
346 |
else case defa of |
347 |
AppE (ConE dt) defval | dt == 'Just -> |
348 |
-- but has a default value |
349 |
[| $(varE (mkName "fromObjWithDefault")) |
350 |
$objvar $objfield $(return defval) |] |
351 |
ConE dt | dt == 'Nothing -> |
352 |
[| $(varE (mkName "fromObj")) $objvar $objfield |] |
353 |
s -> fail $ "Invalid default value " ++ show s ++ |
354 |
", expecting either 'Nothing' or a 'Just defval'" |
355 |
return (fvar, BindS (VarP fvar) bexp) |
356 |
|
357 |
loadConstructor :: String -> [OpParam] -> Q Exp |
358 |
loadConstructor sname fields = do |
359 |
let name = mkName sname |
360 |
fbinds <- mapM loadField fields |
361 |
let (fnames, fstmts) = unzip fbinds |
362 |
let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames |
363 |
fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)] |
364 |
return $ DoE fstmts' |
365 |
|
366 |
genLoadOpCode :: [(String, [OpParam])] -> Q (Dec, Dec) |
367 |
genLoadOpCode opdefs = do |
368 |
let fname = mkName "loadOpCode" |
369 |
arg1 = mkName "v" |
370 |
objname = mkName "o" |
371 |
opid = mkName "op_id" |
372 |
st1 <- bindS (varP objname) [| liftM JSON.fromJSObject |
373 |
(JSON.readJSON $(varE arg1)) |] |
374 |
st2 <- bindS (varP opid) [| $(varE (mkName "fromObj")) |
375 |
$(varE objname) $(litE (stringL "OP_ID")) |] |
376 |
-- the match results (per-constructor blocks) |
377 |
mexps <- mapM (uncurry loadConstructor) opdefs |
378 |
fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |] |
379 |
let mpats = map (\(me, c) -> |
380 |
let mp = LitP . StringL . deCamelCase . fst $ c |
381 |
in Match mp (NormalB me) [] |
382 |
) $ zip mexps opdefs |
383 |
defmatch = Match WildP (NormalB fails) [] |
384 |
cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch] |
385 |
body = DoE [st1, st2, cst] |
386 |
sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |] |
387 |
return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []]) |
388 |
|
389 |
-- | No default type. |
390 |
noDefault :: Q Exp |
391 |
noDefault = conE 'Nothing |