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