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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE IncoherentInstances #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE UndecidableInstances #-}
module Language.Fiddle.Compiler.ConsistencyCheck (consistencyCheckPhase) where
import Control.Monad (forM_, unless, when)
import Control.Monad.RWS (MonadWriter (tell))
import Control.Monad.Trans.Writer (Writer, execWriter)
import Data.Foldable (foldlM, toList)
import Data.Functor.Identity
import qualified Data.IntMap as IntMap
import Data.List (intercalate)
import qualified Data.List.NonEmpty as NonEmpty
import Data.Typeable
import Data.Word (Word32)
import GHC.TypeError as TypeError
import Language.Fiddle.Ast
import Language.Fiddle.Compiler
import Language.Fiddle.Internal.UnitInterface as UnitInterface
import Language.Fiddle.Types
import Text.Printf (printf)
import Prelude hiding (unzip)
type S = Qualified
type S' = Checked
type F = Identity
type A = Commented SourceSpan
type M = Compile ()
instance CompilationStage Checked where
type StageAfter Checked = TypeError (TypeError.Text "No stage after Checked")
type StageMonad Checked = M
type StageState Checked = ()
type StageFunctor Checked = Identity
type StageAnnotation Checked = A
instance CompilationStage S where
type StageAfter S = S'
type StageMonad S = M
type StageState S = ()
type StageFunctor S = F
type StageAnnotation S = A
consistencyCheckPhase :: CompilationPhase S S'
consistencyCheckPhase = pureCompilationPhase $ advanceStage ()
instance AdvanceStage S ObjTypeBody where
advanceStage () objTypeBody = snd <$> advanceObjTypeBody objTypeBody 0
deriving instance AdvanceStage S AnonymousBitsType
deriving instance AdvanceStage S ImportStatement
instance AdvanceStage S BitType where
customAdvanceStage t _ = do
case t of
(EnumBitType sz (Identity body) _) -> do
checkEnumConsistency sz body
_ -> return ()
return Nothing
deriving instance AdvanceStage S EnumBody
deriving instance AdvanceStage S EnumConstantDecl
deriving instance AdvanceStage S PackageBody
deriving instance AdvanceStage S FiddleDecl
instance AdvanceStage S FiddleUnit where
advanceStage () fu@(FiddleUnit _ decls a) =
FiddleUnit (getUnitInterface fu) <$> mapM (advanceStage ()) decls <*> pure a
where
getUnitInterface = execWriter . walk_ doWalk
doWalk :: forall t'. (Walk t', Typeable t') => t' F A -> Writer UnitInterface ()
doWalk t =
case () of
()
| (Just (PackageDecl {packageQualificationMetadata = (Identity d)})) <-
castTS t ->
tell (UnitInterface.singleton d)
| (Just (LocationDecl {locationQualificationMetadata = (Identity d)})) <-
castTS t ->
tell (UnitInterface.singleton d)
| (Just (BitsDecl {bitsQualificationMetadata = (Identity d)})) <-
castTS t ->
tell (UnitInterface.singleton d)
| (Just (ObjTypeDecl {objTypeQualificationMetadata = (Identity d)})) <-
castTS t ->
tell (UnitInterface.singleton d)
| (Just (ObjectDecl {objectQualificationMetadata = (Identity d)})) <-
castTS t ->
tell (UnitInterface.singleton d)
| (Just (ImportStatement {importInterface = ii})) <-
castTS t ->
tell (UnitInterface mempty (dependencies ii))
_ -> return ()
castTS ::
(Typeable t', Typeable t, Typeable f, Typeable a) =>
t' f a ->
Maybe (t S f a)
castTS = cast
deriving instance AdvanceStage S Expression
deriving instance AdvanceStage S RegisterBitsTypeRef
deriving instance AdvanceStage S ObjType
deriving instance (AdvanceStage S t) => AdvanceStage S (Directed t)
advanceObjTypeBody :: ObjTypeBody S F A -> Word32 -> M (Word32, ObjTypeBody S' F A)
advanceObjTypeBody (ObjTypeBody us decls a) startOffset = do
(decls', _) <- advanceDecls
calcSize <- case us of
Union {} -> do
checkJagged decls'
return $ maximum (map fst decls')
Struct {} -> return $ sum (map fst decls')
return (calcSize, ObjTypeBody us (reverse $ map snd decls') a)
where
advanceDecls :: M ([(Word32, Directed ObjTypeDecl S' F A)], Word32)
advanceDecls = do
foldlM
( \(ret, offset) d ->
let advanceOffset = case us of
Union {} -> const
Struct {} -> (+)
doReturn x size = return ((size, mapDirected (const x) d) : ret, advanceOffset offset size)
in case undirected d of
e@AssertPosStatement {assertExpr = expr} -> do
assertedPos <- expressionToIntM expr
checkPositionAssertion (annot e) assertedPos offset
return (ret, offset)
(RegisterDecl _ mod ident size Nothing a) -> do
(sizeExpr, reifiedSize) <- advanceAndGetSize size
doReturn (RegisterDecl offset mod ident sizeExpr Nothing a)
=<< checkBitsSizeMod8 a reifiedSize
(RegisterDecl _ mod ident size (Just body) a) -> do
declaredSize <- expressionToIntM size
(actualSize, body') <- advanceRegisterBody body
checkSizeMismatch a declaredSize actualSize
(sizeExpr, reifiedSize) <- advanceAndGetSize size
doReturn (RegisterDecl offset mod ident sizeExpr (Just body') a)
=<< checkBitsSizeMod8 a reifiedSize
(ReservedDecl size a) -> do
(sizeExpr, reifiedSize) <- advanceAndGetSize size
doReturn (ReservedDecl sizeExpr a) reifiedSize
(TypeSubStructure (Identity body) name a) -> do
(size, body') <- advanceObjTypeBody body offset
doReturn (TypeSubStructure (Identity body') name a) size
)
(([], startOffset) :: ([(Word32, Directed ObjTypeDecl S' F A)], Word32))
decls
advanceAndGetSize e = (,) <$> advanceStage () e <*> expressionToIntM e
pattern RegisterBodyPattern :: BodyType F A -> [Directed RegisterBitsDecl s F A] -> A -> A -> RegisterBody s F A
pattern RegisterBodyPattern u decls a b = RegisterBody u (Identity (DeferredRegisterBody decls b)) a
-- registerBodyPattern u decls a b = RegisterBody u (Identity (DeferredRegisterBody decls a)) a
advanceRegisterBody :: RegisterBody S F A -> M (Word32, RegisterBody S' F A)
-- Handle the case where it's a union.
advanceRegisterBody
(RegisterBodyPattern us (NonEmpty.nonEmpty -> Just decls) a b) = do
(structSize, reverse -> decls') <-
foldlM
( \(offset, ret) d -> do
(sz, t) <- advanceDecl offset (undirected d)
let advanceOffset off sz =
case us of
Union {} -> off
Struct {} -> off + sz
return (advanceOffset offset sz, (sz, mapDirected (const t) d) : ret)
)
(0, [])
decls
calcSize <- case us of
Union {} -> do
checkJagged decls'
return $ maximum (map fst decls')
Struct {} -> return structSize
return (calcSize, RegisterBodyPattern us (map snd $ toList decls') a b)
-- Handle the case where there's no decls.
advanceRegisterBody (RegisterBodyPattern u _ a b) =
return (0, RegisterBodyPattern u [] a b)
advanceRegisterBody RegisterBody {} = error "GHC not smart enuf"
checkJagged :: (Annotated t) => [(Word32, t f A)] -> Compile s ()
checkJagged decls = do
let expectedSize = maximum (fmap fst decls)
forM_ decls $ \(sz, annot -> a) ->
when (sz /= expectedSize) $
emitDiagnosticWarning
( printf
"[JaggedUnion] - All elements of a union should be the same size. \
\ this element is size %d, expected size %d. Maybe bundle this with \
\ reserved(%d)?"
sz
expectedSize
(expectedSize - sz)
)
a
advanceDecl :: Word32 -> RegisterBitsDecl S F A -> M (Word32, RegisterBitsDecl S' F A)
advanceDecl offset = \case
ReservedBits expr an -> do
sz <- expressionToIntM expr
(sz,)
<$> ( ReservedBits
<$> advanceStage () expr
<*> pure an
)
DefinedBits _ mod ident typ annot -> do
size <- bitsTypeSize typ
(size,)
<$> (DefinedBits offset mod ident <$> advanceStage () typ <*> pure annot)
BitsSubStructure subBody subName ann -> do
(sz, body') <- advanceRegisterBody subBody
return (sz, BitsSubStructure body' subName ann)
bitsTypeSize :: RegisterBitsTypeRef S F A -> M Word32
bitsTypeSize (RegisterBitsArray tr nExpr _) = do
sz <- bitsTypeSize tr
n <- expressionToIntM nExpr
return (sz * n)
bitsTypeSize
RegisterBitsReference
{ bitsRefQualificationMetadata =
Identity (ExportedBitsDecl {exportedBitsDeclSizeBits = sz})
} = return sz
bitsTypeSize (RegisterBitsJustBits expr _) =
expressionToIntM expr
checkSizeMismatch :: A -> Word32 -> Word32 -> Compile s ()
checkSizeMismatch _ a b | a == b = return ()
checkSizeMismatch pos declaredSize calculatedSize =
emitDiagnosticError
( printf
"Size assertion failed. Declared size %d, calculated %d"
declaredSize
calculatedSize
)
pos
checkPositionAssertion :: A -> Word32 -> Word32 -> Compile s ()
checkPositionAssertion _ a b | a == b = return ()
checkPositionAssertion pos declaredPosition calculatedPostion =
emitDiagnosticError
( printf
"Position assertion failed. Asserted 0x%x, calculated 0x%x"
declaredPosition
calculatedPostion
)
pos
expressionToIntM ::
(Integral i, Integral (NumberType stage)) =>
Expression stage f A ->
Compile s i
expressionToIntM expr =
resolveOrFail $
either
( \reason -> Left [Diagnostic Error reason (unCommented $ annot expr)]
)
return
(expressionToInt expr)
checkBitsSizeMod8 :: A -> Word32 -> M Word32
checkBitsSizeMod8 _ w | w `mod` 8 == 0 = return (w `div` 8)
checkBitsSizeMod8 a w = do
emitDiagnosticWarning
(printf "Register size %d is not a multiple of 8. Please add padding to this register." w)
a
return ((w `div` 8) + 1)
checkEnumConsistency :: Expression S F A -> EnumBody S F A -> M ()
checkEnumConsistency expr enumBody@(EnumBody {enumConsts = constants}) = do
declaredSize <- expressionToIntM expr
-- If the declared size is less than or equal to 4, we'll enforce that the
-- enum is packed. This is to make sure the user has covered all bases.
when (declaredSize <= (4 :: Word32)) $ do
imap <-
foldlM
( \imap (undirected -> enumConst) -> do
number <- case enumConst of
EnumConstantDecl _ expr _ -> expressionToIntM expr
EnumConstantReserved expr _ -> expressionToIntM expr
when (number >= (2 :: Word32) ^ declaredSize) $
emitDiagnosticError
( printf
"Enum constant too large. Max allowed %d\n"
((2 :: Int) ^ declaredSize)
)
(annot enumConst)
return $ IntMap.insert (fromIntegral number) True imap
)
IntMap.empty
constants
let missing =
filter (not . (`IntMap.member` imap)) [0 .. 2 ^ declaredSize - 1]
unless (null missing) $
emitDiagnosticWarning
( printf
"Missing enum constants %s. Small enums should be fully \
\ populated. Use 'reserved' if needed."
(intercalate ", " (map show missing))
)
(annot enumBody)
|