root / src / Ganeti / THH.hs @ eb577716
History | View | Annotate | Download (46.5 kB)
1 |
{-# LANGUAGE ParallelListComp, TemplateHaskell #-} |
---|---|
2 |
|
3 |
{-| TemplateHaskell helper for Ganeti Haskell code. |
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, 2012, 2013, 2014 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 |
, declareLADT |
34 |
, declareILADT |
35 |
, declareIADT |
36 |
, makeJSONInstance |
37 |
, deCamelCase |
38 |
, genOpID |
39 |
, genAllConstr |
40 |
, genAllOpIDs |
41 |
, PyValue(..) |
42 |
, PyValueEx(..) |
43 |
, OpCodeField(..) |
44 |
, OpCodeDescriptor(..) |
45 |
, genOpCode |
46 |
, genStrOfOp |
47 |
, genStrOfKey |
48 |
, genLuxiOp |
49 |
, Field (..) |
50 |
, simpleField |
51 |
, specialNumericalField |
52 |
, withDoc |
53 |
, defaultField |
54 |
, optionalField |
55 |
, optionalNullSerField |
56 |
, renameField |
57 |
, customField |
58 |
, timeStampFields |
59 |
, uuidFields |
60 |
, serialFields |
61 |
, tagsFields |
62 |
, TagSet |
63 |
, buildObject |
64 |
, buildObjectSerialisation |
65 |
, buildParam |
66 |
, DictObject(..) |
67 |
, genException |
68 |
, excErrMsg |
69 |
) where |
70 |
|
71 |
import Control.Arrow ((&&&)) |
72 |
import Control.Applicative |
73 |
import Control.Monad |
74 |
import Data.Char |
75 |
import Data.List |
76 |
import Data.Maybe |
77 |
import qualified Data.Set as Set |
78 |
import Language.Haskell.TH |
79 |
|
80 |
import qualified Text.JSON as JSON |
81 |
import Text.JSON.Pretty (pp_value) |
82 |
|
83 |
import Ganeti.JSON |
84 |
import Ganeti.PyValue |
85 |
import Ganeti.THH.PyType |
86 |
|
87 |
|
88 |
-- * Exported types |
89 |
|
90 |
-- | Class of objects that can be converted to 'JSObject' |
91 |
-- lists-format. |
92 |
class DictObject a where |
93 |
toDict :: a -> [(String, JSON.JSValue)] |
94 |
|
95 |
-- | Optional field information. |
96 |
data OptionalType |
97 |
= NotOptional -- ^ Field is not optional |
98 |
| OptionalOmitNull -- ^ Field is optional, null is not serialised |
99 |
| OptionalSerializeNull -- ^ Field is optional, null is serialised |
100 |
deriving (Show, Eq) |
101 |
|
102 |
-- | Serialised field data type. |
103 |
data Field = Field { fieldName :: String |
104 |
, fieldType :: Q Type |
105 |
, fieldRead :: Maybe (Q Exp) |
106 |
, fieldShow :: Maybe (Q Exp) |
107 |
, fieldExtraKeys :: [String] |
108 |
, fieldDefault :: Maybe (Q Exp) |
109 |
, fieldConstr :: Maybe String |
110 |
, fieldIsOptional :: OptionalType |
111 |
, fieldDoc :: String |
112 |
} |
113 |
|
114 |
-- | Generates a simple field. |
115 |
simpleField :: String -> Q Type -> Field |
116 |
simpleField fname ftype = |
117 |
Field { fieldName = fname |
118 |
, fieldType = ftype |
119 |
, fieldRead = Nothing |
120 |
, fieldShow = Nothing |
121 |
, fieldExtraKeys = [] |
122 |
, fieldDefault = Nothing |
123 |
, fieldConstr = Nothing |
124 |
, fieldIsOptional = NotOptional |
125 |
, fieldDoc = "" |
126 |
} |
127 |
|
128 |
withDoc :: String -> Field -> Field |
129 |
withDoc doc field = |
130 |
field { fieldDoc = doc } |
131 |
|
132 |
-- | Sets the renamed constructor field. |
133 |
renameField :: String -> Field -> Field |
134 |
renameField constrName field = field { fieldConstr = Just constrName } |
135 |
|
136 |
-- | Sets the default value on a field (makes it optional with a |
137 |
-- default value). |
138 |
defaultField :: Q Exp -> Field -> Field |
139 |
defaultField defval field = field { fieldDefault = Just defval } |
140 |
|
141 |
-- | Marks a field optional (turning its base type into a Maybe). |
142 |
optionalField :: Field -> Field |
143 |
optionalField field = field { fieldIsOptional = OptionalOmitNull } |
144 |
|
145 |
-- | Marks a field optional (turning its base type into a Maybe), but |
146 |
-- with 'Nothing' serialised explicitly as /null/. |
147 |
optionalNullSerField :: Field -> Field |
148 |
optionalNullSerField field = field { fieldIsOptional = OptionalSerializeNull } |
149 |
|
150 |
-- | Wrapper around a special parse function, suitable as field-parsing |
151 |
-- function. |
152 |
numericalReadFn :: JSON.JSON a => (String -> JSON.Result a) |
153 |
-> [(String, JSON.JSValue)] -> JSON.JSValue -> JSON.Result a |
154 |
numericalReadFn _ _ v@(JSON.JSRational _ _) = JSON.readJSON v |
155 |
numericalReadFn f _ (JSON.JSString x) = f $ JSON.fromJSString x |
156 |
numericalReadFn _ _ _ = JSON.Error "A numerical field has to be a number or\ |
157 |
\ a string." |
158 |
|
159 |
-- | Sets the read function to also accept string parsable by the given |
160 |
-- function. |
161 |
specialNumericalField :: Name -> Field -> Field |
162 |
specialNumericalField f field = |
163 |
field { fieldRead = Just (appE (varE 'numericalReadFn) (varE f)) } |
164 |
|
165 |
-- | Sets custom functions on a field. |
166 |
customField :: Name -- ^ The name of the read function |
167 |
-> Name -- ^ The name of the show function |
168 |
-> [String] -- ^ The name of extra field keys |
169 |
-> Field -- ^ The original field |
170 |
-> Field -- ^ Updated field |
171 |
customField readfn showfn extra field = |
172 |
field { fieldRead = Just (varE readfn), fieldShow = Just (varE showfn) |
173 |
, fieldExtraKeys = extra } |
174 |
|
175 |
-- | Computes the record name for a given field, based on either the |
176 |
-- string value in the JSON serialisation or the custom named if any |
177 |
-- exists. |
178 |
fieldRecordName :: Field -> String |
179 |
fieldRecordName (Field { fieldName = name, fieldConstr = alias }) = |
180 |
fromMaybe (camelCase name) alias |
181 |
|
182 |
-- | Computes the preferred variable name to use for the value of this |
183 |
-- field. If the field has a specific constructor name, then we use a |
184 |
-- first-letter-lowercased version of that; otherwise, we simply use |
185 |
-- the field name. See also 'fieldRecordName'. |
186 |
fieldVariable :: Field -> String |
187 |
fieldVariable f = |
188 |
case (fieldConstr f) of |
189 |
Just name -> ensureLower name |
190 |
_ -> map (\c -> if c == '-' then '_' else c) $ fieldName f |
191 |
|
192 |
-- | Compute the actual field type (taking into account possible |
193 |
-- optional status). |
194 |
actualFieldType :: Field -> Q Type |
195 |
actualFieldType f | fieldIsOptional f /= NotOptional = [t| Maybe $t |] |
196 |
| otherwise = t |
197 |
where t = fieldType f |
198 |
|
199 |
-- | Checks that a given field is not optional (for object types or |
200 |
-- fields which should not allow this case). |
201 |
checkNonOptDef :: (Monad m) => Field -> m () |
202 |
checkNonOptDef (Field { fieldIsOptional = OptionalOmitNull |
203 |
, fieldName = name }) = |
204 |
fail $ "Optional field " ++ name ++ " used in parameter declaration" |
205 |
checkNonOptDef (Field { fieldIsOptional = OptionalSerializeNull |
206 |
, fieldName = name }) = |
207 |
fail $ "Optional field " ++ name ++ " used in parameter declaration" |
208 |
checkNonOptDef (Field { fieldDefault = (Just _), fieldName = name }) = |
209 |
fail $ "Default field " ++ name ++ " used in parameter declaration" |
210 |
checkNonOptDef _ = return () |
211 |
|
212 |
-- | Construct a function that parses a field value. If the field has |
213 |
-- a custom 'fieldRead', it's applied to @o@ and used. Otherwise |
214 |
-- @JSON.readJSON@ is used. |
215 |
parseFn :: Field -- ^ The field definition |
216 |
-> Q Exp -- ^ The entire object in JSON object format |
217 |
-> Q Exp -- ^ The resulting function that parses a JSON message |
218 |
parseFn field o = maybe [| JSON.readJSON |] (`appE` o) (fieldRead field) |
219 |
|
220 |
-- | Produces the expression that will de-serialise a given |
221 |
-- field. Since some custom parsing functions might need to use the |
222 |
-- entire object, we do take and pass the object to any custom read |
223 |
-- functions. |
224 |
loadFn :: Field -- ^ The field definition |
225 |
-> Q Exp -- ^ The value of the field as existing in the JSON message |
226 |
-> Q Exp -- ^ The entire object in JSON object format |
227 |
-> Q Exp -- ^ Resulting expression |
228 |
loadFn field expr o = [| $expr >>= $(parseFn field o) |] |
229 |
|
230 |
-- | Just as 'loadFn', but for optional fields. |
231 |
loadFnOpt :: Field -- ^ The field definition |
232 |
-> Q Exp -- ^ The value of the field as existing in the JSON message |
233 |
-- as Maybe |
234 |
-> Q Exp -- ^ The entire object in JSON object format |
235 |
-> Q Exp -- ^ Resulting expression |
236 |
loadFnOpt field@(Field { fieldDefault = Just def }) expr o |
237 |
= [| $expr >>= maybe (return $def) $(parseFn field o) |] |
238 |
loadFnOpt field expr o |
239 |
= [| $expr >>= maybe (return Nothing) (liftM Just . $(parseFn field o)) |] |
240 |
|
241 |
-- * Common field declarations |
242 |
|
243 |
-- | Timestamp fields description. |
244 |
timeStampFields :: [Field] |
245 |
timeStampFields = |
246 |
[ defaultField [| 0::Double |] $ simpleField "ctime" [t| Double |] |
247 |
, defaultField [| 0::Double |] $ simpleField "mtime" [t| Double |] |
248 |
] |
249 |
|
250 |
-- | Serial number fields description. |
251 |
serialFields :: [Field] |
252 |
serialFields = |
253 |
[ renameField "Serial" $ simpleField "serial_no" [t| Int |] ] |
254 |
|
255 |
-- | UUID fields description. |
256 |
uuidFields :: [Field] |
257 |
uuidFields = [ simpleField "uuid" [t| String |] ] |
258 |
|
259 |
-- | Tag set type alias. |
260 |
type TagSet = Set.Set String |
261 |
|
262 |
-- | Tag field description. |
263 |
tagsFields :: [Field] |
264 |
tagsFields = [ defaultField [| Set.empty |] $ |
265 |
simpleField "tags" [t| TagSet |] ] |
266 |
|
267 |
-- * Internal types |
268 |
|
269 |
-- | A simple field, in constrast to the customisable 'Field' type. |
270 |
type SimpleField = (String, Q Type) |
271 |
|
272 |
-- | A definition for a single constructor for a simple object. |
273 |
type SimpleConstructor = (String, [SimpleField]) |
274 |
|
275 |
-- | A definition for ADTs with simple fields. |
276 |
type SimpleObject = [SimpleConstructor] |
277 |
|
278 |
-- | A type alias for an opcode constructor of a regular object. |
279 |
type OpCodeConstructor = (String, Q Type, String, [Field], String) |
280 |
|
281 |
-- | A type alias for a Luxi constructor of a regular object. |
282 |
type LuxiConstructor = (String, [Field]) |
283 |
|
284 |
-- * Helper functions |
285 |
|
286 |
-- | Ensure first letter is lowercase. |
287 |
-- |
288 |
-- Used to convert type name to function prefix, e.g. in @data Aa -> |
289 |
-- aaToRaw@. |
290 |
ensureLower :: String -> String |
291 |
ensureLower [] = [] |
292 |
ensureLower (x:xs) = toLower x:xs |
293 |
|
294 |
-- | Ensure first letter is uppercase. |
295 |
-- |
296 |
-- Used to convert constructor name to component |
297 |
ensureUpper :: String -> String |
298 |
ensureUpper [] = [] |
299 |
ensureUpper (x:xs) = toUpper x:xs |
300 |
|
301 |
-- | Helper for quoted expressions. |
302 |
varNameE :: String -> Q Exp |
303 |
varNameE = varE . mkName |
304 |
|
305 |
-- | showJSON as an expression, for reuse. |
306 |
showJSONE :: Q Exp |
307 |
showJSONE = varE 'JSON.showJSON |
308 |
|
309 |
-- | makeObj as an expression, for reuse. |
310 |
makeObjE :: Q Exp |
311 |
makeObjE = varE 'JSON.makeObj |
312 |
|
313 |
-- | fromObj (Ganeti specific) as an expression, for reuse. |
314 |
fromObjE :: Q Exp |
315 |
fromObjE = varE 'fromObj |
316 |
|
317 |
-- | ToRaw function name. |
318 |
toRawName :: String -> Name |
319 |
toRawName = mkName . (++ "ToRaw") . ensureLower |
320 |
|
321 |
-- | FromRaw function name. |
322 |
fromRawName :: String -> Name |
323 |
fromRawName = mkName . (++ "FromRaw") . ensureLower |
324 |
|
325 |
-- | Converts a name to it's varE\/litE representations. |
326 |
reprE :: Either String Name -> Q Exp |
327 |
reprE = either stringE varE |
328 |
|
329 |
-- | Smarter function application. |
330 |
-- |
331 |
-- This does simply f x, except that if is 'id', it will skip it, in |
332 |
-- order to generate more readable code when using -ddump-splices. |
333 |
appFn :: Exp -> Exp -> Exp |
334 |
appFn f x | f == VarE 'id = x |
335 |
| otherwise = AppE f x |
336 |
|
337 |
-- | Builds a field for a normal constructor. |
338 |
buildConsField :: Q Type -> StrictTypeQ |
339 |
buildConsField ftype = do |
340 |
ftype' <- ftype |
341 |
return (NotStrict, ftype') |
342 |
|
343 |
-- | Builds a constructor based on a simple definition (not field-based). |
344 |
buildSimpleCons :: Name -> SimpleObject -> Q Dec |
345 |
buildSimpleCons tname cons = do |
346 |
decl_d <- mapM (\(cname, fields) -> do |
347 |
fields' <- mapM (buildConsField . snd) fields |
348 |
return $ NormalC (mkName cname) fields') cons |
349 |
return $ DataD [] tname [] decl_d [''Show, ''Eq] |
350 |
|
351 |
-- | Generate the save function for a given type. |
352 |
genSaveSimpleObj :: Name -- ^ Object type |
353 |
-> String -- ^ Function name |
354 |
-> SimpleObject -- ^ Object definition |
355 |
-> (SimpleConstructor -> Q Clause) -- ^ Constructor save fn |
356 |
-> Q (Dec, Dec) |
357 |
genSaveSimpleObj tname sname opdefs fn = do |
358 |
let sigt = AppT (AppT ArrowT (ConT tname)) (ConT ''JSON.JSValue) |
359 |
fname = mkName sname |
360 |
cclauses <- mapM fn opdefs |
361 |
return $ (SigD fname sigt, FunD fname cclauses) |
362 |
|
363 |
-- * Template code for simple raw type-equivalent ADTs |
364 |
|
365 |
-- | Generates a data type declaration. |
366 |
-- |
367 |
-- The type will have a fixed list of instances. |
368 |
strADTDecl :: Name -> [String] -> Dec |
369 |
strADTDecl name constructors = |
370 |
DataD [] name [] |
371 |
(map (flip NormalC [] . mkName) constructors) |
372 |
[''Show, ''Eq, ''Enum, ''Bounded, ''Ord] |
373 |
|
374 |
-- | Generates a toRaw function. |
375 |
-- |
376 |
-- This generates a simple function of the form: |
377 |
-- |
378 |
-- @ |
379 |
-- nameToRaw :: Name -> /traw/ |
380 |
-- nameToRaw Cons1 = var1 |
381 |
-- nameToRaw Cons2 = \"value2\" |
382 |
-- @ |
383 |
genToRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec] |
384 |
genToRaw traw fname tname constructors = do |
385 |
let sigt = AppT (AppT ArrowT (ConT tname)) (ConT traw) |
386 |
-- the body clauses, matching on the constructor and returning the |
387 |
-- raw value |
388 |
clauses <- mapM (\(c, v) -> clause [recP (mkName c) []] |
389 |
(normalB (reprE v)) []) constructors |
390 |
return [SigD fname sigt, FunD fname clauses] |
391 |
|
392 |
-- | Generates a fromRaw function. |
393 |
-- |
394 |
-- The function generated is monadic and can fail parsing the |
395 |
-- raw value. It is of the form: |
396 |
-- |
397 |
-- @ |
398 |
-- nameFromRaw :: (Monad m) => /traw/ -> m Name |
399 |
-- nameFromRaw s | s == var1 = Cons1 |
400 |
-- | s == \"value2\" = Cons2 |
401 |
-- | otherwise = fail /.../ |
402 |
-- @ |
403 |
genFromRaw :: Name -> Name -> Name -> [(String, Either String Name)] -> Q [Dec] |
404 |
genFromRaw traw fname tname constructors = do |
405 |
-- signature of form (Monad m) => String -> m $name |
406 |
sigt <- [t| (Monad m) => $(conT traw) -> m $(conT tname) |] |
407 |
-- clauses for a guarded pattern |
408 |
let varp = mkName "s" |
409 |
varpe = varE varp |
410 |
clauses <- mapM (\(c, v) -> do |
411 |
-- the clause match condition |
412 |
g <- normalG [| $varpe == $(reprE v) |] |
413 |
-- the clause result |
414 |
r <- [| return $(conE (mkName c)) |] |
415 |
return (g, r)) constructors |
416 |
-- the otherwise clause (fallback) |
417 |
oth_clause <- do |
418 |
g <- normalG [| otherwise |] |
419 |
r <- [|fail ("Invalid string value for type " ++ |
420 |
$(litE (stringL (nameBase tname))) ++ ": " ++ show $varpe) |] |
421 |
return (g, r) |
422 |
let fun = FunD fname [Clause [VarP varp] |
423 |
(GuardedB (clauses++[oth_clause])) []] |
424 |
return [SigD fname sigt, fun] |
425 |
|
426 |
-- | Generates a data type from a given raw format. |
427 |
-- |
428 |
-- The format is expected to multiline. The first line contains the |
429 |
-- type name, and the rest of the lines must contain two words: the |
430 |
-- constructor name and then the string representation of the |
431 |
-- respective constructor. |
432 |
-- |
433 |
-- The function will generate the data type declaration, and then two |
434 |
-- functions: |
435 |
-- |
436 |
-- * /name/ToRaw, which converts the type to a raw type |
437 |
-- |
438 |
-- * /name/FromRaw, which (monadically) converts from a raw type to the type |
439 |
-- |
440 |
-- Note that this is basically just a custom show\/read instance, |
441 |
-- nothing else. |
442 |
declareADT |
443 |
:: (a -> Either String Name) -> Name -> String -> [(String, a)] -> Q [Dec] |
444 |
declareADT fn traw sname cons = do |
445 |
let name = mkName sname |
446 |
ddecl = strADTDecl name (map fst cons) |
447 |
-- process cons in the format expected by genToRaw |
448 |
cons' = map (\(a, b) -> (a, fn b)) cons |
449 |
toraw <- genToRaw traw (toRawName sname) name cons' |
450 |
fromraw <- genFromRaw traw (fromRawName sname) name cons' |
451 |
return $ ddecl:toraw ++ fromraw |
452 |
|
453 |
declareLADT :: Name -> String -> [(String, String)] -> Q [Dec] |
454 |
declareLADT = declareADT Left |
455 |
|
456 |
declareILADT :: String -> [(String, Int)] -> Q [Dec] |
457 |
declareILADT sname cons = do |
458 |
consNames <- sequence [ newName ('_':n) | (n, _) <- cons ] |
459 |
consFns <- concat <$> sequence |
460 |
[ do sig <- sigD n [t| Int |] |
461 |
let expr = litE (IntegerL (toInteger i)) |
462 |
fn <- funD n [clause [] (normalB expr) []] |
463 |
return [sig, fn] |
464 |
| n <- consNames |
465 |
| (_, i) <- cons ] |
466 |
let cons' = [ (n, n') | (n, _) <- cons | n' <- consNames ] |
467 |
(consFns ++) <$> declareADT Right ''Int sname cons' |
468 |
|
469 |
declareIADT :: String -> [(String, Name)] -> Q [Dec] |
470 |
declareIADT = declareADT Right ''Int |
471 |
|
472 |
declareSADT :: String -> [(String, Name)] -> Q [Dec] |
473 |
declareSADT = declareADT Right ''String |
474 |
|
475 |
-- | Creates the showJSON member of a JSON instance declaration. |
476 |
-- |
477 |
-- This will create what is the equivalent of: |
478 |
-- |
479 |
-- @ |
480 |
-- showJSON = showJSON . /name/ToRaw |
481 |
-- @ |
482 |
-- |
483 |
-- in an instance JSON /name/ declaration |
484 |
genShowJSON :: String -> Q Dec |
485 |
genShowJSON name = do |
486 |
body <- [| JSON.showJSON . $(varE (toRawName name)) |] |
487 |
return $ FunD 'JSON.showJSON [Clause [] (NormalB body) []] |
488 |
|
489 |
-- | Creates the readJSON member of a JSON instance declaration. |
490 |
-- |
491 |
-- This will create what is the equivalent of: |
492 |
-- |
493 |
-- @ |
494 |
-- readJSON s = case readJSON s of |
495 |
-- Ok s' -> /name/FromRaw s' |
496 |
-- Error e -> Error /description/ |
497 |
-- @ |
498 |
-- |
499 |
-- in an instance JSON /name/ declaration |
500 |
genReadJSON :: String -> Q Dec |
501 |
genReadJSON name = do |
502 |
let s = mkName "s" |
503 |
body <- [| case JSON.readJSON $(varE s) of |
504 |
JSON.Ok s' -> $(varE (fromRawName name)) s' |
505 |
JSON.Error e -> |
506 |
JSON.Error $ "Can't parse raw value for type " ++ |
507 |
$(stringE name) ++ ": " ++ e ++ " from " ++ |
508 |
show $(varE s) |
509 |
|] |
510 |
return $ FunD 'JSON.readJSON [Clause [VarP s] (NormalB body) []] |
511 |
|
512 |
-- | Generates a JSON instance for a given type. |
513 |
-- |
514 |
-- This assumes that the /name/ToRaw and /name/FromRaw functions |
515 |
-- have been defined as by the 'declareSADT' function. |
516 |
makeJSONInstance :: Name -> Q [Dec] |
517 |
makeJSONInstance name = do |
518 |
let base = nameBase name |
519 |
showJ <- genShowJSON base |
520 |
readJ <- genReadJSON base |
521 |
return [InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) [readJ,showJ]] |
522 |
|
523 |
-- * Template code for opcodes |
524 |
|
525 |
-- | Transforms a CamelCase string into an_underscore_based_one. |
526 |
deCamelCase :: String -> String |
527 |
deCamelCase = |
528 |
intercalate "_" . map (map toUpper) . groupBy (\_ b -> not $ isUpper b) |
529 |
|
530 |
-- | Transform an underscore_name into a CamelCase one. |
531 |
camelCase :: String -> String |
532 |
camelCase = concatMap (ensureUpper . drop 1) . |
533 |
groupBy (\_ b -> b /= '_' && b /= '-') . ('_':) |
534 |
|
535 |
-- | Computes the name of a given constructor. |
536 |
constructorName :: Con -> Q Name |
537 |
constructorName (NormalC name _) = return name |
538 |
constructorName (RecC name _) = return name |
539 |
constructorName x = fail $ "Unhandled constructor " ++ show x |
540 |
|
541 |
-- | Extract all constructor names from a given type. |
542 |
reifyConsNames :: Name -> Q [String] |
543 |
reifyConsNames name = do |
544 |
reify_result <- reify name |
545 |
case reify_result of |
546 |
TyConI (DataD _ _ _ cons _) -> mapM (liftM nameBase . constructorName) cons |
547 |
o -> fail $ "Unhandled name passed to reifyConsNames, expected\ |
548 |
\ type constructor but got '" ++ show o ++ "'" |
549 |
|
550 |
-- | Builds the generic constructor-to-string function. |
551 |
-- |
552 |
-- This generates a simple function of the following form: |
553 |
-- |
554 |
-- @ |
555 |
-- fname (ConStructorOne {}) = trans_fun("ConStructorOne") |
556 |
-- fname (ConStructorTwo {}) = trans_fun("ConStructorTwo") |
557 |
-- @ |
558 |
-- |
559 |
-- This builds a custom list of name\/string pairs and then uses |
560 |
-- 'genToRaw' to actually generate the function. |
561 |
genConstrToStr :: (String -> String) -> Name -> String -> Q [Dec] |
562 |
genConstrToStr trans_fun name fname = do |
563 |
cnames <- reifyConsNames name |
564 |
let svalues = map (Left . trans_fun) cnames |
565 |
genToRaw ''String (mkName fname) name $ zip cnames svalues |
566 |
|
567 |
-- | Constructor-to-string for OpCode. |
568 |
genOpID :: Name -> String -> Q [Dec] |
569 |
genOpID = genConstrToStr deCamelCase |
570 |
|
571 |
-- | Builds a list with all defined constructor names for a type. |
572 |
-- |
573 |
-- @ |
574 |
-- vstr :: String |
575 |
-- vstr = [...] |
576 |
-- @ |
577 |
-- |
578 |
-- Where the actual values of the string are the constructor names |
579 |
-- mapped via @trans_fun@. |
580 |
genAllConstr :: (String -> String) -> Name -> String -> Q [Dec] |
581 |
genAllConstr trans_fun name vstr = do |
582 |
cnames <- reifyConsNames name |
583 |
let svalues = sort $ map trans_fun cnames |
584 |
vname = mkName vstr |
585 |
sig = SigD vname (AppT ListT (ConT ''String)) |
586 |
body = NormalB (ListE (map (LitE . StringL) svalues)) |
587 |
return $ [sig, ValD (VarP vname) body []] |
588 |
|
589 |
-- | Generates a list of all defined opcode IDs. |
590 |
genAllOpIDs :: Name -> String -> Q [Dec] |
591 |
genAllOpIDs = genAllConstr deCamelCase |
592 |
|
593 |
-- | OpCode parameter (field) type. |
594 |
type OpParam = (String, Q Type, Q Exp) |
595 |
|
596 |
-- * Python code generation |
597 |
|
598 |
data OpCodeField = OpCodeField { ocfName :: String |
599 |
, ocfType :: PyType |
600 |
, ocfDefl :: Maybe PyValueEx |
601 |
, ocfDoc :: String |
602 |
} |
603 |
|
604 |
-- | Transfers opcode data between the opcode description (through |
605 |
-- @genOpCode@) and the Python code generation functions. |
606 |
data OpCodeDescriptor = OpCodeDescriptor { ocdName :: String |
607 |
, ocdType :: PyType |
608 |
, ocdDoc :: String |
609 |
, ocdFields :: [OpCodeField] |
610 |
, ocdDescr :: String |
611 |
} |
612 |
|
613 |
-- | Optionally encapsulates default values in @PyValueEx@. |
614 |
-- |
615 |
-- @maybeApp exp typ@ returns a quoted expression that encapsulates |
616 |
-- the default value @exp@ of an opcode parameter cast to @typ@ in a |
617 |
-- @PyValueEx@, if @exp@ is @Just@. Otherwise, it returns a quoted |
618 |
-- expression with @Nothing@. |
619 |
maybeApp :: Maybe (Q Exp) -> Q Type -> Q Exp |
620 |
maybeApp Nothing _ = |
621 |
[| Nothing |] |
622 |
|
623 |
maybeApp (Just expr) typ = |
624 |
[| Just ($(conE (mkName "PyValueEx")) ($expr :: $typ)) |] |
625 |
|
626 |
-- | Generates a Python type according to whether the field is |
627 |
-- optional. |
628 |
-- |
629 |
-- The type of created expression is PyType. |
630 |
genPyType' :: OptionalType -> Q Type -> Q PyType |
631 |
genPyType' opt typ = typ >>= pyOptionalType (opt /= NotOptional) |
632 |
|
633 |
-- | Generates Python types from opcode parameters. |
634 |
genPyType :: Field -> Q PyType |
635 |
genPyType f = genPyType' (fieldIsOptional f) (fieldType f) |
636 |
|
637 |
-- | Generates Python default values from opcode parameters. |
638 |
genPyDefault :: Field -> Q Exp |
639 |
genPyDefault f = maybeApp (fieldDefault f) (fieldType f) |
640 |
|
641 |
pyField :: Field -> Q Exp |
642 |
pyField f = genPyType f >>= \t -> |
643 |
[| OpCodeField $(stringE (fieldName f)) |
644 |
t |
645 |
$(genPyDefault f) |
646 |
$(stringE (fieldDoc f)) |] |
647 |
|
648 |
-- | Generates a Haskell function call to "showPyClass" with the |
649 |
-- necessary information on how to build the Python class string. |
650 |
pyClass :: OpCodeConstructor -> Q Exp |
651 |
pyClass (consName, consType, consDoc, consFields, consDscField) = |
652 |
do let pyClassVar = varNameE "showPyClass" |
653 |
consName' = stringE consName |
654 |
consType' <- genPyType' NotOptional consType |
655 |
let consDoc' = stringE consDoc |
656 |
[| OpCodeDescriptor $consName' |
657 |
consType' |
658 |
$consDoc' |
659 |
$(listE $ map pyField consFields) |
660 |
consDscField |] |
661 |
|
662 |
-- | Generates a function called "pyClasses" that holds the list of |
663 |
-- all the opcode descriptors necessary for generating the Python |
664 |
-- opcodes. |
665 |
pyClasses :: [OpCodeConstructor] -> Q [Dec] |
666 |
pyClasses cons = |
667 |
do let name = mkName "pyClasses" |
668 |
sig = SigD name (AppT ListT (ConT ''OpCodeDescriptor)) |
669 |
fn <- FunD name <$> (:[]) <$> declClause cons |
670 |
return [sig, fn] |
671 |
where declClause c = |
672 |
clause [] (normalB (ListE <$> mapM pyClass c)) [] |
673 |
|
674 |
-- | Converts from an opcode constructor to a Luxi constructor. |
675 |
opcodeConsToLuxiCons :: (a, b, c, d, e) -> (a, d) |
676 |
opcodeConsToLuxiCons (x, _, _, y, _) = (x, y) |
677 |
|
678 |
-- | Generates the OpCode data type. |
679 |
-- |
680 |
-- This takes an opcode logical definition, and builds both the |
681 |
-- datatype and the JSON serialisation out of it. We can't use a |
682 |
-- generic serialisation since we need to be compatible with Ganeti's |
683 |
-- own, so we have a few quirks to work around. |
684 |
genOpCode :: String -- ^ Type name to use |
685 |
-> [OpCodeConstructor] -- ^ Constructor name and parameters |
686 |
-> Q [Dec] |
687 |
genOpCode name cons = do |
688 |
let tname = mkName name |
689 |
decl_d <- mapM (\(cname, _, _, fields, _) -> do |
690 |
-- we only need the type of the field, without Q |
691 |
fields' <- mapM (fieldTypeInfo "op") fields |
692 |
return $ RecC (mkName cname) fields') |
693 |
cons |
694 |
let declD = DataD [] tname [] decl_d [''Show, ''Eq] |
695 |
let (allfsig, allffn) = genAllOpFields "allOpFields" cons |
696 |
save_decs <- genSaveOpCode tname "saveOpCode" "toDictOpCode" |
697 |
(map opcodeConsToLuxiCons cons) saveConstructor True |
698 |
(loadsig, loadfn) <- genLoadOpCode cons |
699 |
pyDecls <- pyClasses cons |
700 |
return $ [declD, allfsig, allffn, loadsig, loadfn] ++ save_decs ++ pyDecls |
701 |
|
702 |
-- | Generates the function pattern returning the list of fields for a |
703 |
-- given constructor. |
704 |
genOpConsFields :: OpCodeConstructor -> Clause |
705 |
genOpConsFields (cname, _, _, fields, _) = |
706 |
let op_id = deCamelCase cname |
707 |
fvals = map (LitE . StringL) . sort . nub $ |
708 |
concatMap (\f -> fieldName f:fieldExtraKeys f) fields |
709 |
in Clause [LitP (StringL op_id)] (NormalB $ ListE fvals) [] |
710 |
|
711 |
-- | Generates a list of all fields of an opcode constructor. |
712 |
genAllOpFields :: String -- ^ Function name |
713 |
-> [OpCodeConstructor] -- ^ Object definition |
714 |
-> (Dec, Dec) |
715 |
genAllOpFields sname opdefs = |
716 |
let cclauses = map genOpConsFields opdefs |
717 |
other = Clause [WildP] (NormalB (ListE [])) [] |
718 |
fname = mkName sname |
719 |
sigt = AppT (AppT ArrowT (ConT ''String)) (AppT ListT (ConT ''String)) |
720 |
in (SigD fname sigt, FunD fname (cclauses++[other])) |
721 |
|
722 |
-- | Generates the \"save\" clause for an entire opcode constructor. |
723 |
-- |
724 |
-- This matches the opcode with variables named the same as the |
725 |
-- constructor fields (just so that the spliced in code looks nicer), |
726 |
-- and passes those name plus the parameter definition to 'saveObjectField'. |
727 |
saveConstructor :: LuxiConstructor -- ^ The constructor |
728 |
-> Q Clause -- ^ Resulting clause |
729 |
saveConstructor (sname, fields) = do |
730 |
let cname = mkName sname |
731 |
fnames <- mapM (newName . fieldVariable) fields |
732 |
let pat = conP cname (map varP fnames) |
733 |
let felems = map (uncurry saveObjectField) (zip fnames fields) |
734 |
-- now build the OP_ID serialisation |
735 |
opid = [| [( $(stringE "OP_ID"), |
736 |
JSON.showJSON $(stringE . deCamelCase $ sname) )] |] |
737 |
flist = listE (opid:felems) |
738 |
-- and finally convert all this to a json object |
739 |
flist' = [| concat $flist |] |
740 |
clause [pat] (normalB flist') [] |
741 |
|
742 |
-- | Generates the main save opcode function. |
743 |
-- |
744 |
-- This builds a per-constructor match clause that contains the |
745 |
-- respective constructor-serialisation code. |
746 |
genSaveOpCode :: Name -- ^ Object ype |
747 |
-> String -- ^ To 'JSValue' function name |
748 |
-> String -- ^ To 'JSObject' function name |
749 |
-> [LuxiConstructor] -- ^ Object definition |
750 |
-> (LuxiConstructor -> Q Clause) -- ^ Constructor save fn |
751 |
-> Bool -- ^ Whether to generate |
752 |
-- obj or just a |
753 |
-- list\/tuple of values |
754 |
-> Q [Dec] |
755 |
genSaveOpCode tname jvalstr tdstr opdefs fn gen_object = do |
756 |
tdclauses <- mapM fn opdefs |
757 |
let typecon = ConT tname |
758 |
jvalname = mkName jvalstr |
759 |
jvalsig = AppT (AppT ArrowT typecon) (ConT ''JSON.JSValue) |
760 |
tdname = mkName tdstr |
761 |
tdsig <- [t| $(return typecon) -> [(String, JSON.JSValue)] |] |
762 |
jvalclause <- if gen_object |
763 |
then [| $makeObjE . $(varE tdname) |] |
764 |
else [| JSON.showJSON . map snd . $(varE tdname) |] |
765 |
return [ SigD tdname tdsig |
766 |
, FunD tdname tdclauses |
767 |
, SigD jvalname jvalsig |
768 |
, ValD (VarP jvalname) (NormalB jvalclause) []] |
769 |
|
770 |
-- | Generates load code for a single constructor of the opcode data type. |
771 |
loadConstructor :: OpCodeConstructor -> Q Exp |
772 |
loadConstructor (sname, _, _, fields, _) = do |
773 |
let name = mkName sname |
774 |
fbinds <- mapM loadObjectField fields |
775 |
let (fnames, fstmts) = unzip fbinds |
776 |
let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames |
777 |
fstmts' = fstmts ++ [NoBindS (AppE (VarE 'return) cval)] |
778 |
return $ DoE fstmts' |
779 |
|
780 |
-- | Generates the loadOpCode function. |
781 |
genLoadOpCode :: [OpCodeConstructor] -> Q (Dec, Dec) |
782 |
genLoadOpCode opdefs = do |
783 |
let fname = mkName "loadOpCode" |
784 |
arg1 = mkName "v" |
785 |
objname = mkName "o" |
786 |
opid = mkName "op_id" |
787 |
st1 <- bindS (varP objname) [| liftM JSON.fromJSObject |
788 |
(JSON.readJSON $(varE arg1)) |] |
789 |
st2 <- bindS (varP opid) [| $fromObjE $(varE objname) $(stringE "OP_ID") |] |
790 |
-- the match results (per-constructor blocks) |
791 |
mexps <- mapM loadConstructor opdefs |
792 |
fails <- [| fail $ "Unknown opcode " ++ $(varE opid) |] |
793 |
let mpats = map (\(me, (consName, _, _, _, _)) -> |
794 |
let mp = LitP . StringL . deCamelCase $ consName |
795 |
in Match mp (NormalB me) [] |
796 |
) $ zip mexps opdefs |
797 |
defmatch = Match WildP (NormalB fails) [] |
798 |
cst = NoBindS $ CaseE (VarE opid) $ mpats++[defmatch] |
799 |
body = DoE [st1, st2, cst] |
800 |
sigt <- [t| JSON.JSValue -> JSON.Result $(conT (mkName "OpCode")) |] |
801 |
return $ (SigD fname sigt, FunD fname [Clause [VarP arg1] (NormalB body) []]) |
802 |
|
803 |
-- * Template code for luxi |
804 |
|
805 |
-- | Constructor-to-string for LuxiOp. |
806 |
genStrOfOp :: Name -> String -> Q [Dec] |
807 |
genStrOfOp = genConstrToStr id |
808 |
|
809 |
-- | Constructor-to-string for MsgKeys. |
810 |
genStrOfKey :: Name -> String -> Q [Dec] |
811 |
genStrOfKey = genConstrToStr ensureLower |
812 |
|
813 |
-- | Generates the LuxiOp data type. |
814 |
-- |
815 |
-- This takes a Luxi operation definition and builds both the |
816 |
-- datatype and the function transforming the arguments to JSON. |
817 |
-- We can't use anything less generic, because the way different |
818 |
-- operations are serialized differs on both parameter- and top-level. |
819 |
-- |
820 |
-- There are two things to be defined for each parameter: |
821 |
-- |
822 |
-- * name |
823 |
-- |
824 |
-- * type |
825 |
-- |
826 |
genLuxiOp :: String -> [LuxiConstructor] -> Q [Dec] |
827 |
genLuxiOp name cons = do |
828 |
let tname = mkName name |
829 |
decl_d <- mapM (\(cname, fields) -> do |
830 |
-- we only need the type of the field, without Q |
831 |
fields' <- mapM actualFieldType fields |
832 |
let fields'' = zip (repeat NotStrict) fields' |
833 |
return $ NormalC (mkName cname) fields'') |
834 |
cons |
835 |
let declD = DataD [] (mkName name) [] decl_d [''Show, ''Eq] |
836 |
save_decs <- genSaveOpCode tname "opToArgs" "opToDict" |
837 |
cons saveLuxiConstructor False |
838 |
req_defs <- declareSADT "LuxiReq" . |
839 |
map (\(str, _) -> ("Req" ++ str, mkName ("luxiReq" ++ str))) $ |
840 |
cons |
841 |
return $ declD:save_decs ++ req_defs |
842 |
|
843 |
-- | Generates the \"save\" clause for entire LuxiOp constructor. |
844 |
saveLuxiConstructor :: LuxiConstructor -> Q Clause |
845 |
saveLuxiConstructor (sname, fields) = do |
846 |
let cname = mkName sname |
847 |
fnames <- mapM (newName . fieldVariable) fields |
848 |
let pat = conP cname (map varP fnames) |
849 |
let felems = map (uncurry saveObjectField) (zip fnames fields) |
850 |
flist = [| concat $(listE felems) |] |
851 |
clause [pat] (normalB flist) [] |
852 |
|
853 |
-- * "Objects" functionality |
854 |
|
855 |
-- | Extract the field's declaration from a Field structure. |
856 |
fieldTypeInfo :: String -> Field -> Q (Name, Strict, Type) |
857 |
fieldTypeInfo field_pfx fd = do |
858 |
t <- actualFieldType fd |
859 |
let n = mkName . (field_pfx ++) . fieldRecordName $ fd |
860 |
return (n, NotStrict, t) |
861 |
|
862 |
-- | Build an object declaration. |
863 |
buildObject :: String -> String -> [Field] -> Q [Dec] |
864 |
buildObject sname field_pfx fields = do |
865 |
let name = mkName sname |
866 |
fields_d <- mapM (fieldTypeInfo field_pfx) fields |
867 |
let decl_d = RecC name fields_d |
868 |
let declD = DataD [] name [] [decl_d] [''Show, ''Eq] |
869 |
ser_decls <- buildObjectSerialisation sname fields |
870 |
return $ declD:ser_decls |
871 |
|
872 |
-- | Generates an object definition: data type and its JSON instance. |
873 |
buildObjectSerialisation :: String -> [Field] -> Q [Dec] |
874 |
buildObjectSerialisation sname fields = do |
875 |
let name = mkName sname |
876 |
savedecls <- genSaveObject saveObjectField sname fields |
877 |
(loadsig, loadfn) <- genLoadObject loadObjectField sname fields |
878 |
shjson <- objectShowJSON sname |
879 |
rdjson <- objectReadJSON sname |
880 |
let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) |
881 |
[rdjson, shjson] |
882 |
return $ savedecls ++ [loadsig, loadfn, instdecl] |
883 |
|
884 |
-- | The toDict function name for a given type. |
885 |
toDictName :: String -> Name |
886 |
toDictName sname = mkName ("toDict" ++ sname) |
887 |
|
888 |
-- | Generates the save object functionality. |
889 |
genSaveObject :: (Name -> Field -> Q Exp) |
890 |
-> String -> [Field] -> Q [Dec] |
891 |
genSaveObject save_fn sname fields = do |
892 |
let name = mkName sname |
893 |
fnames <- mapM (newName . fieldVariable) fields |
894 |
let pat = conP name (map varP fnames) |
895 |
let tdname = toDictName sname |
896 |
tdsigt <- [t| $(conT name) -> [(String, JSON.JSValue)] |] |
897 |
|
898 |
let felems = map (uncurry save_fn) (zip fnames fields) |
899 |
flist = listE felems |
900 |
-- and finally convert all this to a json object |
901 |
tdlist = [| concat $flist |] |
902 |
iname = mkName "i" |
903 |
tclause <- clause [pat] (normalB tdlist) [] |
904 |
cclause <- [| $makeObjE . $(varE tdname) |] |
905 |
let fname = mkName ("save" ++ sname) |
906 |
sigt <- [t| $(conT name) -> JSON.JSValue |] |
907 |
return [SigD tdname tdsigt, FunD tdname [tclause], |
908 |
SigD fname sigt, ValD (VarP fname) (NormalB cclause) []] |
909 |
|
910 |
-- | Generates the code for saving an object's field, handling the |
911 |
-- various types of fields that we have. |
912 |
saveObjectField :: Name -> Field -> Q Exp |
913 |
saveObjectField fvar field = |
914 |
let formatFn = fromMaybe [| JSON.showJSON &&& (const []) |] $ |
915 |
fieldShow field |
916 |
formatCode v = [| let (actual, extra) = $formatFn $(v) |
917 |
in ($nameE, actual) : extra |] |
918 |
in case fieldIsOptional field of |
919 |
OptionalOmitNull -> [| case $(fvarE) of |
920 |
Nothing -> [] |
921 |
Just v -> $(formatCode [| v |]) |
922 |
|] |
923 |
OptionalSerializeNull -> [| case $(fvarE) of |
924 |
Nothing -> [( $nameE, JSON.JSNull )] |
925 |
Just v -> $(formatCode [| v |]) |
926 |
|] |
927 |
NotOptional -> formatCode fvarE |
928 |
where nameE = stringE (fieldName field) |
929 |
fvarE = varE fvar |
930 |
|
931 |
-- | Generates the showJSON clause for a given object name. |
932 |
objectShowJSON :: String -> Q Dec |
933 |
objectShowJSON name = do |
934 |
body <- [| JSON.showJSON . $(varE . mkName $ "save" ++ name) |] |
935 |
return $ FunD 'JSON.showJSON [Clause [] (NormalB body) []] |
936 |
|
937 |
-- | Generates the load object functionality. |
938 |
genLoadObject :: (Field -> Q (Name, Stmt)) |
939 |
-> String -> [Field] -> Q (Dec, Dec) |
940 |
genLoadObject load_fn sname fields = do |
941 |
let name = mkName sname |
942 |
funname = mkName $ "load" ++ sname |
943 |
arg1 = mkName $ if null fields then "_" else "v" |
944 |
objname = mkName "o" |
945 |
opid = mkName "op_id" |
946 |
st1 <- bindS (varP objname) [| liftM JSON.fromJSObject |
947 |
(JSON.readJSON $(varE arg1)) |] |
948 |
fbinds <- mapM load_fn fields |
949 |
let (fnames, fstmts) = unzip fbinds |
950 |
let cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) fnames |
951 |
retstmt = [NoBindS (AppE (VarE 'return) cval)] |
952 |
-- FIXME: should we require an empty dict for an empty type? |
953 |
-- this allows any JSValue right now |
954 |
fstmts' = if null fields |
955 |
then retstmt |
956 |
else st1:fstmts ++ retstmt |
957 |
sigt <- [t| JSON.JSValue -> JSON.Result $(conT name) |] |
958 |
return $ (SigD funname sigt, |
959 |
FunD funname [Clause [VarP arg1] (NormalB (DoE fstmts')) []]) |
960 |
|
961 |
-- | Generates code for loading an object's field. |
962 |
loadObjectField :: Field -> Q (Name, Stmt) |
963 |
loadObjectField field = do |
964 |
let name = fieldVariable field |
965 |
fvar <- newName name |
966 |
-- these are used in all patterns below |
967 |
let objvar = varNameE "o" |
968 |
objfield = stringE (fieldName field) |
969 |
bexp <- case fieldDefault field of |
970 |
-- Only non-optional fields without defaults must have a value; |
971 |
-- we treat both optional types the same, since |
972 |
-- 'maybeFromObj' can deal with both missing and null values |
973 |
-- appropriately (the same) |
974 |
Nothing | fieldIsOptional field == NotOptional -> |
975 |
loadFn field [| fromObj $objvar $objfield |] objvar |
976 |
_ -> loadFnOpt field [| maybeFromObj $objvar $objfield |] objvar |
977 |
|
978 |
return (fvar, BindS (VarP fvar) bexp) |
979 |
|
980 |
-- | Builds the readJSON instance for a given object name. |
981 |
objectReadJSON :: String -> Q Dec |
982 |
objectReadJSON name = do |
983 |
let s = mkName "s" |
984 |
body <- [| case JSON.readJSON $(varE s) of |
985 |
JSON.Ok s' -> $(varE .mkName $ "load" ++ name) s' |
986 |
JSON.Error e -> |
987 |
JSON.Error $ "Can't parse value for type " ++ |
988 |
$(stringE name) ++ ": " ++ e |
989 |
|] |
990 |
return $ FunD 'JSON.readJSON [Clause [VarP s] (NormalB body) []] |
991 |
|
992 |
-- * Inheritable parameter tables implementation |
993 |
|
994 |
-- | Compute parameter type names. |
995 |
paramTypeNames :: String -> (String, String) |
996 |
paramTypeNames root = ("Filled" ++ root ++ "Params", |
997 |
"Partial" ++ root ++ "Params") |
998 |
|
999 |
-- | Compute information about the type of a parameter field. |
1000 |
paramFieldTypeInfo :: String -> Field -> Q (Name, Strict, Type) |
1001 |
paramFieldTypeInfo field_pfx fd = do |
1002 |
t <- actualFieldType fd |
1003 |
let n = mkName . (++ "P") . (field_pfx ++) . |
1004 |
fieldRecordName $ fd |
1005 |
return (n, NotStrict, AppT (ConT ''Maybe) t) |
1006 |
|
1007 |
-- | Build a parameter declaration. |
1008 |
-- |
1009 |
-- This function builds two different data structures: a /filled/ one, |
1010 |
-- in which all fields are required, and a /partial/ one, in which all |
1011 |
-- fields are optional. Due to the current record syntax issues, the |
1012 |
-- fields need to be named differrently for the two structures, so the |
1013 |
-- partial ones get a /P/ suffix. |
1014 |
buildParam :: String -> String -> [Field] -> Q [Dec] |
1015 |
buildParam sname field_pfx fields = do |
1016 |
let (sname_f, sname_p) = paramTypeNames sname |
1017 |
name_f = mkName sname_f |
1018 |
name_p = mkName sname_p |
1019 |
fields_f <- mapM (fieldTypeInfo field_pfx) fields |
1020 |
fields_p <- mapM (paramFieldTypeInfo field_pfx) fields |
1021 |
let decl_f = RecC name_f fields_f |
1022 |
decl_p = RecC name_p fields_p |
1023 |
let declF = DataD [] name_f [] [decl_f] [''Show, ''Eq] |
1024 |
declP = DataD [] name_p [] [decl_p] [''Show, ''Eq] |
1025 |
ser_decls_f <- buildObjectSerialisation sname_f fields |
1026 |
ser_decls_p <- buildPParamSerialisation sname_p fields |
1027 |
fill_decls <- fillParam sname field_pfx fields |
1028 |
return $ [declF, declP] ++ ser_decls_f ++ ser_decls_p ++ fill_decls ++ |
1029 |
buildParamAllFields sname fields ++ |
1030 |
buildDictObjectInst name_f sname_f |
1031 |
|
1032 |
-- | Builds a list of all fields of a parameter. |
1033 |
buildParamAllFields :: String -> [Field] -> [Dec] |
1034 |
buildParamAllFields sname fields = |
1035 |
let vname = mkName ("all" ++ sname ++ "ParamFields") |
1036 |
sig = SigD vname (AppT ListT (ConT ''String)) |
1037 |
val = ListE $ map (LitE . StringL . fieldName) fields |
1038 |
in [sig, ValD (VarP vname) (NormalB val) []] |
1039 |
|
1040 |
-- | Builds the 'DictObject' instance for a filled parameter. |
1041 |
buildDictObjectInst :: Name -> String -> [Dec] |
1042 |
buildDictObjectInst name sname = |
1043 |
[InstanceD [] (AppT (ConT ''DictObject) (ConT name)) |
1044 |
[ValD (VarP 'toDict) (NormalB (VarE (toDictName sname))) []]] |
1045 |
|
1046 |
-- | Generates the serialisation for a partial parameter. |
1047 |
buildPParamSerialisation :: String -> [Field] -> Q [Dec] |
1048 |
buildPParamSerialisation sname fields = do |
1049 |
let name = mkName sname |
1050 |
savedecls <- genSaveObject savePParamField sname fields |
1051 |
(loadsig, loadfn) <- genLoadObject loadPParamField sname fields |
1052 |
shjson <- objectShowJSON sname |
1053 |
rdjson <- objectReadJSON sname |
1054 |
let instdecl = InstanceD [] (AppT (ConT ''JSON.JSON) (ConT name)) |
1055 |
[rdjson, shjson] |
1056 |
return $ savedecls ++ [loadsig, loadfn, instdecl] |
1057 |
|
1058 |
-- | Generates code to save an optional parameter field. |
1059 |
savePParamField :: Name -> Field -> Q Exp |
1060 |
savePParamField fvar field = do |
1061 |
checkNonOptDef field |
1062 |
let actualVal = mkName "v" |
1063 |
normalexpr <- saveObjectField actualVal field |
1064 |
-- we have to construct the block here manually, because we can't |
1065 |
-- splice-in-splice |
1066 |
return $ CaseE (VarE fvar) [ Match (ConP 'Nothing []) |
1067 |
(NormalB (ConE '[])) [] |
1068 |
, Match (ConP 'Just [VarP actualVal]) |
1069 |
(NormalB normalexpr) [] |
1070 |
] |
1071 |
|
1072 |
-- | Generates code to load an optional parameter field. |
1073 |
loadPParamField :: Field -> Q (Name, Stmt) |
1074 |
loadPParamField field = do |
1075 |
checkNonOptDef field |
1076 |
let name = fieldName field |
1077 |
fvar <- newName name |
1078 |
-- these are used in all patterns below |
1079 |
let objvar = varNameE "o" |
1080 |
objfield = stringE name |
1081 |
loadexp = [| $(varE 'maybeFromObj) $objvar $objfield |] |
1082 |
bexp <- loadFnOpt field loadexp objvar |
1083 |
return (fvar, BindS (VarP fvar) bexp) |
1084 |
|
1085 |
-- | Builds a simple declaration of type @n_x = fromMaybe f_x p_x@. |
1086 |
buildFromMaybe :: String -> Q Dec |
1087 |
buildFromMaybe fname = |
1088 |
valD (varP (mkName $ "n_" ++ fname)) |
1089 |
(normalB [| $(varE 'fromMaybe) |
1090 |
$(varNameE $ "f_" ++ fname) |
1091 |
$(varNameE $ "p_" ++ fname) |]) [] |
1092 |
|
1093 |
-- | Builds a function that executes the filling of partial parameter |
1094 |
-- from a full copy (similar to Python's fillDict). |
1095 |
fillParam :: String -> String -> [Field] -> Q [Dec] |
1096 |
fillParam sname field_pfx fields = do |
1097 |
let fnames = map (\fd -> field_pfx ++ fieldRecordName fd) fields |
1098 |
(sname_f, sname_p) = paramTypeNames sname |
1099 |
oname_f = "fobj" |
1100 |
oname_p = "pobj" |
1101 |
name_f = mkName sname_f |
1102 |
name_p = mkName sname_p |
1103 |
fun_name = mkName $ "fill" ++ sname ++ "Params" |
1104 |
le_full = ValD (ConP name_f (map (VarP . mkName . ("f_" ++)) fnames)) |
1105 |
(NormalB . VarE . mkName $ oname_f) [] |
1106 |
le_part = ValD (ConP name_p (map (VarP . mkName . ("p_" ++)) fnames)) |
1107 |
(NormalB . VarE . mkName $ oname_p) [] |
1108 |
obj_new = foldl (\accu vname -> AppE accu (VarE vname)) (ConE name_f) |
1109 |
$ map (mkName . ("n_" ++)) fnames |
1110 |
le_new <- mapM buildFromMaybe fnames |
1111 |
funt <- [t| $(conT name_f) -> $(conT name_p) -> $(conT name_f) |] |
1112 |
let sig = SigD fun_name funt |
1113 |
fclause = Clause [VarP (mkName oname_f), VarP (mkName oname_p)] |
1114 |
(NormalB $ LetE (le_full:le_part:le_new) obj_new) [] |
1115 |
fun = FunD fun_name [fclause] |
1116 |
return [sig, fun] |
1117 |
|
1118 |
-- * Template code for exceptions |
1119 |
|
1120 |
-- | Exception simple error message field. |
1121 |
excErrMsg :: (String, Q Type) |
1122 |
excErrMsg = ("errMsg", [t| String |]) |
1123 |
|
1124 |
-- | Builds an exception type definition. |
1125 |
genException :: String -- ^ Name of new type |
1126 |
-> SimpleObject -- ^ Constructor name and parameters |
1127 |
-> Q [Dec] |
1128 |
genException name cons = do |
1129 |
let tname = mkName name |
1130 |
declD <- buildSimpleCons tname cons |
1131 |
(savesig, savefn) <- genSaveSimpleObj tname ("save" ++ name) cons $ |
1132 |
uncurry saveExcCons |
1133 |
(loadsig, loadfn) <- genLoadExc tname ("load" ++ name) cons |
1134 |
return [declD, loadsig, loadfn, savesig, savefn] |
1135 |
|
1136 |
-- | Generates the \"save\" clause for an entire exception constructor. |
1137 |
-- |
1138 |
-- This matches the exception with variables named the same as the |
1139 |
-- constructor fields (just so that the spliced in code looks nicer), |
1140 |
-- and calls showJSON on it. |
1141 |
saveExcCons :: String -- ^ The constructor name |
1142 |
-> [SimpleField] -- ^ The parameter definitions for this |
1143 |
-- constructor |
1144 |
-> Q Clause -- ^ Resulting clause |
1145 |
saveExcCons sname fields = do |
1146 |
let cname = mkName sname |
1147 |
fnames <- mapM (newName . fst) fields |
1148 |
let pat = conP cname (map varP fnames) |
1149 |
felems = if null fnames |
1150 |
then conE '() -- otherwise, empty list has no type |
1151 |
else listE $ map (\f -> [| JSON.showJSON $(varE f) |]) fnames |
1152 |
let tup = tupE [ litE (stringL sname), felems ] |
1153 |
clause [pat] (normalB [| JSON.showJSON $tup |]) [] |
1154 |
|
1155 |
-- | Generates load code for a single constructor of an exception. |
1156 |
-- |
1157 |
-- Generates the code (if there's only one argument, we will use a |
1158 |
-- list, not a tuple: |
1159 |
-- |
1160 |
-- @ |
1161 |
-- do |
1162 |
-- (x1, x2, ...) <- readJSON args |
1163 |
-- return $ Cons x1 x2 ... |
1164 |
-- @ |
1165 |
loadExcConstructor :: Name -> String -> [SimpleField] -> Q Exp |
1166 |
loadExcConstructor inname sname fields = do |
1167 |
let name = mkName sname |
1168 |
f_names <- mapM (newName . fst) fields |
1169 |
let read_args = AppE (VarE 'JSON.readJSON) (VarE inname) |
1170 |
let binds = case f_names of |
1171 |
[x] -> BindS (ListP [VarP x]) |
1172 |
_ -> BindS (TupP (map VarP f_names)) |
1173 |
cval = foldl (\accu fn -> AppE accu (VarE fn)) (ConE name) f_names |
1174 |
return $ DoE [binds read_args, NoBindS (AppE (VarE 'return) cval)] |
1175 |
|
1176 |
{-| Generates the loadException function. |
1177 |
|
1178 |
This generates a quite complicated function, along the lines of: |
1179 |
|
1180 |
@ |
1181 |
loadFn (JSArray [JSString name, args]) = case name of |
1182 |
"A1" -> do |
1183 |
(x1, x2, ...) <- readJSON args |
1184 |
return $ A1 x1 x2 ... |
1185 |
"a2" -> ... |
1186 |
s -> fail $ "Unknown exception" ++ s |
1187 |
loadFn v = fail $ "Expected array but got " ++ show v |
1188 |
@ |
1189 |
-} |
1190 |
genLoadExc :: Name -> String -> SimpleObject -> Q (Dec, Dec) |
1191 |
genLoadExc tname sname opdefs = do |
1192 |
let fname = mkName sname |
1193 |
exc_name <- newName "name" |
1194 |
exc_args <- newName "args" |
1195 |
exc_else <- newName "s" |
1196 |
arg_else <- newName "v" |
1197 |
fails <- [| fail $ "Unknown exception '" ++ $(varE exc_else) ++ "'" |] |
1198 |
-- default match for unknown exception name |
1199 |
let defmatch = Match (VarP exc_else) (NormalB fails) [] |
1200 |
-- the match results (per-constructor blocks) |
1201 |
str_matches <- |
1202 |
mapM (\(s, params) -> do |
1203 |
body_exp <- loadExcConstructor exc_args s params |
1204 |
return $ Match (LitP (StringL s)) (NormalB body_exp) []) |
1205 |
opdefs |
1206 |
-- the first function clause; we can't use [| |] due to TH |
1207 |
-- limitations, so we have to build the AST by hand |
1208 |
let clause1 = Clause [ConP 'JSON.JSArray |
1209 |
[ListP [ConP 'JSON.JSString [VarP exc_name], |
1210 |
VarP exc_args]]] |
1211 |
(NormalB (CaseE (AppE (VarE 'JSON.fromJSString) |
1212 |
(VarE exc_name)) |
1213 |
(str_matches ++ [defmatch]))) [] |
1214 |
-- the fail expression for the second function clause |
1215 |
fail_type <- [| fail $ "Invalid exception: expected '(string, [args])' " ++ |
1216 |
" but got " ++ show (pp_value $(varE arg_else)) ++ "'" |
1217 |
|] |
1218 |
-- the second function clause |
1219 |
let clause2 = Clause [VarP arg_else] (NormalB fail_type) [] |
1220 |
sigt <- [t| JSON.JSValue -> JSON.Result $(conT tname) |] |
1221 |
return $ (SigD fname sigt, FunD fname [clause1, clause2]) |