-
Notifications
You must be signed in to change notification settings - Fork 339
/
Data.hs
1874 lines (1655 loc) · 78.7 KB
/
Data.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
{-# LANGUAGE NondecreasingIndentation #-}
module Agda.TypeChecking.Rules.Data where
import Prelude hiding (null)
import Control.Monad
import Control.Monad.Except
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import Control.Exception as E
-- Control.Monad.Fail import is redundant since GHC 8.8.1
import Control.Monad.Fail (MonadFail)
import Data.Set (Set)
import qualified Data.Set as Set
import Agda.Interaction.Options.Base
import qualified Agda.Syntax.Abstract as A
import qualified Agda.Syntax.Concrete.Name as C
import Agda.Syntax.Abstract.Views (deepUnscope)
import Agda.Syntax.Internal
import Agda.Syntax.Internal.Pattern
import Agda.Syntax.Common
import Agda.Syntax.Position
import qualified Agda.Syntax.Info as Info
import Agda.Syntax.Scope.Monad
import {-# SOURCE #-} Agda.TypeChecking.CompiledClause.Compile
import Agda.TypeChecking.Monad
import Agda.TypeChecking.Conversion
import Agda.TypeChecking.Substitute
import Agda.TypeChecking.Generalize
import Agda.TypeChecking.Implicit
import Agda.TypeChecking.InstanceArguments
import Agda.TypeChecking.MetaVars
import Agda.TypeChecking.Names
import Agda.TypeChecking.Reduce
import Agda.TypeChecking.Positivity.Occurrence (Occurrence(StrictPos))
import Agda.TypeChecking.Pretty
import Agda.TypeChecking.Primitive hiding (Nat)
import Agda.TypeChecking.Free
import Agda.TypeChecking.Forcing
import Agda.TypeChecking.Irrelevance
import Agda.TypeChecking.Telescope
import {-# SOURCE #-} Agda.TypeChecking.Rules.Term ( isType_ )
import Agda.Utils.Either
import Agda.Utils.Function (applyWhen)
import Agda.Utils.Functor
import Agda.Utils.List
import Agda.Utils.Maybe
import Agda.Utils.Monad
import Agda.Utils.Null
import qualified Agda.Syntax.Common.Pretty as P
import Agda.Utils.Size
import Agda.Utils.Impossible
---------------------------------------------------------------------------
-- * Datatypes
---------------------------------------------------------------------------
-- | Type check a datatype definition. Assumes that the type has already been
-- checked.
checkDataDef :: A.DefInfo -> QName -> UniverseCheck -> A.DataDefParams -> [A.Constructor] -> TCM ()
checkDataDef i name uc (A.DataDefParams gpars ps) cs =
traceCall (CheckDataDef (getRange name) name ps cs) $ do
-- Add the datatype module
addSection (qnameToMName name)
-- Look up the type of the datatype.
def <- instantiateDef =<< getConstInfo name
t <- instantiateFull $ defType def
let npars =
case theDef def of
DataOrRecSig n -> n
_ -> __IMPOSSIBLE__
-- If the data type is erased, then hard compile-time mode is
-- entered.
setHardCompileTimeModeIfErased' def $ do
-- Make sure the shape of the type is visible
let unTelV (TelV tel a) = telePi tel a
t <- unTelV <$> telView t
parNames <- getGeneralizedParameters gpars name
-- Top level free vars
freeVars <- getContextSize
-- The parameters are in scope when checking the constructors.
dataDef <- bindGeneralizedParameters parNames t $ \ gtel t0 ->
bindParameters (npars - length parNames) ps t0 $ \ ptel t0 -> do
-- The type we get from bindParameters is Θ -> s where Θ is the type of
-- the indices. We count the number of indices and return s.
-- We check that s is a sort.
let TelV ixTel s0 = telView' t0
nofIxs = size ixTel
s <- workOnTypes $ do
-- Andreas, 2016-11-02 issue #2290
-- Trying to unify the sort with a fresh sort meta which is
-- defined outside the index telescope is the most robust way
-- to check independence of the indices.
-- However, it might give the dreaded "Cannot instantiate meta..."
-- error which we replace by a more understandable error
-- in case of a suspected dependency.
s <- newSortMetaBelowInf
catchError_ (addContext ixTel $ equalType s0 $ raise nofIxs $ sort s) $ \ err ->
if any (`freeIn` s0) [0..nofIxs - 1] then typeError $ SortCannotDependOnItsIndex name t0
else throwError err
reduce s
withK <- not . optWithoutK <$>
pragmaOptions
erasure <- optErasure <$> pragmaOptions
-- Parameters are always hidden in constructors. If
-- --erasure is used, then the parameters are erased for
-- non-indexed data types, and if --with-K is active this
-- applies also to indexed data types.
let tel = abstract gtel ptel
tel' = applyWhen (erasure && (withK || nofIxs == 0)) (applyQuantity zeroQuantity) .
hideAndRelParams <$>
tel
reportSDoc "tc.data.sort" 20 $ vcat
[ "checking datatype" <+> prettyTCM name
, nest 2 $ vcat
[ "type (parameters instantiated): " <+> prettyTCM t0
, "type (full): " <+> prettyTCM t
, "sort: " <+> prettyTCM s
, "indices:" <+> text (show nofIxs)
, "gparams:" <+> text (show parNames)
, "params: " <+> text (show $ deepUnscope ps)
]
]
let npars = size tel
-- Change the datatype from an axiom to a datatype with no constructors.
let dataDef = DatatypeData
{ _dataPars = npars
, _dataIxs = nofIxs
, _dataClause = Nothing
, _dataCons = [] -- Constructors are added later
, _dataSort = s
, _dataAbstr = Info.defAbstract i
, _dataMutual = Nothing
, _dataPathCons = [] -- Path constructors are added later
, _dataTranspIx = Nothing -- Generated later if nofIxs > 0.
, _dataTransp = Nothing -- Added later
}
escapeContext impossible npars $ do
addConstant' name defaultArgInfo name t $ DatatypeDefn dataDef
-- polarity and argOcc.s determined by the positivity checker
-- Check the types of the constructors
pathCons <- forM cs $ \ c -> do
isPathCons <- checkConstructor name uc tel' nofIxs s c
return $ if isPathCons == PathCons then Just (A.axiomName c) else Nothing
-- cubical: the interval universe does not contain datatypes
-- similar: SizeUniv, ...
checkDataSort name s
-- when `--without-K`, all the indices should fit in the
-- sort of the datatype (see #3420).
-- Andreas, 2019-07-16, issue #3916:
-- NoUniverseCheck should also disable the index sort check!
unless (uc == NoUniverseCheck) $
whenM withoutKOption $ do
let s' = case s of
Prop l -> Type l
_ -> s
checkIndexSorts s' ixTel
-- Return the data definition
return dataDef{ _dataPathCons = catMaybes pathCons
}
let cons = map A.axiomName cs -- get constructor names
(mtranspix, transpFun) <-
ifM (optCubicalCompatible <$> pragmaOptions)
(do mtranspix <- inTopContext $ defineTranspIx name
transpFun <- inTopContext $
defineTranspFun name mtranspix cons
(_dataPathCons dataDef)
return (mtranspix, transpFun))
(return (Nothing, Nothing))
-- Add the datatype to the signature with its constructors.
-- It was previously added without them.
addConstant' name defaultArgInfo name t $ DatatypeDefn
dataDef{ _dataCons = cons
, _dataTranspIx = mtranspix
, _dataTransp = transpFun
}
-- | Make sure that the target universe admits data type definitions.
-- E.g. @IUniv@, @SizeUniv@ etc. do not accept new constructions.
checkDataSort :: QName -> Sort -> TCM ()
checkDataSort name s = setCurrentRange name $ do
ifBlocked s postpone {-else-} $ \ _ (s :: Sort) -> do
let
yes :: TCM ()
yes = return ()
no :: TCM ()
no = typeError $ SortDoesNotAdmitDataDefinitions name s
case s of
-- Sorts that admit data definitions.
Univ _ _ -> yes
Inf _ _ -> yes
DefS _ _ -> yes
-- Sorts that do not admit data definitions.
SizeUniv -> no
LockUniv -> no
LevelUniv -> no
IntervalUniv -> no
-- Blocked sorts.
PiSort _ _ _ -> __IMPOSSIBLE__
FunSort _ _ -> __IMPOSSIBLE__
UnivSort _ -> __IMPOSSIBLE__
MetaS _ _ -> __IMPOSSIBLE__
DummyS _ -> __IMPOSSIBLE__
where
postpone :: Blocker -> Sort -> TCM ()
postpone b s = addConstraint b $ CheckDataSort name s
-- | Ensure that the type is a sort.
-- If it is not directly a sort, compare it to a 'newSortMetaBelowInf'.
forceSort :: Type -> TCM Sort
forceSort t = reduce (unEl t) >>= \case
Sort s -> return s
_ -> do
s <- newSortMetaBelowInf
equalType t (sort s)
return s
-- | Type check a constructor declaration. Checks that the constructor targets
-- the datatype and that it fits inside the declared sort.
-- Returns the non-linear parameters.
checkConstructor
:: QName -- ^ Name of data type.
-> UniverseCheck -- ^ Check universes?
-> Telescope -- ^ Parameter telescope.
-> Nat -- ^ Number of indices of the data type.
-> Sort -- ^ Sort of the data type.
-> A.Constructor -- ^ Constructor declaration (type signature).
-> TCM IsPathCons
checkConstructor d uc tel nofIxs s (A.ScopedDecl scope [con]) = do
setScope scope
checkConstructor d uc tel nofIxs s con
checkConstructor d uc tel nofIxs s con@(A.Axiom _ i ai Nothing c e) =
traceCall (CheckConstructor d tel s con) $ do
{- WRONG
-- Andreas, 2011-04-26: the following happens to the right of ':'
-- we may use irrelevant arguments in a non-strict way in types
t' <- workOnTypes $ do
-}
debugEnter c e
-- check that we are relevant
case getRelevance ai of
Relevant -> return ()
Irrelevant -> typeError $ GenericError $ "Irrelevant constructors are not supported"
NonStrict -> typeError $ GenericError $ "Shape-irrelevant constructors are not supported"
case getQuantity ai of
Quantityω{} -> return ()
Quantity0{} -> return ()
Quantity1{} -> typeError $ GenericError $ "Quantity-restricted constructors are not supported"
-- If the constructor is erased, then hard compile-time mode
-- is entered.
setHardCompileTimeModeIfErased' ai $ do
-- check that the type of the constructor is well-formed
(t, isPathCons) <- checkConstructorType e d
-- compute which constructor arguments are forced (only point constructors)
forcedArgs <- if isPathCons == PointCons
then computeForcingAnnotations c t
else return []
-- check that the sort (universe level) of the constructor type
-- is contained in the sort of the data type
-- (to avoid impredicative existential types)
debugFitsIn s
-- To allow propositional squash, we turn @Prop ℓ@ into @Set ℓ@
-- for the purpose of checking the type of the constructors.
let s' = case s of
Prop l -> Type l
_ -> s
arity <- applyQuantityToJudgement ai $
fitsIn c uc forcedArgs t s'
-- this may have instantiated some metas in s, so we reduce
s <- reduce s
debugAdd c t
(TelV fields _, boundary) <- telViewUpToPathBoundaryP (-1) t
-- We assume that the current context matches the parameters
-- of the datatype in an empty context (c.f. getContextSize above).
params <- getContextTelescope
(con, comp, projNames) <- do
-- Name for projection of ith field of constructor c is just c-i
names <- forM [0 .. size fields - 1] $ \ i ->
freshAbstractQName'_ $ P.prettyShow (A.qnameName c) ++ "-" ++ show i
-- nofIxs == 0 means the data type can be reconstructed
-- by appling the QName d to the parameters.
let dataT = El s $ Def d $ map Apply $ teleArgs params
reportSDoc "tc.data.con.comp" 5 $ inTopContext $ vcat $
[ "params =" <+> pretty params
, "dataT =" <+> pretty dataT
, "fields =" <+> pretty fields
, "names =" <+> pretty names
]
let con = ConHead c IsData Inductive $ zipWith (<$) names $ map argFromDom $ telToList fields
defineProjections d con params names fields dataT
-- Cannot compose indexed inductive types yet.
comp <- if nofIxs /= 0 || (Info.defAbstract i == AbstractDef)
then return emptyCompKit
else inTopContext $ defineCompData d con params names fields dataT boundary
return (con, comp, Just names)
-- add parameters to constructor type and put into signature
escapeContext impossible (size tel) $ do
erasure <- optErasure <$> pragmaOptions
addConstant' c ai c (telePi tel t) $ Constructor
{ conPars = size tel
, conArity = arity
, conSrcCon = con
, conData = d
, conAbstr = Info.defAbstract i
, conComp = comp
, conProj = projNames
, conForced = forcedArgs
, conErased = Nothing -- computed during compilation to treeless
, conErasure = erasure
, conInline = False
}
-- Add the constructor to the instance table, if needed
case Info.defInstance i of
InstanceDef _r -> setCurrentRange c $ do
-- Including the range of the @instance@ keyword, like
-- @(getRange (r,c))@, does not produce good results.
-- Andreas, 2020-01-28, issue #4360:
-- Use addTypedInstance instead of addNamedInstance
-- to detect unusable instances.
addTypedInstance c t
-- addNamedInstance c d
NotInstanceDef -> pure ()
return isPathCons
where
-- Issue 3362: we need to do the `constructs` call inside the
-- generalization, so unpack the A.Generalize
checkConstructorType (A.ScopedExpr s e) d = withScope_ s $ checkConstructorType e d
checkConstructorType e d = do
let check k e = do
t <- workOnTypes $ isType_ e
-- check that the type of the constructor ends in the data type
n <- getContextSize
debugEndsIn t d (n - k)
isPathCons <- constructs (n - k) k t d
return (t, isPathCons)
case e of
A.Generalized s e -> do
(_, t, isPathCons) <- generalizeType' s (check 1 e)
return (t, isPathCons)
_ -> check 0 e
debugEnter c e =
reportSDoc "tc.data.con" 5 $ vcat
[ "checking constructor" <+> prettyTCM c <+> ":" <+> prettyTCM e
]
debugEndsIn t d n =
reportSDoc "tc.data.con" 15 $ vcat
[ sep [ "checking that"
, nest 2 $ prettyTCM t
, "ends in" <+> prettyTCM d
]
, nest 2 $ "nofPars =" <+> text (show n)
]
debugFitsIn s =
reportSDoc "tc.data.con" 15 $ sep
[ "checking that the type fits in"
, nest 2 $ prettyTCM s
]
debugAdd c t =
reportSDoc "tc.data.con" 5 $ vcat
[ "adding constructor" <+> prettyTCM c <+> ":" <+> prettyTCM t
]
checkConstructor _ _ _ _ _ _ = __IMPOSSIBLE__ -- constructors are axioms
defineCompData :: QName -- datatype name
-> ConHead
-> Telescope -- Γ parameters
-> [QName] -- projection names
-> Telescope -- Γ ⊢ Φ field types
-> Type -- Γ ⊢ T target type
-> Boundary -- [(i,t_i,b_i)], Γ.Φ ⊢ [ (i=0) -> t_i; (i=1) -> u_i ] : B_i
-> TCM CompKit
defineCompData d con params names fsT t boundary = do
required <- mapM getTerm'
[ someBuiltin builtinInterval
, someBuiltin builtinIZero
, someBuiltin builtinIOne
, someBuiltin builtinIMin
, someBuiltin builtinIMax
, someBuiltin builtinINeg
, someBuiltin builtinPOr
, someBuiltin builtinItIsOne
]
if not (all isJust required) then return $ emptyCompKit else do
hcomp <- whenDefined (null boundary) [builtinHComp,builtinTrans]
(defineKanOperationD DoHComp d con params names fsT t boundary)
transp <- whenDefined True [builtinTrans]
(defineKanOperationD DoTransp d con params names fsT t boundary)
return $ CompKit
{ nameOfTransp = transp
, nameOfHComp = hcomp
}
where
-- Δ^I, i : I |- sub Δ : Δ
sub tel = [ var n `apply` [Arg defaultArgInfo $ var 0] | n <- [1..size tel] ] ++# EmptyS __IMPOSSIBLE__
withArgInfo tel = zipWith Arg (map domInfo . telToList $ tel)
defineKanOperationD cmd d con params names fsT t boundary = do
let project = (\ t p -> apply (Def p []) [argN t])
stuff <- defineKanOperationForFields cmd
(guard (not $ null boundary) >> Just (Con con ConOSystem $ teleElims fsT boundary))
project d params fsT (map argN names) t
caseMaybe stuff (return Nothing) $ \ ((theName, gamma , ty, _cl_types , bodies), theSub) -> do
iz <- primIZero
body <- do
case cmd of
DoHComp -> return $ Con con ConOSystem (map Apply $ withArgInfo fsT bodies)
DoTransp | null boundary {- && null ixs -} -> return $ Con con ConOSystem (map Apply $ withArgInfo fsT bodies)
| otherwise -> do
io <- primIOne
tIMax <- primIMax
tIMin <- primIMin
tINeg <- primINeg
tPOr <- fromMaybe __IMPOSSIBLE__ <$> getTerm' builtinPOr
tHComp <- primHComp
-- Δ = params
-- Δ ⊢ Φ = fsT
-- (δ : Δ) ⊢ T = R δ
-- (δ : Δ) ⊢ con : Φ → R δ -- no indexing
-- boundary = [(i,t_i,u_i)]
-- Δ.Φ ⊢ [ (i=0) -> t_i; (i=1) -> u_i ] : B_i
-- Δ.Φ | PiPath Φ boundary (R δ) |- teleElims fsT boundary : R δ
-- Γ = ((δ : Δ^I), φ, us : Φ[δ 0]) = gamma
-- Γ ⊢ ty = R (δ i1)
-- (γ : Γ) ⊢ cl_types = (flatten Φ)[n ↦ f_n (transpR γ)]
-- Γ ⊢ bodies : Φ[δ i1]
-- Γ ⊢ t : ty
-- Γ, i : I ⊢ theSub : Δ.Φ
let
-- Δ.Φ ⊢ u = Con con ConOSystem $ teleElims fsT boundary : R δ
u = Con con ConOSystem $ teleElims fsT boundary
-- Γ ⊢ u
the_u = liftS (size fsT) d0 `applySubst` u
where
-- δ : Δ^I, φ : F ⊢ [δ 0] : Δ
d0 :: Substitution
d0 = wkS 1 -- Δ^I, φ : F ⊢ Δ
(consS iz IdS `composeS` sub params) -- Δ^I ⊢ Δ
-- Δ^I , i:I ⊢ sub params : Δ
the_phi = raise (size fsT) $ var 0
-- Γ ⊢ sigma : Δ.Φ
-- sigma = [δ i1,bodies]
-- sigma = theSub[i1]
sigma = reverse bodies ++# d1
where
-- δ i1
d1 :: Substitution
d1 = wkS (size gamma - size params) -- Γ ⊢ Δ
(consS io IdS `composeS` sub params) -- Δ^I ⊢ Δ
-- Δ^I , i:I ⊢ sub params : Δ
-- Δ.Φ ⊢ [ (i=0) -> t_i; (i=1) -> u_i ] : R δ
bs = fullBoundary fsT boundary
-- ψ = sigma `applySubst` map (\ i → i ∨ ~ i) . map fst $ boundary
-- Γ ⊢ t : R (δ i1)
w1' = Con con ConOSystem $ sigma `applySubst` teleElims fsT boundary
-- (δ, φ, u0) : Γ ⊢
-- w1 = hcomp (\ i → R (δ i1))
-- (\ i → [ ψ ↦ α (~ i), φ ↦ u0])
-- w1'
imax x y = pure tIMax <@> x <@> y
ineg r = pure tINeg <@> r
lvlOfType = (\ (Type l) -> Level l) . getSort
pOr la i j u0 u1 = pure tPOr <#> (lvlOfType <$> la) <@> i <@> j
<#> ilam "o" (\ _ -> unEl <$> la) <@> u0 <@> u1
absAp x y = liftM2 absApp x y
mkFace (r,(u1,u2)) = runNamesT [] $ do
-- Γ
phi <- open the_phi -- (δ , φ , us) ⊢ φ
-- Γ ⊢ ty = Abs i. R (δ i)
ty <- open (Abs "i" $ (liftS 1 (raiseS (size gamma - size params)) `composeS` sub params) `applySubst` t)
bind "i" $ \ i -> do
-- Γ, i
[r,u1,u2] <- mapM (open . applySubst theSub) [r,u1,u2]
psi <- imax r (ineg r)
let
-- Γ, i ⊢ squeeze u = primTrans (\ j -> ty [i := i ∨ j]) (φ ∨ i) u
squeeze u = cl primTrans
<#> lam "j" (\ j -> lvlOfType <$> ty `absAp` (imax i j))
<@> lam "j" (\ j -> unEl <$> ty `absAp` (imax i j))
<@> (phi `imax` i)
<@> u
alpha <- pOr (ty `absAp` i)
(ineg r)
r
(ilam "o" $ \ _ -> squeeze u1) (ilam "o" $ \ _ -> squeeze u2)
return $ (psi, alpha)
-- Γ ⊢ Abs i. [(ψ_n,α_n : [ψ] → R (δ i))]
faces <- mapM mkFace bs
runNamesT [] $ do
-- Γ
w1' <- open w1'
phi <- open the_phi
u <- open the_u
-- R (δ i1)
ty <- open ty
faces <- mapM (\ x -> liftM2 (,) (open . noabsApp __IMPOSSIBLE__ $ fmap fst x) (open $ fmap snd x)) faces
let
thePsi = foldl1 imax (map fst faces)
hcomp ty phi sys a0 = pure tHComp <#> (lvlOfType <$> ty)
<#> (unEl <$> ty)
<#> phi
<@> sys
<@> a0
let
sys = lam "i" $ \ i -> do
let
recurse [(psi,alpha)] = alpha `absAp` (ineg i)
recurse ((psi,alpha):xs) = pOr ty
psi theOr
(alpha `absAp` (ineg i)) (recurse xs)
where
theOr = foldl1 imax (map fst xs)
recurse [] = __IMPOSSIBLE__
sys_alpha = recurse faces
pOr ty
thePsi phi
sys_alpha (ilam "o" $ \ _ -> u)
hcomp ty (thePsi `imax` phi) sys w1'
let
-- δ : Δ^I, φ : F ⊢ [δ 0] : Δ
d0 :: Substitution
d0 = wkS 1 -- Δ^I, φ : F ⊢ Δ
(consS iz IdS `composeS` sub params) -- Δ^I ⊢ Δ
-- Δ^I , i:I ⊢ sub params : Δ
-- Δ.Φ ⊢ u = Con con ConOSystem $ teleElims fsT boundary : R δ
-- u = Con con ConOSystem $ teleElims fsT boundary
up = ConP con (ConPatternInfo defaultPatternInfo False False Nothing False) $
telePatterns (d0 `applySubst` fsT) (liftS (size fsT) d0 `applySubst` boundary)
-- gamma' = telFromList $ take (size gamma - 1) $ telToList gamma
-- (δ , φ , fs : Φ[d0]) ⊢ u[liftS Φ d0]
-- (δ , φ, u) : Γ ⊢ body
-- Δ ⊢ Φ = fsT
-- (δ , φ , fs : Φ[d0]) ⊢ u[liftS Φ d0] `consS` raiseS Φ : Γ
-- (tel',theta) = (abstract gamma' (d0 `applySubst` fsT), (liftS (size fsT) d0 `applySubst` u) `consS` raiseS (size fsT))
let
pats | null boundary = teleNamedArgs gamma
| otherwise = take (size gamma - size fsT) (teleNamedArgs gamma) ++ [argN $ unnamed $ up]
clause = Clause
{ clauseTel = gamma
, clauseType = Just . argN $ ty
, namedClausePats = pats
, clauseFullRange = noRange
, clauseLHSRange = noRange
, clauseCatchall = False
, clauseBody = Just $ body
, clauseExact = Just True
, clauseRecursive = Nothing
-- Andreas 2020-02-06 TODO
-- Or: Just False; is it known to be non-recursive?
, clauseUnreachable = Just False
, clauseEllipsis = NoEllipsis
, clauseWhereModule = Nothing
}
cs = [clause]
addClauses theName cs
(mst, _, cc) <- inTopContext (compileClauses Nothing cs)
whenJust mst $ setSplitTree theName
setCompiledClauses theName cc
setTerminates theName True
return $ Just theName
whenDefined False _ _ = return Nothing
whenDefined True xs m = do
xs <- mapM getTerm' xs
if all isJust xs then m else return Nothing
-- Andrea: TODO handle Irrelevant fields somehow.
-- | Define projections for non-indexed data types (families don't work yet).
-- Of course, these projections are partial functions in general.
--
-- Precondition: we are in the context Γ of the data type parameters.
defineProjections :: QName -- datatype name
-> ConHead
-> Telescope -- Γ parameters
-> [QName] -- projection names
-> Telescope -- Γ ⊢ Φ field types
-> Type -- Γ ⊢ T target type
-> TCM ()
defineProjections dataName con params names fsT t = do
let
-- Γ , (d : T) ⊢ Φ[n ↦ proj n d]
fieldTypes = ([ Def f [] `apply` [argN $ var 0] | f <- reverse names ] ++# raiseS 1) `applySubst`
flattenTel fsT -- Γ , Φ ⊢ Φ
-- ⊢ Γ , (d : T)
projTel = abstract params (ExtendTel (defaultDom t) (Abs "d" EmptyTel))
np = size params
forM_ (zip3 (downFrom (size fieldTypes)) names fieldTypes) $ \ (i,projName,ty) -> do
let
projType = abstract projTel <$> ty
cpi = ConPatternInfo defaultPatternInfo False False (Just $ argN $ raise (size fsT) t) False
conp = defaultNamedArg $ ConP con cpi $ teleNamedArgs fsT
sigma = Con con ConOSystem (map Apply $ teleArgs fsT) `consS` raiseS (size fsT)
clause = empty
{ clauseTel = abstract params fsT
, namedClausePats = [ conp ]
, clauseBody = Just $ var i
, clauseType = Just $ argN $ applySubst sigma $ unDom ty
, clauseRecursive = Just False -- non-recursive
, clauseUnreachable = Just False
}
reportSDoc "tc.data.proj" 20 $ inTopContext $ sep
[ "proj" <+> prettyTCM (i,ty)
, nest 2 $ sep [ prettyTCM projName, ":", prettyTCM projType ]
]
-- Andreas, 2020-02-14, issue #4437
-- Define data projections as projection-like from the start.
noMutualBlock $ do
let cs = [ clause ]
(mst, _, cc) <- compileClauses Nothing cs
fun <- emptyFunctionData <&> \fun -> fun
{ _funClauses = cs
, _funCompiled = Just cc
, _funSplitTree = mst
, _funProjection = Right Projection
{ projProper = Nothing
, projOrig = projName
, projFromType = Arg (getArgInfo ty) dataName
, projIndex = np + 1
, projLams = ProjLams $ map (argFromDom . fmap fst) $ telToList projTel
}
, _funMutual = Just []
, _funTerminates = Just True
}
lang <- getLanguage
inTopContext $ addConstant projName $
(defaultDefn defaultArgInfo projName (unDom projType) lang $ FunctionDefn fun)
{ defNoCompilation = True
, defArgOccurrences = [StrictPos]
}
reportSDoc "tc.data.proj.fun" 60 $ inTopContext $ vcat
[ "proj" <+> prettyTCM i
, nest 2 $ pretty fun
]
freshAbstractQName'_ :: String -> TCM QName
freshAbstractQName'_ = freshAbstractQName noFixity' . C.simpleName
-- | Defines and returns the name of the `transpIx` function.
defineTranspIx :: QName -- ^ datatype name
-> TCM (Maybe QName)
defineTranspIx d = do
def <- getConstInfo d
case theDef def of
Datatype { dataPars = npars
, dataIxs = nixs
, dataSort = s}
-> do
let t = defType def
reportSDoc "tc.data.ixs" 20 $ vcat
[ "name :" <+> prettyTCM d
, "type :" <+> prettyTCM t
, "npars:" <+> pretty npars
, "nixs :" <+> pretty nixs
]
if nixs == 0 then return Nothing else do
trIx <- freshAbstractQName'_ $ "transpX-" ++ P.prettyShow (A.qnameName d)
TelV params t' <- telViewUpTo npars t
TelV ixs dT <- telViewUpTo nixs t'
-- params ⊢ s
-- params ⊢ ixs
-- params.ixs ⊢ dT
reportSDoc "tc.data.ixs" 20 $ vcat
[ "params :" <+> prettyTCM params
, "ixs :" <+> (addContext params $ prettyTCM ixs)
, "dT :" <+> (addContext params $ addContext ixs $ prettyTCM dT)
]
-- theType <- abstract params <$> undefined
interval <- primIntervalType
let deltaI = expTelescope interval ixs
iz <- primIZero
io@(Con c _ _) <- primIOne
imin <- getPrimitiveTerm builtinIMin
imax <- getPrimitiveTerm builtinIMax
ineg <- getPrimitiveTerm builtinINeg
transp <- getPrimitiveTerm builtinTrans
por <- getPrimitiveTerm builtinPOr
one <- primItIsOne
-- reportSDoc "trans.rec" 20 $ text $ show params
-- reportSDoc "trans.rec" 20 $ text $ show deltaI
-- reportSDoc "trans.rec" 10 $ text $ show fsT
-- let thePrefix = "transp-"
-- theName <- freshAbstractQName'_ $ thePrefix ++ P.prettyShow (A.qnameName name)
-- reportSLn "trans.rec" 5 $ ("Generated name: " ++ show theName ++ " " ++ showQNameId theName)
-- record type in 'exponentiated' context
-- (params : Γ)(ixs : Δ^I), i : I |- T[params, ixs i]
let rect' = sub ixs `applySubst` El (raise (size ixs) s) (Def d (teleElims (abstract params ixs) []))
addContext params $ reportSDoc "tc.data.ixs" 20 $ "deltaI:" <+> prettyTCM deltaI
addContext params $ addContext deltaI $ addContext ("i"::String, defaultDom interval) $ do
reportSDoc "tc.data.ixs" 20 $ "rect':" <+> pretty (sub ixs)
reportSDoc "tc.data.ixs" 20 $ "rect':" <+> pretty rect'
theType <- (abstract (setHiding Hidden <$> params) <$>) . (abstract deltaI <$>) $ runNamesT [] $ do
rect' <- open (runNames [] $ bind "i" $ \ x -> let _ = x `asTypeOf` pure (undefined :: Term) in
pure rect')
nPi' "phi" (primIntervalType) $ \ phi ->
(absApp <$> rect' <*> pure iz) --> (absApp <$> rect' <*> pure io)
reportSDoc "tc.data.ixs" 20 $ "transpIx:" <+> prettyTCM theType
let
ctel = abstract params $ abstract deltaI $ ExtendTel (defaultDom $ subst 0 iz rect') (Abs "t" EmptyTel)
ps = telePatterns ctel []
cpi = noConPatternInfo { conPType = Just (defaultArg interval) }
pat :: NamedArg (Pattern' DBPatVar)
pat = defaultNamedArg $ ConP c cpi []
clause = empty
{ clauseTel = ctel
, namedClausePats = init ps ++ [pat, last ps]
, clauseBody = Just $ var 0
, clauseType = Just $ defaultArg $ raise 1 $ subst 0 io rect'
, clauseRecursive = Just False -- non-recursive
, clauseUnreachable = Just False
}
noMutualBlock $ do
let cs = [ clause ]
-- we do not compile clauses as that leads to throwing missing clauses errors.
-- (mst, _, cc) <- compileClauses Nothing cs
fun <- emptyFunctionData <&> \fun -> fun
{ _funClauses = cs
-- , _funCompiled = Just cc
-- , _funSplitTree = mst
, _funProjection = Left MaybeProjection
, _funMutual = Just []
, _funTerminates = Just True
, _funIsKanOp = Just d
}
inTopContext $ do
reportSDoc "tc.transpx.type" 15 $ vcat
[ "type of" <+> prettyTCM trIx <+> ":"
, nest 2 $ prettyTCM theType
]
addConstant trIx $
(defaultDefn defaultArgInfo trIx theType (Cubical CErased) $ FunctionDefn fun)
{ defNoCompilation = True
}
-- reportSDoc "tc.data.proj.fun" 60 $ inTopContext $ vcat
-- [ "proj" <+> prettyTCM i
-- , nest 2 $ pretty fun
-- ]
-- addContext ctel $ do
-- let es = teleElims ctel []
-- r <- reduce $ Def trIx es
-- reportSDoc "tc.data.ixs" 20 $ "reducedx:" <+> prettyTCM r
-- r <- reduce $ Def trIx (init es ++ [Apply $ argN io, last es])
-- reportSDoc "tc.data.ixs" 20 $ "reduced1:" <+> prettyTCM r
return $ Just trIx
_ -> __IMPOSSIBLE__
where
-- Γ, Δ^I, i : I |- sub (Γ ⊢ Δ) : Γ, Δ
sub tel = expS $ size tel
defineTranspFun :: QName -- ^ datatype
-> Maybe QName -- ^ transpX "constructor"
-> [QName] -- ^ constructor names
-> [QName] -- ^ path cons
-> TCM (Maybe QName) -- transp function for the datatype.
defineTranspFun d mtrX cons pathCons = do
def <- getConstInfo d
case theDef def of
Datatype { dataPars = npars
, dataIxs = nixs
, dataSort = s@(Type _)
-- , dataCons = cons -- not there yet
}
-> do
let t = defType def
reportSDoc "tc.data.transp" 20 $ vcat
[ "name :" <+> prettyTCM d
, "type :" <+> prettyTCM t
, "npars:" <+> pretty npars
, "nixs :" <+> pretty nixs
]
trD <- freshAbstractQName'_ $ "transp" ++ P.prettyShow (A.qnameName d)
TelV params t' <- telViewUpTo npars t
TelV ixs dT <- telViewUpTo nixs t'
let tel = abstract params ixs
mixs <- runMaybeT $ traverse (traverse (MaybeT . toLType)) ixs
caseMaybe mixs (return Nothing) $ \ _ -> do
io@(Con io_c _ []) <- primIOne
iz <- primIZero
interval <- primIntervalType
let telI = expTelescope interval tel
sigma = sub tel
dTs = (sigma `applySubst` El s (Def d $ map Apply $ teleArgs tel))
theType <- (abstract telI <$>) $ runNamesT [] $ do
dT <- open $ Abs "i" $ dTs
nPi' "phi" primIntervalType $ \ phi ->
(absApp <$> dT <*> pure iz) --> (absApp <$> dT <*> pure io)
reportSDoc "tc.data.transp" 20 $ "transpD:" <+> prettyTCM theType
noMutualBlock $ do
fun <- emptyFunction
inTopContext $ addConstant trD $
(defaultDefn defaultArgInfo trD theType (Cubical CErased) fun)
let
ctel = abstract telI $ ExtendTel (defaultDom $ subst 0 iz dTs) (Abs "t" EmptyTel)
ps = telePatterns ctel []
cpi = noConPatternInfo { conPType = Just (defaultArg interval)
, conPFallThrough = True
}
pat :: NamedArg (Pattern' DBPatVar)
pat = defaultNamedArg $ ConP io_c cpi []
clause = empty
{ clauseTel = ctel
, namedClausePats = init ps ++ [pat, last ps]
, clauseBody = Just $ var 0
, clauseType = Just $ defaultArg $ raise 1 $ subst 0 io dTs
, clauseRecursive = Just False -- non-recursive
, clauseUnreachable = Just False
}
let debugNoTransp cl = enterClosure cl $ \ t -> do
reportSDoc "tc.data.transp" 20 $ addContext ("i" :: String, __DUMMY_DOM__) $
"could not transp" <+> prettyTCM (absBody t)
-- TODO: if no params nor indexes trD phi u0 = u0.
ecs <- tryTranspError $ (clause:) <$> defineConClause trD (not $ null pathCons) mtrX npars nixs ixs telI sigma dTs cons
caseEitherM (pure ecs) (\ cl -> debugNoTransp cl >> return Nothing) $ \ cs -> do
(mst, _, cc) <- compileClauses Nothing cs
fun <- emptyFunctionData <&> \fun -> fun
{ _funClauses = cs
, _funCompiled = Just cc
, _funSplitTree = mst
, _funProjection = Left MaybeProjection
, _funMutual = Just []
, _funTerminates = Just True
, _funIsKanOp = Just d
}
inTopContext $ addConstant trD $
(defaultDefn defaultArgInfo trD theType (Cubical CErased) $ FunctionDefn fun)
{ defNoCompilation = True
}
reportSDoc "tc.data.transp" 20 $ sep
[ "transp: compiled clauses of " <+> prettyTCM trD
, nest 2 $ return $ P.pretty cc
]
return $ Just trD
Datatype {} -> return Nothing
_ -> __IMPOSSIBLE__
where
-- Γ, Δ^I, i : I |- sub (Γ ⊢ Δ) : Γ, Δ
sub tel = expS (size tel)
defineConClause :: QName -- ^ trD
-> Bool -- ^ HIT
-> Maybe QName -- ^ trX
-> Nat -- ^ npars = size Δ
-> Nat -- ^ nixs = size X
-> Telescope -- ^ Δ ⊢ X
-> Telescope -- ^ (Δ.X)^I
-> Substitution -- ^ (Δ.X)^I, i : I ⊢ σ : Δ.X
-> Type -- ^ (Δ.X)^I, i : I ⊢ D[δ i,x i] -- datatype
-> [QName] -- ^ Constructors
-> TCM [Clause]
defineConClause trD' isHIT mtrX npars nixs xTel' telI sigma dT' cnames = do
unless (isNothing mtrX == (nixs == 0)) $ __IMPOSSIBLE__
io <- primIOne
iz <- primIZero
tHComp <- primHComp
tINeg <- primINeg
let max i j = cl primIMax <@> i <@> j
let min i j = cl primIMin <@> i <@> j
let neg i = cl primINeg <@> i
let hcomp ty sys u0 = do
ty <- ty
Just (LEl l ty) <- toLType ty
l <- open $ Level l
ty <- open $ ty
face <- (foldr max (pure iz) $ map fst $ sys)
sys <- lam "i'" $ \ i -> combineSys l ty [(phi, u <@> i) | (phi,u) <- sys]
pure tHComp <#> l <#> ty <#> pure face <@> pure sys <@> u0
interval <- primIntervalType
let intervalTel nm = ExtendTel (defaultDom interval) (Abs nm EmptyTel)
let (parI,ixsI) = splitTelescopeAt npars telI
let
abstract_trD :: MonadFail m => (Vars m -> Vars m -> Vars m -> NamesT m Telescope) -> NamesT m Telescope
abstract_trD k = do
ixsI <- open $ AbsN (teleNames parI) ixsI
parI <- open parI
abstractN parI $ \ delta -> do
abstractN (ixsI `applyN` delta) $ \ x -> do
abstractN (pure $ intervalTel "phi") $ \ phi -> do
k delta x phi
bind_trD :: MonadFail m => (ArgVars m -> ArgVars m -> ArgVars m -> NamesT m b) ->
NamesT m (AbsN (AbsN (AbsN b)))
bind_trD k = do
bindNArg (teleArgNames parI) $ \ delta_ps -> do
bindNArg (teleArgNames ixsI) $ \ x_ps -> do
bindNArg (teleArgNames $ intervalTel "phi") $ \ phi_ps -> do
k delta_ps x_ps phi_ps
let trD = bindNArg (teleArgNames parI) $ \ delta ->
bindNArg (teleArgNames ixsI) $ \ x ->
bindN ["phi","u0"] $ \ [phi,u0] ->
((Def trD' [] `apply`) <$> sequence (delta ++ x)) <@> phi <@> u0
-- [Δ] ⊢ X
let xTel = pure $ AbsN (teleNames parI) xTel'
-- [δ : Δ^I, x : X^I, i : I] ⊢ D (δ i) (x i)
let dT = pure $ AbsN (teleNames parI ++ teleNames ixsI ++ ["i"]) dT'
let hcompComputes = not $ isHIT || nixs > 0
c_HComp <- if hcompComputes then return [] else do
reportSDoc "tc.data.transp.con" 20 $ "======================="
reportSDoc "tc.data.transp.con" 20 $ "hcomp"
qHComp <- fromMaybe __IMPOSSIBLE__ <$> getPrimitiveName' builtinHComp
hcomp_ty <- defType <$> getConstInfo qHComp
gamma <- runNamesT [] $ do
ixsI <- open $ AbsN (teleNames parI) ixsI
parI <- open parI
abstract_trD $ \ delta x _ -> do
Just (LEl l ty) <- toLType =<< (dT `applyN` (delta ++ x ++ [pure iz]))
-- (φ : I), (I → Partial φ (D (δ i0) (x i0))), D (δ i0) (x i0)
TelV args _ <- lift $ telView =<< piApplyM hcomp_ty [Level l,ty]
unless (size args == 3) __IMPOSSIBLE__
pure args
res <- runNamesT [] $ do