-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathCompile.hs
More file actions
310 lines (266 loc) · 12.3 KB
/
Compile.hs
File metadata and controls
310 lines (266 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
{-# LANGUAGE GADTs #-}
-- | Compile Copilot specifications to C99 code.
module Copilot.Compile.C99.Compile
( compile
, compileWith
) where
-- External imports
import Data.List ( nub, nubBy, union )
import Data.Maybe ( mapMaybe )
import Data.Type.Equality ( testEquality, (:~:)(Refl) )
import Data.Typeable ( Typeable )
import Language.C99.Pretty ( pretty )
import qualified Language.C99.Simple as C
import System.Directory ( createDirectoryIfMissing )
import System.Exit ( exitFailure )
import System.FilePath ( (</>) )
import System.IO ( hPutStrLn, stderr )
import Text.PrettyPrint ( render )
-- Internal imports: Copilot
import Copilot.Core ( Expr (..), Spec (..), Stream (..), Struct (..),
Trigger (..), Type (..), UExpr (..), UType (..),
Value (..) )
-- Internal imports
import Copilot.Compile.C99.CodeGen ( mkAccessDecln, mkBuffDecln,
mkExtCpyDecln, mkExtDecln,
mkGenFun, mkGenFunArray,
mkIndexDecln, mkStep,
mkStructDecln, mkStructForwDecln )
import Copilot.Compile.C99.External ( External, gatherExts )
import Copilot.Compile.C99.Name ( argNames, generatorName,
generatorOutputArgName, guardName )
import Copilot.Compile.C99.Settings ( CSettings,
cSettingsOutputDirectory,
cSettingsStepFunctionName,
mkDefaultCSettings )
import Copilot.Compile.C99.Type ( transType )
import Copilot.Compile.C99.Representation ( UniqueTrigger (..),
mkUniqueTriggers )
-- | Compile a specification to a .h and a .c file.
--
-- The first argument is the settings for the C code generated.
--
-- The second argument is used as prefix for the .h and .c files generated.
compileWith :: CSettings -> String -> Spec -> IO ()
compileWith cSettings prefix spec
| null triggers
= do hPutStrLn stderr $
"Copilot error: attempt at compiling empty specification.\n"
++ "You must define at least one trigger to generate C monitors."
exitFailure
| incompatibleTriggers triggers
= do hPutStrLn stderr $
"Copilot error: attempt at compiling specification with conflicting "
++ "trigger definitions.\n"
++ "Multiple triggers have the same name, but different argument "
++ "types.\n"
exitFailure
| otherwise
= do let cFile = render $ pretty $ C.translate $ compileC cSettings spec
hFile = render $ pretty $ C.translate $ compileH cSettings spec
typeDeclnsFile = safeCRender $ compileTypeDeclns cSettings spec
cMacros = unlines [ "#include <stdint.h>"
, "#include <stdbool.h>"
, "#include <string.h>"
, "#include <stdlib.h>"
, "#include <math.h>"
, ""
, "#include \"" ++ prefix ++ "_types.h\""
, "#include \"" ++ prefix ++ ".h\""
, ""
]
let dir = cSettingsOutputDirectory cSettings
createDirectoryIfMissing True dir
writeFile (dir </> prefix ++ ".c") $ cMacros ++ cFile
writeFile (dir </> prefix ++ ".h") hFile
writeFile (dir </> prefix ++ "_types.h") typeDeclnsFile
where
triggers = specTriggers spec
-- Check that two triggers do no conflict, that is: if their names are
-- equal, the types of their arguments should be equal as well.
incompatibleTriggers :: [Trigger] -> Bool
incompatibleTriggers = pairwiseAny conflict
where
conflict :: Trigger -> Trigger -> Bool
conflict t1@(Trigger name1 _ _) t2@(Trigger name2 _ _) =
name1 == name2 && not (compareTrigger t1 t2)
-- True if the function holds for any pair of elements. We assume that
-- the function is commutative.
pairwiseAny :: (a -> a -> Bool) -> [a] -> Bool
pairwiseAny _ [] = False
pairwiseAny _ (_:[]) = False
pairwiseAny f (x:xs) = any (f x) xs || pairwiseAny f xs
-- | Compile a specification to a .h and a .c file.
--
-- The first argument is used as prefix for the .h and .c files generated.
compile :: String -> Spec -> IO ()
compile = compileWith mkDefaultCSettings
-- | Generate the .c file from a 'Spec'.
--
-- The generated C file has the following structure:
--
-- * Include .h file.
-- * Declarations of global buffers and indices.
-- * Generator functions for streams, guards and trigger arguments.
-- * Declaration of the @step()@ function.
compileC :: CSettings -> Spec -> C.TransUnit
compileC cSettings spec = C.TransUnit declns funs
where
declns = mkExts exts
++ mkGlobals streams
funs = mkGenFuns streams uniqueTriggers
++ [mkStep cSettings streams uniqueTriggers exts]
streams = specStreams spec
triggers = specTriggers spec
uniqueTriggers = mkUniqueTriggers triggers
exts = gatherExts streams triggers
-- Make declarations for copies of external variables.
mkExts :: [External] -> [C.Decln]
mkExts = map mkExtCpyDecln
-- Make buffer and index declarations for streams.
mkGlobals :: [Stream] -> [C.Decln]
mkGlobals streamList = map buffDecln streamList
++ map indexDecln streamList
where
buffDecln (Stream sId buff _ ty) = mkBuffDecln sId ty buff
indexDecln (Stream sId _ _ _ ) = mkIndexDecln sId
-- Make generator functions, including trigger arguments.
mkGenFuns :: [Stream] -> [UniqueTrigger] -> [C.FunDef]
mkGenFuns streamList triggerList = map accessDecln streamList
++ map streamGen streamList
++ concatMap triggerGen triggerList
where
accessDecln :: Stream -> C.FunDef
accessDecln (Stream sId buff _ ty) = mkAccessDecln sId ty buff
streamGen :: Stream -> C.FunDef
streamGen (Stream sId _ expr ty) =
exprGen (generatorName sId) (generatorOutputArgName sId) expr ty
triggerGen :: UniqueTrigger -> [C.FunDef]
triggerGen (UniqueTrigger uniqueName (Trigger _name guard args)) = guardDef : argDefs
where
guardDef = mkGenFun (guardName uniqueName) guard Bool
argDefs = zipWith argGen (argNames uniqueName) args
argGen :: String -> UExpr -> C.FunDef
argGen argName (UExpr ty expr) =
exprGen argName (argName ++ "_output") expr ty
-- Create a function that calculates the current value generated by an
-- expression `expr` of type `ty`. The generator treats arrays
-- specially, and the function takes an output array as a parameter.
-- The second identifier `outputArrName` is not used if `expr` is not an
-- array.
exprGen :: C.Ident -> C.Ident -> Expr a -> Type a -> C.FunDef
exprGen funName outputArrName expr ty@(Array _) =
mkGenFunArray funName outputArrName expr ty
exprGen funName _ expr ty =
mkGenFun funName expr ty
-- | Generate the .h file from a 'Spec'.
compileH :: CSettings -> Spec -> C.TransUnit
compileH cSettings spec = C.TransUnit declns []
where
declns = mkStructForwDeclns exprs
++ mkExts exts
++ extFunDeclns triggers
++ [stepDecln]
exprs = gatherExprs streams triggers
exts = gatherExts streams triggers
streams = specStreams spec
-- Remove duplicates due to multiple guards for the same trigger.
triggers = nubBy compareTrigger (specTriggers spec)
mkStructForwDeclns :: [UExpr] -> [C.Decln]
mkStructForwDeclns es = mapMaybe mkDecln uTypes
where
mkDecln (UType ty) = case ty of
Struct _ -> Just $ mkStructForwDecln ty
_ -> Nothing
uTypes = nub $ concatMap (\(UExpr _ e) -> exprTypes e) es
-- Make declarations for external variables.
mkExts :: [External] -> [C.Decln]
mkExts = map mkExtDecln
extFunDeclns :: [Trigger] -> [C.Decln]
extFunDeclns = map extFunDecln
where
extFunDecln :: Trigger -> C.Decln
extFunDecln (Trigger name _ args) = C.FunDecln Nothing cTy name params
where
cTy = C.TypeSpec C.Void
params = zipWith mkParam (argNames name) args
mkParam paramName (UExpr ty _) = C.Param (mkParamTy ty) paramName
-- Special case for Struct, to pass struct arguments by reference.
-- Arrays are also passed by reference, but using C's array type
-- does that automatically.
mkParamTy ty =
case ty of
Struct _ -> C.Ptr (transType ty)
_ -> transType ty
-- Declaration for the step function.
stepDecln :: C.Decln
stepDecln = C.FunDecln Nothing (C.TypeSpec C.Void)
(cSettingsStepFunctionName cSettings) []
-- | Generate a C translation unit that contains all type declarations needed
-- by the Copilot specification.
compileTypeDeclns :: CSettings -> Spec -> C.TransUnit
compileTypeDeclns _cSettings spec = C.TransUnit declns []
where
declns = mkTypeDeclns exprs
exprs = gatherExprs streams triggers
streams = specStreams spec
triggers = specTriggers spec
-- Generate type declarations.
mkTypeDeclns :: [UExpr] -> [C.Decln]
mkTypeDeclns es = mapMaybe mkTypeDecln uTypes
where
uTypes = nub $ concatMap (\(UExpr _ e) -> exprTypes e) es
mkTypeDecln (UType ty) = case ty of
Struct _ -> Just $ mkStructDecln ty
_ -> Nothing
-- * Auxiliary definitions
-- | Render a C.TransUnit to a String, accounting for the case in which the
-- translation unit is empty.
safeCRender :: C.TransUnit -> String
safeCRender (C.TransUnit [] []) = ""
safeCRender transUnit = render $ pretty $ C.translate transUnit
-- ** Obtain information from Copilot Core Exprs and Types.
-- | List all types of an expression, returns items uniquely.
exprTypes :: Typeable a => Expr a -> [UType]
exprTypes e = case e of
Const ty _ -> typeTypes ty
Local ty1 ty2 _ e1 e2 -> typeTypes ty1 `union` typeTypes ty2
`union` exprTypes e1 `union` exprTypes e2
Var ty _ -> typeTypes ty
Drop ty _ _ -> typeTypes ty
ExternVar ty _ _ -> typeTypes ty
Op1 _ e1 -> exprTypes e1
Op2 _ e1 e2 -> exprTypes e1 `union` exprTypes e2
Op3 _ e1 e2 e3 -> exprTypes e1 `union` exprTypes e2
`union` exprTypes e3
Label ty _ _ -> typeTypes ty
-- | List all types of a type, returns items uniquely.
typeTypes :: Typeable a => Type a -> [UType]
typeTypes ty = case ty of
Array ty' -> typeTypes ty' `union` [UType ty]
Struct x -> concatMap (\(Value ty' _) -> typeTypes ty') (toValues x)
`union` [UType ty]
_ -> [UType ty]
-- | Collect all expression of a list of streams and triggers and wrap them
-- into an UExpr.
gatherExprs :: [Stream] -> [Trigger] -> [UExpr]
gatherExprs streams triggers = map streamUExpr streams
++ concatMap triggerUExpr triggers
where
streamUExpr (Stream _ _ expr ty) = UExpr ty expr
triggerUExpr (Trigger _ guard args) = UExpr Bool guard : args
-- | We consider triggers to be equal, if their names match and the number and
-- types of arguments.
compareTrigger :: Trigger -> Trigger -> Bool
compareTrigger (Trigger name1 _ args1) (Trigger name2 _ args2)
= name1 == name2 && compareArguments args1 args2
where
compareArguments :: [UExpr] -> [UExpr] -> Bool
compareArguments [] [] = True
compareArguments [] _ = False
compareArguments _ [] = False
compareArguments (x:xs) (y:ys) = compareUExpr x y && compareArguments xs ys
compareUExpr :: UExpr -> UExpr -> Bool
compareUExpr (UExpr ty1 _) (UExpr ty2 _)
| Just Refl <- testEquality ty1 ty2 = True
| otherwise = False