-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathBinds.hs
More file actions
463 lines (368 loc) · 15.9 KB
/
Binds.hs
File metadata and controls
463 lines (368 loc) · 15.9 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
{-# Language BlockArguments #-}
{-# Language RecordWildCards #-}
{-# Language FlexibleInstances #-}
{-# LANGUAGE DeriveTraversable #-}
module Cryptol.ModuleSystem.Binds
( BindsNames
, TopDef(..)
, Mod(..)
, ModKind(..)
, modNested
, modBuilder
, topModuleDefs
, topDeclsDefs
, newModParam
, newFunctorInst
, InModule(..)
, ifaceToMod
, ifaceSigToMod
, modToMap
, defsOf
) where
import Data.Map(Map)
import qualified Data.Map as Map
import Data.Set(Set)
import qualified Data.Set as Set
import Data.Maybe(fromMaybe)
import Control.Monad(foldM,forM)
import qualified MonadLib as M
import Cryptol.Utils.Panic (panic)
import Cryptol.Utils.Ident(allNamespaces)
import Cryptol.Parser.Position
import Cryptol.Parser.Name(isGeneratedName)
import Cryptol.Parser.AST
import Cryptol.ModuleSystem.Exports(exportedDecls,exported)
import Cryptol.ModuleSystem.Renamer.Error
import Cryptol.ModuleSystem.Name
import Cryptol.ModuleSystem.Names
import Cryptol.ModuleSystem.NamingEnv
import Cryptol.ModuleSystem.Interface
import Cryptol.TypeCheck.Type(ModParamNames(..))
data TopDef = TopMod ModName (Mod ())
| TopInst ModName (ImpName PName) (ModuleInstanceArgs PName)
-- | Things defined by a module
data Mod a = Mod
{ modImports :: [ ImportG (ImpName PName) ]
, modKind :: ModKind
, modInstances :: Map Name (ImpName PName, ModuleInstanceArgs PName)
, modMods :: Map Name (Mod a) -- ^ this includes signatures
, modDefines :: NamingEnv
{- ^ Things defined by this module. Note the for normal modules we
really just need the public names, however for things within
functors we need all defined names, so that we can generate fresh
names in instantiations -}
, modPublic :: !(Set Name)
-- ^ These are the exported names
, modState :: a
{- ^ Used in the import loop to track the current state of processing.
The reason this is here, rather than just having a pair in the
other algorithm is because this type is recursive (for nested modules)
and it is conveninet to keep track for all modules at once -}
}
modNested :: Mod a -> Set Name
modNested m = Set.unions [ Map.keysSet (modInstances m)
, Map.keysSet (modMods m)
]
instance Functor Mod where
fmap f m = m { modState = f (modState m)
, modMods = fmap f <$> modMods m
}
-- | Generate a map from this module and all modules nested in it.
modToMap ::
ImpName Name -> Mod () ->
Map (ImpName Name) (Mod ()) -> Map (ImpName Name) (Mod ())
modToMap x m mp = Map.insert x m (Map.foldrWithKey add mp (modMods m))
where
add n = modToMap (ImpNested n)
-- | Make a `Mod` from the public declarations in an interface.
-- This is used to handle imports.
ifaceToMod :: IfaceG name -> Mod ()
ifaceToMod iface = ifaceNamesToMod iface (ifaceIsFunctor iface) (ifNames iface)
ifaceNamesToMod :: IfaceG topname -> Bool -> IfaceNames name -> Mod ()
ifaceNamesToMod iface params names =
Mod
{ modKind = if params then AFunctor else AModule
, modMods = (ifaceNamesToMod iface False <$> ifModules decls)
`Map.union`
(ifaceToMod <$> ifFunctors decls)
`Map.union`
(ifaceSigToMod <$> ifSignatures decls)
, modDefines = namingEnvFromNames defs
, modPublic = ifsPublic names
, modImports = []
, modInstances = mempty
, modState = ()
}
where
defs = ifsDefines names
isLocal x = x `Set.member` defs
decls = filterIfaceDecls isLocal (ifDefines iface)
ifaceSigToMod :: ModParamNames -> Mod ()
ifaceSigToMod ps = Mod
{ modImports = []
, modKind = ASignature
, modInstances = mempty
, modMods = mempty
, modDefines = env
, modPublic = namingEnvNames env
, modState = ()
}
where
env = modParamNamesNamingEnv ps
type ModBuilder = SupplyT (M.StateT [RenamerError] M.Id)
modBuilder :: ModBuilder a -> Supply -> ((a, [RenamerError]),Supply)
modBuilder m s = ((a,errs),s1)
where ((a,s1),errs) = M.runId (M.runStateT [] (runSupplyT s m))
defErr :: RenamerError -> ModBuilder ()
defErr a = M.lift (M.sets_ (a:))
defNames :: BuildNamingEnv -> ModBuilder NamingEnv
defNames b = liftSupply \s -> M.runId (runSupplyT s (runBuild b))
topModuleDefs :: Module PName -> ModBuilder TopDef
topModuleDefs m =
case mDef m of
NormalModule ds -> TopMod mname <$> declsToMod (Just (TopModule mname)) ds
FunctorInstance f as _ -> pure (TopInst mname (thing f) as)
InterfaceModule s -> TopMod mname <$> sigToMod (TopModule mname) s
where
mname = thing (mName m)
topDeclsDefs :: ModPath -> [TopDecl PName] -> ModBuilder (Mod ())
topDeclsDefs = declsToMod . Just
sigToMod :: ModPath -> Signature PName -> ModBuilder (Mod ())
sigToMod mp sig =
do env <- defNames (signatureDefs mp sig)
pure Mod { modImports = map thing (sigImports sig)
, modKind = ASignature
, modInstances = mempty
, modMods = mempty
, modDefines = env
, modPublic = namingEnvNames env
, modState = ()
}
declsToMod :: Maybe ModPath -> [TopDecl PName] -> ModBuilder (Mod ())
declsToMod mbPath ds =
do defs <- defNames (foldMap (namingEnv . InModule mbPath) ds)
let expSpec = exportedDecls ds
let pub = Set.fromList
[ name
| ns <- allNamespaces
, pname <- Set.toList (exported ns expSpec)
, name <- lookupListNS ns pname defs
]
case findAmbig defs of
bad@(_ : _) : _ ->
-- defErr (MultipleDefinitions mbPath (nameIdent f) (map nameLoc bad))
defErr (OverlappingSyms bad)
_ -> pure ()
let mo = Mod { modImports = [ thing i | DImport i <- ds ]
, modKind = if any isParamDecl ds
then AFunctor else AModule
, modInstances = mempty
, modMods = mempty
, modDefines = defs
, modPublic = pub
, modState = ()
}
foldM (checkNest defs) mo ds
where
checkNest defs mo d =
case d of
DModule tl ->
do let NestedModule nmod = tlValue tl
pname = thing (mName nmod)
name = case lookupNS NSModule pname defs of
Just xs -> anyOne xs
_ -> panic "declsToMod" ["undefined name", show pname]
case mbPath of
Nothing ->
do defErr (UnexpectedNest (srcRange (mName nmod)) pname)
pure mo
Just path ->
case mDef nmod of
NormalModule xs ->
do m <- declsToMod (Just (Nested path (nameIdent name))) xs
pure mo { modMods = Map.insert name m (modMods mo) }
FunctorInstance f args _ ->
pure mo { modInstances = Map.insert name (thing f, args)
(modInstances mo) }
InterfaceModule sig ->
do m <- sigToMod (Nested path (nameIdent name)) sig
pure mo { modMods = Map.insert name m (modMods mo) }
_ -> pure mo
-- | These are the names "owned" by the signature. These names are
-- used when resolving the signature. They are also used to figure out what
-- names to instantuate when the signature is used.
signatureDefs :: ModPath -> Signature PName -> BuildNamingEnv
signatureDefs m sig =
mconcat [ namingEnv (InModule loc p) | p <- sigTypeParams sig ]
<> mconcat [ namingEnv (InModule loc p) | p <- sigFunParams sig ]
<> mconcat [ namingEnv (InModule loc p) | p <- sigDecls sig ]
where
loc = Just m
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Computes the names introduced by various declarations.
-- | Things that define exported names.
class BindsNames a where
namingEnv :: a -> BuildNamingEnv
newtype BuildNamingEnv = BuildNamingEnv { runBuild :: SupplyT M.Id NamingEnv }
buildNamingEnv :: BuildNamingEnv -> Supply -> (NamingEnv,Supply)
buildNamingEnv b supply = M.runId $ runSupplyT supply $ runBuild b
-- | Generate a 'NamingEnv' using an explicit supply.
defsOf :: BindsNames a => a -> Supply -> (NamingEnv,Supply)
defsOf = buildNamingEnv . namingEnv
instance Semigroup BuildNamingEnv where
BuildNamingEnv a <> BuildNamingEnv b = BuildNamingEnv $
do x <- a
y <- b
return (mappend x y)
instance Monoid BuildNamingEnv where
mempty = BuildNamingEnv (pure mempty)
mappend = (<>)
mconcat bs = BuildNamingEnv $
do ns <- sequence (map runBuild bs)
return (mconcat ns)
instance BindsNames NamingEnv where
namingEnv env = BuildNamingEnv (return env)
{-# INLINE namingEnv #-}
instance BindsNames a => BindsNames (Maybe a) where
namingEnv = foldMap namingEnv
{-# INLINE namingEnv #-}
instance BindsNames a => BindsNames [a] where
namingEnv = foldMap namingEnv
{-# INLINE namingEnv #-}
-- | Generate a type renaming environment from the parameters that are bound by
-- this schema.
instance BindsNames (Schema PName) where
namingEnv (Forall ps _ _ _) = foldMap namingEnv ps
{-# INLINE namingEnv #-}
-- | Introduce the name
instance BindsNames (InModule (Bind PName)) where
namingEnv (InModule mb b) = BuildNamingEnv $
do let Located { .. } = bName b
n <- case mb of
Just m -> newTop NSValue m thing (bFixity b) srcRange
Nothing -> newLocal NSValue thing srcRange -- local fixitiies?
return (singletonNS NSValue thing n)
-- | Generate the naming environment for a type parameter.
instance BindsNames (TParam PName) where
namingEnv TParam { .. } = BuildNamingEnv $
do let range = fromMaybe emptyRange tpRange
n <- newLocal NSType tpName range
return (singletonNS NSType tpName n)
instance BindsNames (InModule (TopDecl PName)) where
namingEnv (InModule ns td) =
case td of
Decl d -> namingEnv (InModule ns (tlValue d))
DPrimType d -> namingEnv (InModule ns (tlValue d))
TDNewtype d -> namingEnv (InModule ns (tlValue d))
TDEnum d -> namingEnv (InModule ns (tlValue d))
DParamDecl {} -> mempty
Include _ -> mempty
DImport {} -> mempty -- see 'openLoop' in the renamer
DModule m -> namingEnv (InModule ns (tlValue m))
DModParam {} -> mempty -- shouldn't happen
DInterfaceConstraint {} -> mempty
-- handled in the renamer as we need to resolve
-- the signature name first (similar to import)
instance BindsNames (InModule (NestedModule PName)) where
namingEnv (InModule ~(Just m) (NestedModule mdef)) = BuildNamingEnv $
do let pnmame = mName mdef
nm <- newTop NSModule m (thing pnmame) Nothing (srcRange pnmame)
pure (singletonNS NSModule (thing pnmame) nm)
instance BindsNames (InModule (PrimType PName)) where
namingEnv (InModule ~(Just m) PrimType { .. }) =
BuildNamingEnv $
do let Located { .. } = primTName
nm <- newTop NSType m thing primTFixity srcRange
pure (singletonNS NSType thing nm)
instance BindsNames (InModule (ParameterFun PName)) where
namingEnv (InModule ~(Just ns) ParameterFun { .. }) = BuildNamingEnv $
do let Located { .. } = pfName
ntName <- newTop NSValue ns thing pfFixity srcRange
return (singletonNS NSValue thing ntName)
instance BindsNames (InModule (ParameterType PName)) where
namingEnv (InModule ~(Just ns) ParameterType { .. }) = BuildNamingEnv $
-- XXX: we don't seem to have a fixity environment at the type level
do let Located { .. } = ptName
ntName <- newTop NSType ns thing Nothing srcRange
return (singletonNS NSType thing ntName)
instance BindsNames (InModule (Newtype PName)) where
namingEnv (InModule ~(Just ns) Newtype { .. }) = BuildNamingEnv $
do let Located { .. } = nName
ntName <- newTop NSType ns thing Nothing srcRange
ntConName <- newTop NSConstructor ns thing Nothing srcRange
return (singletonNS NSType thing ntName `mappend`
singletonNS NSConstructor thing ntConName)
instance BindsNames (InModule (EnumDecl PName)) where
namingEnv (InModule (Just ns) EnumDecl { .. }) = BuildNamingEnv $
do enName <- newTop NSType ns (thing eName) Nothing (srcRange eName)
conNames <- forM eCons \topc ->
do let c = ecName (tlValue topc)
pname = thing c
cName <- newTop NSConstructor ns pname Nothing
(srcRange c)
pure (singletonNS NSConstructor pname cName)
pure (mconcat (singletonNS NSType (thing eName) enName : conNames))
namingEnv _ = panic "namingEnv" ["Unreachable"]
-- | The naming environment for a single declaration.
instance BindsNames (InModule (Decl PName)) where
namingEnv (InModule pfx d) = case d of
DBind b -> namingEnv (InModule pfx b)
DSignature ns _sig -> foldMap qualBind ns
DPragma ns _p -> foldMap qualBind ns
DType syn -> qualType (tsName syn) (tsFixity syn)
DProp syn -> qualType (psName syn) (psFixity syn)
DLocated d' _ -> namingEnv (InModule pfx d')
DRec {} -> panic "namingEnv" [ "DRec" ]
DPatBind _pat _e -> panic "namingEnv" ["Unexpected pattern binding"]
DFixity{} -> panic "namingEnv" ["Unexpected fixity declaration"]
where
mkName ns ln fx = case pfx of
Just m -> newTop ns m (thing ln) fx (srcRange ln)
Nothing -> newLocal ns (thing ln) (srcRange ln)
qualBind ln = BuildNamingEnv $
do n <- mkName NSValue ln Nothing
return (singletonNS NSValue (thing ln) n)
qualType ln f = BuildNamingEnv $
do n <- mkName NSType ln f
return (singletonNS NSType (thing ln) n)
instance BindsNames (InModule (SigDecl PName)) where
namingEnv (InModule m d) =
case d of
SigTySyn ts _ -> namingEnv (InModule m (DType ts))
SigPropSyn ps _ -> namingEnv (InModule m (DProp ps))
instance BindsNames (Pattern PName) where
namingEnv pat =
case pat of
PVar x -> BuildNamingEnv (
do y <- newLocal NSValue (thing x) (srcRange x)
pure (singletonNS NSValue (thing x) y)
)
PCon _ xs -> mconcat (map namingEnv xs)
_ -> panic "namingEnv" ["Unexpected pattern"]
--------------------------------------------------------------------------------
-- Helpers
newTop ::
FreshM m => Namespace -> ModPath -> PName -> Maybe Fixity -> Range -> m Name
newTop ns m thing fx rng =
liftSupply (mkDeclared ns m src (getIdent thing) fx rng)
where src = if isGeneratedName thing then SystemName else UserName
newLocal :: FreshM m => Namespace -> PName -> Range -> m Name
newLocal ns thing rng = liftSupply (mkLocal ns (getIdent thing) rng)
-- | Given a name in a signature, make a name for the parameter corresponding
-- to the signature.
newModParam :: FreshM m => ModPath -> Ident -> Range -> Name -> m Name
newModParam m i rng n = liftSupply (mkModParam m i rng n)
-- | Given a name in a functor, make a fresh name for the corresponding thing in
-- the instantiation.
--
-- The 'ModPath' should be the instantiation not the functor.
newFunctorInst :: FreshM m => ModPath -> Name -> m Name
newFunctorInst m n = liftSupply (freshNameFor m n)
{- | Do something in the context of a module.
If `Nothing` than we are working with a local declaration.
Otherwise we are at the top-level of the given module.
By wrapping types with this, we can pass the module path
to methods that need the extra information. -}
data InModule a = InModule (Maybe ModPath) a
deriving (Functor,Traversable,Foldable,Show)