-
Notifications
You must be signed in to change notification settings - Fork 123
/
Renamer.hs
1458 lines (1200 loc) · 51.3 KB
/
Renamer.hs
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- |
-- Module : Cryptol.ModuleSystem.Renamer
-- Copyright : (c) 2013-2016 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
{-# Language RecordWildCards #-}
{-# Language FlexibleInstances #-}
{-# Language FlexibleContexts #-}
{-# Language BlockArguments #-}
{-# Language OverloadedStrings #-}
module Cryptol.ModuleSystem.Renamer (
NamingEnv(), shadowing
, BindsNames, InModule(..)
, shadowNames
, Rename(..), runRenamer, RenameM()
, RenamerError(..)
, RenamerWarning(..)
, renameVar
, renameType
, renameModule
, renameTopDecls
, RenamerInfo(..)
, NameType(..)
, RenamedModule(..)
) where
import Prelude ()
import Prelude.Compat
import Data.Either(partitionEithers)
import Data.Maybe(mapMaybe)
import Data.List(find,groupBy,sortBy)
import Data.Function(on)
import Data.Foldable(toList)
import Data.Map(Map)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.Graph(SCC(..))
import Data.Graph.SCC(stronglyConnComp)
import MonadLib hiding (mapM, mapM_)
import Cryptol.ModuleSystem.Name
import Cryptol.ModuleSystem.Names
import Cryptol.ModuleSystem.NamingEnv
import Cryptol.ModuleSystem.Exports
import Cryptol.Parser.Position(Range)
import Cryptol.Parser.AST
import Cryptol.Parser.Selector(selName)
import Cryptol.Utils.Panic (panic)
import Cryptol.Utils.RecordMap
import Cryptol.Utils.Ident(allNamespaces,OrigName(..),modPathCommon,
undefinedModName)
import Cryptol.Utils.PP
import Cryptol.ModuleSystem.Interface
import Cryptol.ModuleSystem.Renamer.Error
import Cryptol.ModuleSystem.Binds
import Cryptol.ModuleSystem.Renamer.Monad
import Cryptol.ModuleSystem.Renamer.Imports
import Cryptol.ModuleSystem.Renamer.ImplicitImports
{-
The Renamer Algorithm
=====================
1. Add implicit imports for visible nested modules
2. Compute what each module defines (see "Cryptol.ModuleSystem.Binds")
- This assigns unique names to names introduces by various declarations
- Here we detect repeated top-level definitions in a module.
- Module instantiations also get a name, but are not yet resolved, so
we don't know what's defined by them.
- We do not generate unique names for functor parameters---those will
be matched textually to the arguments when applied.
- We *do* generate unique names for declarations in "signatures"
* those are only really needed when renaming the signature (step 4)
(e.g., to determine if a name refers to something declared in the
signature or something else).
* when validating a module against a signature the names of the declarations
are matched textually, *not* using the unique names
(e.g., `x` in a signature is matched with the thing named `x` in a module,
even though these two `x`s will have different unique `id`s)
3. Resolve imports and instantiations (see "Cryptol.ModuleSystem.Imports")
- Resolves names in submodule imports
- Resolves functor instantiations:
* generate new names for declarations in the functors.
* this includes any nested modules, and things nested within them.
- At this point we have enough information to know what's exported by
each module.
4. Do the renaming (this module)
- Using step 3 we compute the scoping environment for each module/signature
- We traverse all declarations and replace the parser names with the
corresponding names in scope:
* Here we detect ambiguity and undefined errors
* During this pass is also where we keep track of information of what
names are used by declarations:
- this is used to compute the dependencies between declarations
- which are in turn used to order the declarations in dependency order
* this is assumed by the TC
* here we also report errors about invalid recursive dependencies
* During this stage we also issue warning about unused type names
(and we should probably do unused value names too one day)
- During the rewriting we also do:
- rebalance expression trees using the operator fixities
- desugar record update notation
-}
-- | The result of renaming a module
data RenamedModule = RenamedModule
{ rmModule :: Module Name -- ^ The renamed module
, rmDefines :: NamingEnv -- ^ What this module defines
, rmImported :: IfaceDecls
-- ^ Imported declarations. This provides the types for external
-- names (used by the type-checker).
}
-- | Entry point. This is used for renaming a top-level module.
renameModule :: Module PName -> RenameM RenamedModule
renameModule m0 =
do -- Step 1: add implicit imports
let m = m0 { mDef =
case mDef m0 of
NormalModule ds ->
NormalModule (addImplicitNestedImports ds)
FunctorInstance f as i -> FunctorInstance f as i
InterfaceModule s -> InterfaceModule s
}
-- Step 2: compute what's defined
(defs,errs) <- liftSupply (modBuilder (topModuleDefs m))
mapM_ recordError errs
-- Step 3: resolve imports
extern <- getExternal
resolvedMods <- liftSupply (resolveImports extern defs)
let pathToName = Map.fromList [ (Nested (nameModPath x) (nameIdent x), x)
| ImpNested x <- Map.keys resolvedMods ]
let mname = ImpTop (thing (mName m))
setResolvedLocals resolvedMods $
setNestedModule pathToName
do (ifs,m1) <- collectIfaceDeps (renameModule' mname m)
env <- rmodDefines <$> lookupResolved mname
pure RenamedModule
{ rmModule = m1
, rmDefines = env
, rmImported = ifs
-- XXX: maybe we should keep the nested defines too?
}
{- | Entry point. Rename a list of top-level declarations.
This is used for declaration that don't live in a module
(e.g., define on the command line.)
We assume that these declarations do not contain any nested modules.
-}
renameTopDecls ::
ModName -> [TopDecl PName] -> RenameM (NamingEnv,[TopDecl Name])
renameTopDecls m ds0 =
do -- Step 1: add implicit imports
let ds = addImplicitNestedImports ds0
-- Step 2: compute what's defined
(defs,errs) <- liftSupply (modBuilder (topDeclsDefs (TopModule m) ds))
mapM_ recordError errs
-- Step 3: resolve imports
extern <- getExternal
resolvedMods <- liftSupply (resolveImports extern (TopMod m defs))
let pathToName = Map.fromList [ (Nested (nameModPath x) (nameIdent x), x)
| ImpNested x <- Map.keys resolvedMods ]
setResolvedLocals resolvedMods $
setNestedModule pathToName
do env <- rmodDefines <$> lookupResolved (ImpTop m)
-- we already checked for duplicates in Step 2
ds1 <- shadowNames' CheckNone env (renameTopDecls' ds)
-- record a use of top-level names to avoid
-- unused name warnings
let exports = exportedDecls ds1
mapM_ recordUse (exported NSType exports)
pure (env,ds1)
--------------------------------------------------------------------------------
-- Stuff below is related to Step 4 of the algorithm.
class Rename f where
rename :: f PName -> RenameM (f Name)
-- | This is used for both top-level and nested modules.
-- Returns:
--
-- * Things defined in the module
-- * Renamed module
renameModule' ::
ImpName Name {- ^ Resolved name for this module -} ->
ModuleG mname PName ->
RenameM (ModuleG mname Name)
renameModule' mname m =
setCurMod (impNameModPath mname)
do resolved <- lookupResolved mname
shadowNames' CheckNone (rmodImports resolved)
case mDef m of
NormalModule ds ->
do let env = rmodDefines resolved
(paramEnv,params) <-
shadowNames' CheckNone env
(doModParams (mModParams m))
-- we check that defined names and ones that came
-- from parameters do not clash, as this would be
-- very confusing.
shadowNames' CheckOverlap (env <> paramEnv) $
setModParams params
do ds1 <- renameTopDecls' ds
let exports = exportedDecls ds1
mapM_ recordUse (exported NSType exports)
inScope <- getNamingEnv
pure m { mDef = NormalModule ds1, mInScope = inScope }
-- The things defined by this module are the *results*
-- of the instantiation, so we should *not* add them
-- in scope when resolving.
FunctorInstance f as _ ->
do f' <- rnLocated rename f
as' <- rename as
checkFunctorArgs as'
let l = Just (srcRange f')
imap <- mkInstMap l mempty (thing f') mname
-- This inScope is incomplete; it only contains names from the
-- enclosing scope, but we also want the names in scope from the
-- functor, for ease of testing at the command line. We will fix
-- this up in doFunctorInst in the typechecker, because right now
-- we don't have access yet to the inScope of the functor.
inScope <- getNamingEnv
pure m { mDef = FunctorInstance f' as' imap, mInScope = inScope }
InterfaceModule s ->
shadowNames' CheckNone (rmodDefines resolved)
do d <- InterfaceModule <$> renameIfaceModule mname s
inScope <- getNamingEnv
pure m { mDef = d, mInScope = inScope }
checkFunctorArgs :: ModuleInstanceArgs Name -> RenameM ()
checkFunctorArgs args =
case args of
DefaultInstAnonArg {} ->
panic "checkFunctorArgs" ["Nested DefaultInstAnonArg"]
DefaultInstArg l -> checkArg l
NamedInstArgs as -> mapM_ checkNamedArg as
where
checkNamedArg (ModuleInstanceNamedArg _ l) = checkArg l
checkArg l =
case thing l of
ModuleArg m
| isFakeName m -> pure ()
| otherwise -> checkIsModule (srcRange l) m AModule
ParameterArg {} -> pure () -- we check these in the type checker
AddParams -> pure ()
mkInstMap :: Maybe Range -> Map Name Name -> ImpName Name -> ImpName Name ->
RenameM (Map Name Name)
mkInstMap checkFun acc0 ogname iname
| isFakeName ogname = pure Map.empty
| otherwise =
do case checkFun of
Nothing -> pure ()
Just r -> checkIsModule r ogname AFunctor
(onames,osubs) <- lookupDefinesAndSubs ogname
inames <- lookupDefines iname
let mp = zipByTextName onames inames
subs = [ (ImpNested k, ImpNested v)
| k <- Set.toList osubs, Just v <- [Map.lookup k mp]
]
foldM doSub (Map.union mp acc0) subs
where
doSub acc (k,v) = mkInstMap Nothing acc k v
-- | This is used to rename local declarations (e.g. `where`)
renameDecls :: [Decl PName] -> RenameM [Decl Name]
renameDecls ds =
do (ds1,deps) <- depGroup (traverse rename ds)
let toNode d = let x = NamedThing (declName d)
in ((d,x), x, map NamedThing
$ Set.toList
$ Map.findWithDefault Set.empty x deps)
ordered = toList (stronglyConnComp (map toNode ds1))
fromSCC x =
case x of
AcyclicSCC (d,_) -> pure [d]
CyclicSCC ds_xs ->
let (rds,xs) = unzip ds_xs
in case mapM validRecursiveD rds of
Nothing -> do recordError (InvalidDependency xs)
pure rds
Just bs ->
do checkSameModule xs
pure [DRec bs]
concat <$> mapM fromSCC ordered
-- | Rename declarations in a signature (i.e., type/prop synonyms)
renameSigDecls :: [SigDecl PName] -> RenameM [SigDecl Name]
renameSigDecls ds =
do (ds1,deps) <- depGroup (traverse rename ds)
let toNode d = let nm = case d of
SigTySyn ts _ -> thing (tsName ts)
SigPropSyn ps _ -> thing (psName ps)
x = NamedThing nm
in ((d,x), x, map NamedThing
$ Set.toList
$ Map.findWithDefault Set.empty x deps)
ordered = toList (stronglyConnComp (map toNode ds1))
fromSCC x =
case x of
AcyclicSCC (d,_) -> pure [d]
CyclicSCC ds_xs ->
do let (rds,xs) = unzip ds_xs
recordError (InvalidDependency xs)
pure rds
concat <$> mapM fromSCC ordered
validRecursiveD :: Decl name -> Maybe (Bind name)
validRecursiveD d =
case d of
DBind b -> Just b
DLocated d' _ -> validRecursiveD d'
_ -> Nothing
checkSameModule :: [DepName] -> RenameM ()
checkSameModule xs =
case ms of
a : as | let bad = [ fst b | b <- as, snd a /= snd b ]
, not (null bad) ->
recordError (InvalidDependency $ map NamedThing $ fst a : bad)
_ -> pure ()
where
ms = [ (x,ogModule og)
| NamedThing x <- xs, GlobalName _ og <- [ nameInfo x ]
]
{- NOTE: Dependencies on Top Level Constraints
===========================================
For the new module system, things using a parameter depend on the parameter
declaration (i.e., `import signature`), which depends on the signature,
so dependencies on constraints in there should be OK.
However, we'd like to have a mechanism for declaring top level constraints in
a functor, that can impose constraints across types from *different*
parameters. For the moment, we reuse `parameter type constraint C` for this.
Such constraints need to be:
1. After the signature import
2. After any type synonyms/newtypes using the parameters
3. Before any value or type declarations that need to use the parameters.
Note that type declarations used by a constraint cannot use the constraint,
so they need to be well formed without it.
For other types, we use the following rule to determine if they use a
constraint:
If:
1. We have a constraint and type declaration
2. They both mention the same type parameter
3. There is no explicit dependency of the constraint on the DECL
Then:
The type declaration depends on the constraint.
Example:
type T = 10 // Does not depend on anything so can go first
signature A where
type n : #
import signature A // Depends on A, so need to be after A
parameter type constraint n > T
// Depends on the import (for @n@) and T
type Q = [n-T] // Depends on the top-level constraint
-}
-- This assumes imports have already been processed
renameTopDecls' :: [TopDecl PName] -> RenameM [TopDecl Name]
renameTopDecls' ds =
do -- rename and compute what names we depend on
(ds1,deps) <- depGroup (traverse rename ds)
fromParams <- getNamesFromModParams
localParams <- getLocalModParamDeps
let rawDepsFor x = Map.findWithDefault Set.empty x deps
isTyParam x = nameNamespace x == NSType && x `Map.member` fromParams
(noNameDs,nameDs) = partitionEithers (map topDeclName ds1)
ctrs = [ nm | (_,nm@(ConstratintAt {}),_) <- nameDs ]
indirect = Map.fromList [ (y,x)
| (_,x,ys) <- nameDs, y <- ys ]
mkDepName x = case Map.lookup x fromParams of
Just dn -> dn
Nothing -> NamedThing x
depsFor x =
[ Map.findWithDefault (mkDepName y) (NamedThing y) indirect
| y <- Set.toList (Map.findWithDefault Set.empty x deps)
]
{- See [NOTE: Dependencies on Top Level Constraints] -}
addCtr nm ctr =
case nm of
NamedThing x
| nameNamespace x == NSType
, let ctrDeps = rawDepsFor ctr
tyDeps = rawDepsFor nm
, not (x `Set.member` ctrDeps)
, not (Set.null (Set.intersection
(Set.filter isTyParam ctrDeps)
(Set.filter isTyParam tyDeps)))
-> Just ctr
_ -> Nothing
addCtrs (d,x)
| usesCtrs d = ctrs
| otherwise = mapMaybe (addCtr x) ctrs
addModParams d =
case d of
DModule tl | NestedModule m <- tlValue tl
, FunctorInstance _ as _ <- mDef m ->
case as of
DefaultInstArg arg -> depsOfArg arg
NamedInstArgs args -> concatMap depsOfNamedArg args
DefaultInstAnonArg {} -> []
where depsOfNamedArg (ModuleInstanceNamedArg _ a) = depsOfArg a
depsOfArg a = case thing a of
AddParams -> []
ModuleArg {} -> []
ParameterArg p ->
case Map.lookup p localParams of
Just i -> [i]
Nothing -> []
_ -> []
toNode (d,x,_) = ((d,x),x, addCtrs (d,x) ++
addModParams d ++
depsFor x)
ordered = stronglyConnComp (map toNode nameDs)
fromSCC x =
case x of
AcyclicSCC (d,_) -> pure [d]
CyclicSCC ds_xs ->
let (rds,xs) = unzip ds_xs
in case mapM valid rds of
Nothing -> do recordError (InvalidDependency xs)
pure rds
Just bs ->
do checkSameModule xs
pure [Decl TopLevel
{ tlDoc = Nothing
, tlExport = Public
, tlValue = DRec bs
}]
where
valid d = case d of
Decl tl -> validRecursiveD (tlValue tl)
_ -> Nothing
rds <- mapM fromSCC ordered
pure (concat (noNameDs:rds))
where
-- This indicates if a declaration might depend on the constraints in scope.
-- Since uses of constraints are not implicitly named, value declarations
-- are assumed to potentially use the constraints.
-- XXX: This is inaccurate, and *I think* it amounts to checking that something
-- is in the value namespace. Perhaps the rule should be that a value
-- depends on a parameter constraint if it mentions at least one
-- type parameter somewhere.
-- XXX: Besides, types might need constraints for well-formedness...
-- This is just bogus
-- Although not that type/prop synonyms may be defined wherever as they
-- keep the validity constraints they need and emit them at the *use* sites.
usesCtrs td =
case td of
Decl tl -> isValDecl (tlValue tl)
DPrimType {} -> False
TDNewtype {} -> False
TDEnum {} -> False
DParamDecl {} -> False
DInterfaceConstraint {} -> False
DModule tl -> any usesCtrs (mDecls m)
where NestedModule m = tlValue tl
DImport {} -> False
DModParam {} -> False -- no definitions here
Include {} -> bad "Include"
isValDecl d =
case d of
DLocated d' _ -> isValDecl d'
DBind {} -> True
DRec {} -> True
DType {} -> False
DProp {} -> False
DSignature {} -> bad "DSignature"
DFixity {} -> bad "DFixity"
DPragma {} -> bad "DPragma"
DPatBind {} -> bad "DPatBind"
bad msg = panic "renameTopDecls'" [msg]
declName :: Decl Name -> Name
declName decl =
case decl of
DLocated d _ -> declName d
DBind b -> thing (bName b)
DType (TySyn x _ _ _) -> thing x
DProp (PropSyn x _ _ _) -> thing x
DSignature {} -> bad "DSignature"
DFixity {} -> bad "DFixity"
DPragma {} -> bad "DPragma"
DPatBind {} -> bad "DPatBind"
DRec {} -> bad "DRec"
where
bad x = panic "declName" [x]
topDeclName ::
TopDecl Name ->
Either (TopDecl Name) (TopDecl Name, DepName, [DepName])
topDeclName topDecl =
case topDecl of
Decl d -> hasName (declName (tlValue d))
DPrimType d -> hasName (thing (primTName (tlValue d)))
TDNewtype d -> hasName' (thing (nName (tlValue d)))
[ nConName (tlValue d) ]
TDEnum d -> hasName' (thing (eName (tlValue d)))
(map (thing . ecName . tlValue)
(eCons (tlValue d)))
DModule d -> hasName (thing (mName m))
where NestedModule m = tlValue d
DInterfaceConstraint _ ds -> special (ConstratintAt (srcRange ds))
DImport {} -> noName
DModParam m -> special (ModParamName (srcRange (mpSignature m))
(mpName m))
Include {} -> bad "Include"
DParamDecl {} -> bad "DParamDecl"
where
noName = Left topDecl
hasName n = hasName' n []
hasName' n ms = Right (topDecl, NamedThing n, map NamedThing ms)
special x = Right (topDecl, x, [])
bad x = panic "topDeclName" [x]
{- | Compute the names introduced by a module parameter.
This should be run in a context containing everything that's in scope
except for the module parameters. We don't need to compute a fixed point here
because the signatures (and hence module parameters) cannot contain signatures.
The resulting naming environment contains the new names introduced by this
parameter.
-}
doModParam ::
ModParam PName ->
RenameM (NamingEnv, RenModParam)
doModParam mp =
do let sigName = mpSignature mp
loc = srcRange sigName
withLoc loc
do me <- getCurMod
(sigName',isFake) <-
case thing sigName of
ImpTop t -> pure (ImpTop t, False)
-- XXX: should we record a dependency here?
-- Not sure what the dependencies are for..
ImpNested n ->
do mb <- resolveNameMaybe NameUse NSModule n
(nm,isFake) <- case mb of
Just rnm -> pure (rnm,False)
Nothing ->
do rnm <- reportUnboundName NSModule n
pure (rnm,True)
case modPathCommon me (nameModPath nm) of
Just (_,[],_) ->
recordError
(InvalidDependency [ModPath me, NamedThing nm])
_ -> pure ()
pure (ImpNested nm, isFake)
unless isFake
(checkIsModule (srcRange sigName) sigName' ASignature)
sigEnv <- if isFake then pure mempty else lookupDefines sigName'
{- XXX: It seems a bit odd to use "newModParam" for the names to
be used for the instantiated type synonyms,
but what other name could we use? -}
let newP x = do y <- lift (newModParam me (mpName mp) loc x)
sets_ (Map.insert y x)
pure y
(newEnv',nameMap) <- runStateT Map.empty (travNamingEnv newP sigEnv)
let paramName = mpAs mp
let newEnv = case paramName of
Nothing -> newEnv'
Just q -> qualify q newEnv'
pure ( newEnv
, RenModParam
{ renModParamName = mpName mp
, renModParamRange = loc
, renModParamSig = sigName'
, renModParamInstance = nameMap
}
)
{- | Process the parameters of a module.
Should be executed in a context where everything's already in the context,
except the module parameters.
-}
doModParams :: [ModParam PName] -> RenameM (NamingEnv, [RenModParam])
doModParams srcParams =
do (paramEnvs,params) <- unzip <$> mapM doModParam srcParams
let repeated = groupBy ((==) `on` renModParamName)
$ sortBy (compare `on` renModParamName) params
forM_ repeated \ps ->
case ps of
[] -> panic "doModParams" ["[]"]
[_] -> pure ()
(p : _) -> recordError (MultipleModParams (renModParamName p)
(map renModParamRange ps))
pure (mconcat paramEnvs,params)
--------------------------------------------------------------------------------
rnLocated :: (a -> RenameM b) -> Located a -> RenameM (Located b)
rnLocated f loc = withLoc loc $
do a' <- f (thing loc)
return loc { thing = a' }
instance Rename TopDecl where
rename td =
case td of
Decl d -> Decl <$> traverse rename d
DPrimType d -> DPrimType <$> traverse rename d
TDNewtype n -> TDNewtype <$> traverse rename n
TDEnum n -> TDEnum <$> traverse rename n
Include n -> return (Include n)
DModule m -> DModule <$> traverse rename m
DImport li -> DImport <$> renI li
DModParam mp -> DModParam <$> rename mp
DInterfaceConstraint d ds ->
depsOf (ConstratintAt (srcRange ds))
(DInterfaceConstraint d <$> rnLocated (mapM rename) ds)
DParamDecl {} -> panic "rename" ["DParamDecl"]
renI :: Located (ImportG (ImpName PName)) ->
RenameM (Located (ImportG (ImpName Name)))
renI li =
withLoc (srcRange li)
do m <- rename (iModule i)
unless (isFakeName m) (recordImport (srcRange li) m)
pure li { thing = i { iModule = m } }
where
i = thing li
instance Rename ModParam where
rename mp =
do x <- rnLocated rename (mpSignature mp)
depsOf (ModParamName (srcRange (mpSignature mp)) (mpName mp))
do ren <- renModParamInstance <$> getModParam (mpName mp)
{- Here we add 2 "uses" to all type-level names introduced,
so that we don't get unused warnings for type parameters.
-}
mapM_ recordUse [ s | t <- Map.keys ren, nameNamespace t == NSType
, s <- [t,t] ]
pure mp { mpSignature = x, mpRenaming = ren }
renameIfaceModule :: ImpName Name -> Signature PName -> RenameM (Signature Name)
renameIfaceModule nm sig =
do env <- rmodDefines <$> lookupResolved nm
let depName = case nm of
ImpNested n -> NamedThing n
ImpTop t -> ModPath (TopModule t)
shadowNames' CheckOverlap env $
depsOf depName
do imps <- traverse renI (sigImports sig)
tps <- traverse rename (sigTypeParams sig)
ds <- renameSigDecls (sigDecls sig)
cts <- traverse (rnLocated rename) (sigConstraints sig)
fun <- traverse rename (sigFunParams sig)
-- we record a use here to avoid getting a warning in interfaces
-- that declare only types, and so appear "unused".
forM_ tps \tp -> recordUse (thing (ptName tp))
forM_ ds \d -> recordUse $ case d of
SigTySyn ts _ -> thing (tsName ts)
SigPropSyn ps _ -> thing (psName ps)
pure Signature
{ sigImports = imps
, sigTypeParams = tps
, sigDecls = ds
, sigConstraints = cts
, sigFunParams = fun
}
instance Rename ImpName where
rename i =
case i of
ImpTop m -> pure (ImpTop m)
ImpNested m -> ImpNested <$> resolveName NameUse NSModule m
instance Rename ModuleInstanceArgs where
rename args =
case args of
DefaultInstArg a -> DefaultInstArg <$> rnLocated rename a
NamedInstArgs xs -> NamedInstArgs <$> traverse rename xs
DefaultInstAnonArg {} -> panic "rename" ["DefaultInstAnonArg"]
instance Rename ModuleInstanceNamedArg where
rename (ModuleInstanceNamedArg x m) =
ModuleInstanceNamedArg x <$> rnLocated rename m
instance Rename ModuleInstanceArg where
rename arg =
case arg of
ModuleArg m -> ModuleArg <$> rename m
ParameterArg a -> pure (ParameterArg a)
AddParams -> pure AddParams
instance Rename NestedModule where
rename (NestedModule m) =
do let lnm = mName m
nm = thing lnm
n <- resolveName NameBind NSModule nm
depsOf (NamedThing n)
do let m' = m { mName = ImpNested <$> mName m }
m1 <- renameModule' (ImpNested n) m'
pure (NestedModule m1 { mName = lnm { thing = n } })
instance Rename PrimType where
rename pt =
do x <- rnLocated (renameType NameBind) (primTName pt)
depsOf (NamedThing (thing x))
do let (as,ps) = primTCts pt
(_,cts) <- renameQual as ps $ \as' ps' -> pure (as',ps')
-- Record an additional use for each parameter since we checked
-- earlier that all the parameters are used exactly once in the
-- body of the signature. This prevents incorrect warnings
-- about unused names.
mapM_ (recordUse . tpName) (fst cts)
pure pt { primTCts = cts, primTName = x }
instance Rename ParameterType where
rename a =
do n' <- rnLocated (renameType NameBind) (ptName a)
return a { ptName = n' }
instance Rename ParameterFun where
rename a =
do n' <- rnLocated (renameVar NameBind) (pfName a)
depsOf (NamedThing (thing n'))
do sig' <- renameSchema (pfSchema a)
return a { pfName = n', pfSchema = snd sig' }
instance Rename SigDecl where
rename decl =
case decl of
SigTySyn ts mb -> SigTySyn <$> rename ts <*> pure mb
SigPropSyn ps mb -> SigPropSyn <$> rename ps <*> pure mb
instance Rename Decl where
rename d = case d of
DBind b -> DBind <$> rename b
DType syn -> DType <$> rename syn
DProp syn -> DProp <$> rename syn
DLocated d' r -> withLoc r
$ DLocated <$> rename d' <*> pure r
DFixity{} -> panic "rename" [ "DFixity" ]
DSignature {} -> panic "rename" [ "DSignature" ]
DPragma {} -> panic "rename" [ "DPragma" ]
DPatBind {} -> panic "rename" [ "DPatBind " ]
DRec {} -> panic "rename" [ "DRec" ]
instance Rename Newtype where
rename n =
shadowNames (nParams n) $
do nameT <- rnLocated (renameType NameBind) (nName n)
nameC <- renameCon NameBind (nConName n)
depsOf (NamedThing nameC) (addDep (thing nameT))
depsOf (NamedThing (thing nameT)) $
do ps' <- traverse rename (nParams n)
body' <- traverse (traverse rename) (nBody n)
return Newtype { nName = nameT
, nConName = nameC
, nParams = ps'
, nBody = body' }
instance Rename EnumDecl where
rename n =
shadowNames (eParams n) $
do nameT <- rnLocated (renameType NameBind) (eName n)
nameCs <- forM (eCons n) \tlEc ->
do let con = tlValue tlEc
nameC <- rnLocated (renameCon NameBind) (ecName con)
depsOf (NamedThing (thing nameC)) (addDep (thing nameT))
pure (nameC,tlEc)
depsOf (NamedThing (thing nameT)) $
do ps' <- traverse rename (eParams n)
cons <- forM nameCs \(c,tlEc) ->
do ts' <- traverse rename (ecFields (tlValue tlEc))
let con = EnumCon { ecName = c, ecFields = ts' }
pure tlEc { tlValue = con }
pure EnumDecl { eName = nameT
, eParams = ps'
, eCons = cons
}
-- | Try to resolve a name.
-- SPECIAL CASE: if we have a NameUse for NSValue, we also look in NSConstructor
resolveNameMaybe :: NameType -> Namespace -> PName -> RenameM (Maybe Name)
resolveNameMaybe nt expected qn =
do ro <- RenameM ask
let lkpIn here = Map.lookup qn (namespaceMap here (roNames ro))
use = case expected of
NSType -> recordUse
_ -> const (pure ())
checkCon = case (nt,expected) of
(NameUse, NSValue) -> lkpIn NSConstructor
_ -> Nothing
found = case (lkpIn expected, checkCon) of
(Just a, Just b) -> Just (a <> b)
(Nothing, y) -> y
(x, Nothing) -> x
case found of
Just xs ->
case xs of
One n ->
do case nt of
NameBind -> pure ()
NameUse -> addDep n
use n -- for warning
return (Just n)
Ambig symSet ->
do let syms = Set.toList symSet
headSym =
case syms of
sym:_ -> sym
[] -> panic "resolveNameMaybe" ["Ambig with no names"]
mapM_ use syms -- mark as used to avoid unused warnings
n <- located qn
recordError (MultipleSyms n syms)
return (Just headSym)
Nothing -> pure Nothing
reportUnboundName :: Namespace -> PName -> RenameM Name
reportUnboundName expected qn =
do ro <- RenameM ask
let lkpIn here = Map.lookup qn (namespaceMap here (roNames ro))
others = [ ns | ns <- allNamespaces
, ns /= expected
, Just _ <- [lkpIn ns] ]
nm <- located qn
case others of
-- name exists in a different namespace
actual : _ -> recordError (WrongNamespace expected actual nm)
-- the value is just missing
[] -> recordError (UnboundName expected nm)
mkFakeName expected qn
isFakeName :: ImpName Name -> Bool
isFakeName m =
case m of
ImpTop x -> x == undefinedModName
ImpNested x ->
case nameTopModuleMaybe x of
Just y -> y == undefinedModName
Nothing -> False
-- | Resolve a name, and report error on failure.
resolveName :: NameType -> Namespace -> PName -> RenameM Name
resolveName nt expected qn =
do mb <- resolveNameMaybe nt expected qn
case mb of
Just n -> pure n
Nothing -> reportUnboundName expected qn
renameVar :: NameType -> PName -> RenameM Name
renameVar nt = resolveName nt NSValue
renameCon :: NameType -> PName -> RenameM Name
renameCon nt = resolveName nt NSConstructor
renameType :: NameType -> PName -> RenameM Name
renameType nt = resolveName nt NSType
-- | Assuming an error has been recorded already, construct a fake name that's
-- not expected to make it out of the renamer.
mkFakeName :: Namespace -> PName -> RenameM Name
mkFakeName ns pn =
do ro <- RenameM ask
liftSupply (mkDeclared ns (TopModule undefinedModName)
SystemName (getIdent pn) Nothing (roLoc ro))
-- | Rename a schema, assuming that none of its type variables are already in
-- scope.
instance Rename Schema where