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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1997-1998
\section[BasicTypes]{Miscellaneous types}
This module defines a miscellaneously collection of very simple
types that
\begin{itemize}
\item have no other obvious home
\item don't depend on any other complicated types
\item are used in more than one "part" of the compiler
\end{itemize}
-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
module GHC.Types.Basic (
Version, bumpVersion, initialVersion,
LeftOrRight(..),
pickLR,
ConTag, ConTagZ, fIRST_TAG,
Arity, RepArity, JoinArity,
Alignment, mkAlignment, alignmentOf, alignmentBytes,
PromotionFlag(..), isPromoted,
FunctionOrData(..),
WarningTxt(..), pprWarningTxtForMsg, StringLiteral(..),
Fixity(..), FixityDirection(..),
defaultFixity, maxPrecedence, minPrecedence,
negateFixity, funTyFixity,
compareFixity,
LexicalFixity(..),
RecFlag(..), isRec, isNonRec, boolToRecFlag,
Origin(..), isGenerated,
RuleName, pprRuleName,
TopLevelFlag(..), isTopLevel, isNotTopLevel,
OverlapFlag(..), OverlapMode(..), setOverlapModeMaybe,
hasOverlappingFlag, hasOverlappableFlag, hasIncoherentFlag,
Boxity(..), isBoxed,
PprPrec(..), topPrec, sigPrec, opPrec, funPrec, starPrec, appPrec,
maybeParen,
TupleSort(..), tupleSortBoxity, boxityTupleSort,
tupleParens,
sumParens, pprAlternative,
-- ** The OneShotInfo type
OneShotInfo(..),
noOneShotInfo, hasNoOneShotInfo, isOneShotInfo,
bestOneShot, worstOneShot,
OccInfo(..), noOccInfo, seqOccInfo, zapFragileOcc, isOneOcc,
isDeadOcc, isStrongLoopBreaker, isWeakLoopBreaker, isManyOccs,
isNoOccInfo, strongLoopBreaker, weakLoopBreaker,
InsideLam(..),
OneBranch(..),
InterestingCxt(..),
TailCallInfo(..), tailCallInfo, zapOccTailCallInfo,
isAlwaysTailCalled,
EP(..),
DefMethSpec(..),
SwapFlag(..), flipSwap, unSwap, isSwapped,
CompilerPhase(..), PhaseNum,
Activation(..), isActive, isActiveIn, competesWith,
isNeverActive, isAlwaysActive, isEarlyActive,
activeAfterInitial, activeDuringFinal,
RuleMatchInfo(..), isConLike, isFunLike,
InlineSpec(..), noUserInlineSpec,
InlinePragma(..), defaultInlinePragma, alwaysInlinePragma,
neverInlinePragma, dfunInlinePragma,
isDefaultInlinePragma,
isInlinePragma, isInlinablePragma, isAnyInlinePragma,
inlinePragmaSpec, inlinePragmaSat,
inlinePragmaActivation, inlinePragmaRuleMatchInfo,
setInlinePragmaActivation, setInlinePragmaRuleMatchInfo,
pprInline, pprInlineDebug,
SuccessFlag(..), succeeded, failed, successIf,
IntegralLit(..), FractionalLit(..),
negateIntegralLit, negateFractionalLit,
mkIntegralLit, mkFractionalLit,
integralFractionalLit,
SourceText(..), pprWithSourceText,
IntWithInf, infinity, treatZeroAsInf, mkIntWithInf, intGtLimit,
SpliceExplicitFlag(..),
TypeOrKind(..), isTypeLevel, isKindLevel
) where
import GHC.Prelude
import GHC.Data.FastString
import GHC.Utils.Outputable
import GHC.Types.SrcLoc ( Located,unLoc )
import Data.Data hiding (Fixity, Prefix, Infix)
import Data.Function (on)
import Data.Bits
import qualified Data.Semigroup as Semi
{-
************************************************************************
* *
Binary choice
* *
************************************************************************
-}
data LeftOrRight = CLeft | CRight
deriving( Eq, Data )
pickLR :: LeftOrRight -> (a,a) -> a
pickLR CLeft (l,_) = l
pickLR CRight (_,r) = r
instance Outputable LeftOrRight where
ppr CLeft = text "Left"
ppr CRight = text "Right"
{-
************************************************************************
* *
\subsection[Arity]{Arity}
* *
************************************************************************
-}
-- | The number of value arguments that can be applied to a value before it does
-- "real work". So:
-- fib 100 has arity 0
-- \x -> fib x has arity 1
-- See also Note [Definition of arity] in GHC.Core.Arity
type Arity = Int
-- | Representation Arity
--
-- The number of represented arguments that can be applied to a value before it does
-- "real work". So:
-- fib 100 has representation arity 0
-- \x -> fib x has representation arity 1
-- \(# x, y #) -> fib (x + y) has representation arity 2
type RepArity = Int
-- | The number of arguments that a join point takes. Unlike the arity of a
-- function, this is a purely syntactic property and is fixed when the join
-- point is created (or converted from a value). Both type and value arguments
-- are counted.
type JoinArity = Int
{-
************************************************************************
* *
Constructor tags
* *
************************************************************************
-}
-- | Constructor Tag
--
-- Type of the tags associated with each constructor possibility or superclass
-- selector
type ConTag = Int
-- | A *zero-indexed* constructor tag
type ConTagZ = Int
fIRST_TAG :: ConTag
-- ^ Tags are allocated from here for real constructors
-- or for superclass selectors
fIRST_TAG = 1
{-
************************************************************************
* *
\subsection[Alignment]{Alignment}
* *
************************************************************************
-}
-- | A power-of-two alignment
newtype Alignment = Alignment { alignmentBytes :: Int } deriving (Eq, Ord)
-- Builds an alignment, throws on non power of 2 input. This is not
-- ideal, but convenient for internal use and better then silently
-- passing incorrect data.
mkAlignment :: Int -> Alignment
mkAlignment n
| n == 1 = Alignment 1
| n == 2 = Alignment 2
| n == 4 = Alignment 4
| n == 8 = Alignment 8
| n == 16 = Alignment 16
| n == 32 = Alignment 32
| n == 64 = Alignment 64
| n == 128 = Alignment 128
| n == 256 = Alignment 256
| n == 512 = Alignment 512
| otherwise = panic "mkAlignment: received either a non power of 2 argument or > 512"
-- Calculates an alignment of a number. x is aligned at N bytes means
-- the remainder from x / N is zero. Currently, interested in N <= 8,
-- but can be expanded to N <= 16 or N <= 32 if used within SSE or AVX
-- context.
alignmentOf :: Int -> Alignment
alignmentOf x = case x .&. 7 of
0 -> Alignment 8
4 -> Alignment 4
2 -> Alignment 2
_ -> Alignment 1
instance Outputable Alignment where
ppr (Alignment m) = ppr m
{-
************************************************************************
* *
One-shot information
* *
************************************************************************
-}
{-
Note [OneShotInfo overview]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lambda-bound Ids (and only lambda-bound Ids) may be decorated with
one-shot info. The idea is that if we see
(\x{one-shot}. e)
it means that this lambda will only be applied once. In particular
that means we can float redexes under the lambda without losing
work. For example, consider
let t = expensive in
(\x{one-shot}. case t of { True -> ...; False -> ... })
Because it's a one-shot lambda, we can safely inline t, giving
(\x{one_shot}. case <expensive> of of
{ True -> ...; False -> ... })
Moving parts:
* Usage analysis, performed as part of demand-analysis, finds
out whether functions call their argument once. Consider
f g x = Just (case g x of { ... })
Here 'f' is lazy in 'g', but it guarantees to call it no
more than once. So g will get a C1(U) usage demand.
* Occurrence analysis propagates this usage information
(in the demand signature of a function) to its calls.
Example, given 'f' above
f (\x.e) blah
Since f's demand signature says it has a C1(U) usage demand on its
first argument, the occurrence analyser sets the \x to be one-shot.
This is done via the occ_one_shots field of OccEnv.
* Float-in and float-out take account of one-shot-ness
* Occurrence analysis doesn't set "inside-lam" for occurrences inside
a one-shot lambda
Other notes
* A one-shot lambda can use its argument many times. To elaborate
the example above
let t = expensive in
(\x{one-shot}. case t of { True -> x+x; False -> x*x })
Here the '\x' is one-shot, which justifies inlining 't',
but x is used many times. That's absolutely fine.
* It's entirely possible to have
(\x{one-shot}. \y{many-shot}. e)
For example
let t = expensive
g = \x -> let v = x+t in
\y -> x + v
in map (g 5) xs
Here the `\x` is a one-shot binder: `g` is applied to one argument
exactly once. And because the `\x` is one-shot, it would be fine to
float that `let t = expensive` binding inside the `\x`.
But the `\y` is most definitely not one-shot!
-}
-- | If the 'Id' is a lambda-bound variable then it may have lambda-bound
-- variable info. Sometimes we know whether the lambda binding this variable
-- is a "one-shot" lambda; that is, whether it is applied at most once.
--
-- This information may be useful in optimisation, as computations may
-- safely be floated inside such a lambda without risk of duplicating
-- work.
--
-- See also Note [OneShotInfo overview] above.
data OneShotInfo
= NoOneShotInfo -- ^ No information
| OneShotLam -- ^ The lambda is applied at most once.
deriving (Eq)
-- | It is always safe to assume that an 'Id' has no lambda-bound variable information
noOneShotInfo :: OneShotInfo
noOneShotInfo = NoOneShotInfo
isOneShotInfo, hasNoOneShotInfo :: OneShotInfo -> Bool
isOneShotInfo OneShotLam = True
isOneShotInfo _ = False
hasNoOneShotInfo NoOneShotInfo = True
hasNoOneShotInfo _ = False
worstOneShot, bestOneShot :: OneShotInfo -> OneShotInfo -> OneShotInfo
worstOneShot NoOneShotInfo _ = NoOneShotInfo
worstOneShot OneShotLam os = os
bestOneShot NoOneShotInfo os = os
bestOneShot OneShotLam _ = OneShotLam
pprOneShotInfo :: OneShotInfo -> SDoc
pprOneShotInfo NoOneShotInfo = empty
pprOneShotInfo OneShotLam = text "OneShot"
instance Outputable OneShotInfo where
ppr = pprOneShotInfo
{-
************************************************************************
* *
Swap flag
* *
************************************************************************
-}
data SwapFlag
= NotSwapped -- Args are: actual, expected
| IsSwapped -- Args are: expected, actual
instance Outputable SwapFlag where
ppr IsSwapped = text "Is-swapped"
ppr NotSwapped = text "Not-swapped"
flipSwap :: SwapFlag -> SwapFlag
flipSwap IsSwapped = NotSwapped
flipSwap NotSwapped = IsSwapped
isSwapped :: SwapFlag -> Bool
isSwapped IsSwapped = True
isSwapped NotSwapped = False
unSwap :: SwapFlag -> (a->a->b) -> a -> a -> b
unSwap NotSwapped f a b = f a b
unSwap IsSwapped f a b = f b a
{- *********************************************************************
* *
Promotion flag
* *
********************************************************************* -}
-- | Is a TyCon a promoted data constructor or just a normal type constructor?
data PromotionFlag
= NotPromoted
| IsPromoted
deriving ( Eq, Data )
isPromoted :: PromotionFlag -> Bool
isPromoted IsPromoted = True
isPromoted NotPromoted = False
instance Outputable PromotionFlag where
ppr NotPromoted = text "NotPromoted"
ppr IsPromoted = text "IsPromoted"
{-
************************************************************************
* *
\subsection[FunctionOrData]{FunctionOrData}
* *
************************************************************************
-}
data FunctionOrData = IsFunction | IsData
deriving (Eq, Ord, Data)
instance Outputable FunctionOrData where
ppr IsFunction = text "(function)"
ppr IsData = text "(data)"
{-
************************************************************************
* *
\subsection[Version]{Module and identifier version numbers}
* *
************************************************************************
-}
type Version = Int
bumpVersion :: Version -> Version
bumpVersion v = v+1
initialVersion :: Version
initialVersion = 1
{-
************************************************************************
* *
Deprecations
* *
************************************************************************
-}
-- | A String Literal in the source, including its original raw format for use by
-- source to source manipulation tools.
data StringLiteral = StringLiteral
{ sl_st :: SourceText, -- literal raw source.
-- See not [Literal source text]
sl_fs :: FastString -- literal string value
} deriving Data
instance Eq StringLiteral where
(StringLiteral _ a) == (StringLiteral _ b) = a == b
instance Outputable StringLiteral where
ppr sl = pprWithSourceText (sl_st sl) (ftext $ sl_fs sl)
-- | Warning Text
--
-- reason/explanation from a WARNING or DEPRECATED pragma
data WarningTxt = WarningTxt (Located SourceText)
[Located StringLiteral]
| DeprecatedTxt (Located SourceText)
[Located StringLiteral]
deriving (Eq, Data)
instance Outputable WarningTxt where
ppr (WarningTxt lsrc ws)
= case unLoc lsrc of
NoSourceText -> pp_ws ws
SourceText src -> text src <+> pp_ws ws <+> text "#-}"
ppr (DeprecatedTxt lsrc ds)
= case unLoc lsrc of
NoSourceText -> pp_ws ds
SourceText src -> text src <+> pp_ws ds <+> text "#-}"
pp_ws :: [Located StringLiteral] -> SDoc
pp_ws [l] = ppr $ unLoc l
pp_ws ws
= text "["
<+> vcat (punctuate comma (map (ppr . unLoc) ws))
<+> text "]"
pprWarningTxtForMsg :: WarningTxt -> SDoc
pprWarningTxtForMsg (WarningTxt _ ws)
= doubleQuotes (vcat (map (ftext . sl_fs . unLoc) ws))
pprWarningTxtForMsg (DeprecatedTxt _ ds)
= text "Deprecated:" <+>
doubleQuotes (vcat (map (ftext . sl_fs . unLoc) ds))
{-
************************************************************************
* *
Rules
* *
************************************************************************
-}
type RuleName = FastString
pprRuleName :: RuleName -> SDoc
pprRuleName rn = doubleQuotes (ftext rn)
{-
************************************************************************
* *
\subsection[Fixity]{Fixity info}
* *
************************************************************************
-}
------------------------
data Fixity = Fixity SourceText Int FixityDirection
-- Note [Pragma source text]
deriving Data
instance Outputable Fixity where
ppr (Fixity _ prec dir) = hcat [ppr dir, space, int prec]
instance Eq Fixity where -- Used to determine if two fixities conflict
(Fixity _ p1 dir1) == (Fixity _ p2 dir2) = p1==p2 && dir1 == dir2
------------------------
data FixityDirection = InfixL | InfixR | InfixN
deriving (Eq, Data)
instance Outputable FixityDirection where
ppr InfixL = text "infixl"
ppr InfixR = text "infixr"
ppr InfixN = text "infix"
------------------------
maxPrecedence, minPrecedence :: Int
maxPrecedence = 9
minPrecedence = 0
defaultFixity :: Fixity
defaultFixity = Fixity NoSourceText maxPrecedence InfixL
negateFixity, funTyFixity :: Fixity
-- Wired-in fixities
negateFixity = Fixity NoSourceText 6 InfixL -- Fixity of unary negate
funTyFixity = Fixity NoSourceText (-1) InfixR -- Fixity of '->', see #15235
{-
Consider
\begin{verbatim}
a `op1` b `op2` c
\end{verbatim}
@(compareFixity op1 op2)@ tells which way to arrange application, or
whether there's an error.
-}
compareFixity :: Fixity -> Fixity
-> (Bool, -- Error please
Bool) -- Associate to the right: a op1 (b op2 c)
compareFixity (Fixity _ prec1 dir1) (Fixity _ prec2 dir2)
= case prec1 `compare` prec2 of
GT -> left
LT -> right
EQ -> case (dir1, dir2) of
(InfixR, InfixR) -> right
(InfixL, InfixL) -> left
_ -> error_please
where
right = (False, True)
left = (False, False)
error_please = (True, False)
-- |Captures the fixity of declarations as they are parsed. This is not
-- necessarily the same as the fixity declaration, as the normal fixity may be
-- overridden using parens or backticks.
data LexicalFixity = Prefix | Infix deriving (Data,Eq)
instance Outputable LexicalFixity where
ppr Prefix = text "Prefix"
ppr Infix = text "Infix"
{-
************************************************************************
* *
\subsection[Top-level/local]{Top-level/not-top level flag}
* *
************************************************************************
-}
data TopLevelFlag
= TopLevel
| NotTopLevel
isTopLevel, isNotTopLevel :: TopLevelFlag -> Bool
isNotTopLevel NotTopLevel = True
isNotTopLevel TopLevel = False
isTopLevel TopLevel = True
isTopLevel NotTopLevel = False
instance Outputable TopLevelFlag where
ppr TopLevel = text "<TopLevel>"
ppr NotTopLevel = text "<NotTopLevel>"
{-
************************************************************************
* *
Boxity flag
* *
************************************************************************
-}
data Boxity
= Boxed
| Unboxed
deriving( Eq, Data )
isBoxed :: Boxity -> Bool
isBoxed Boxed = True
isBoxed Unboxed = False
instance Outputable Boxity where
ppr Boxed = text "Boxed"
ppr Unboxed = text "Unboxed"
{-
************************************************************************
* *
Recursive/Non-Recursive flag
* *
************************************************************************
-}
-- | Recursivity Flag
data RecFlag = Recursive
| NonRecursive
deriving( Eq, Data )
isRec :: RecFlag -> Bool
isRec Recursive = True
isRec NonRecursive = False
isNonRec :: RecFlag -> Bool
isNonRec Recursive = False
isNonRec NonRecursive = True
boolToRecFlag :: Bool -> RecFlag
boolToRecFlag True = Recursive
boolToRecFlag False = NonRecursive
instance Outputable RecFlag where
ppr Recursive = text "Recursive"
ppr NonRecursive = text "NonRecursive"
{-
************************************************************************
* *
Code origin
* *
************************************************************************
-}
data Origin = FromSource
| Generated
deriving( Eq, Data )
isGenerated :: Origin -> Bool
isGenerated Generated = True
isGenerated FromSource = False
instance Outputable Origin where
ppr FromSource = text "FromSource"
ppr Generated = text "Generated"
{-
************************************************************************
* *
Instance overlap flag
* *
************************************************************************
-}
-- | The semantics allowed for overlapping instances for a particular
-- instance. See Note [Safe Haskell isSafeOverlap] (in `InstEnv.hs`) for a
-- explanation of the `isSafeOverlap` field.
--
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnOpen' @'\{-\# OVERLAPPABLE'@ or
-- @'\{-\# OVERLAPPING'@ or
-- @'\{-\# OVERLAPS'@ or
-- @'\{-\# INCOHERENT'@,
-- 'ApiAnnotation.AnnClose' @`\#-\}`@,
-- For details on above see note [Api annotations] in GHC.Parser.Annotation
data OverlapFlag = OverlapFlag
{ overlapMode :: OverlapMode
, isSafeOverlap :: Bool
} deriving (Eq, Data)
setOverlapModeMaybe :: OverlapFlag -> Maybe OverlapMode -> OverlapFlag
setOverlapModeMaybe f Nothing = f
setOverlapModeMaybe f (Just m) = f { overlapMode = m }
hasIncoherentFlag :: OverlapMode -> Bool
hasIncoherentFlag mode =
case mode of
Incoherent _ -> True
_ -> False
hasOverlappableFlag :: OverlapMode -> Bool
hasOverlappableFlag mode =
case mode of
Overlappable _ -> True
Overlaps _ -> True
Incoherent _ -> True
_ -> False
hasOverlappingFlag :: OverlapMode -> Bool
hasOverlappingFlag mode =
case mode of
Overlapping _ -> True
Overlaps _ -> True
Incoherent _ -> True
_ -> False
data OverlapMode -- See Note [Rules for instance lookup] in GHC.Core.InstEnv
= NoOverlap SourceText
-- See Note [Pragma source text]
-- ^ This instance must not overlap another `NoOverlap` instance.
-- However, it may be overlapped by `Overlapping` instances,
-- and it may overlap `Overlappable` instances.
| Overlappable SourceText
-- See Note [Pragma source text]
-- ^ Silently ignore this instance if you find a
-- more specific one that matches the constraint
-- you are trying to resolve
--
-- Example: constraint (Foo [Int])
-- instance Foo [Int]
-- instance {-# OVERLAPPABLE #-} Foo [a]
--
-- Since the second instance has the Overlappable flag,
-- the first instance will be chosen (otherwise
-- its ambiguous which to choose)
| Overlapping SourceText
-- See Note [Pragma source text]
-- ^ Silently ignore any more general instances that may be
-- used to solve the constraint.
--
-- Example: constraint (Foo [Int])
-- instance {-# OVERLAPPING #-} Foo [Int]
-- instance Foo [a]
--
-- Since the first instance has the Overlapping flag,
-- the second---more general---instance will be ignored (otherwise
-- it is ambiguous which to choose)
| Overlaps SourceText
-- See Note [Pragma source text]
-- ^ Equivalent to having both `Overlapping` and `Overlappable` flags.
| Incoherent SourceText
-- See Note [Pragma source text]
-- ^ Behave like Overlappable and Overlapping, and in addition pick
-- an an arbitrary one if there are multiple matching candidates, and
-- don't worry about later instantiation
--
-- Example: constraint (Foo [b])
-- instance {-# INCOHERENT -} Foo [Int]
-- instance Foo [a]
-- Without the Incoherent flag, we'd complain that
-- instantiating 'b' would change which instance
-- was chosen. See also note [Incoherent instances] in GHC.Core.InstEnv
deriving (Eq, Data)
instance Outputable OverlapFlag where
ppr flag = ppr (overlapMode flag) <+> pprSafeOverlap (isSafeOverlap flag)
instance Outputable OverlapMode where
ppr (NoOverlap _) = empty
ppr (Overlappable _) = text "[overlappable]"
ppr (Overlapping _) = text "[overlapping]"
ppr (Overlaps _) = text "[overlap ok]"
ppr (Incoherent _) = text "[incoherent]"
pprSafeOverlap :: Bool -> SDoc
pprSafeOverlap True = text "[safe]"
pprSafeOverlap False = empty
{-
************************************************************************
* *
Precedence
* *
************************************************************************
-}
-- | A general-purpose pretty-printing precedence type.
newtype PprPrec = PprPrec Int deriving (Eq, Ord, Show)
-- See Note [Precedence in types]
topPrec, sigPrec, funPrec, opPrec, starPrec, appPrec :: PprPrec
topPrec = PprPrec 0 -- No parens
sigPrec = PprPrec 1 -- Explicit type signatures
funPrec = PprPrec 2 -- Function args; no parens for constructor apps
-- See [Type operator precedence] for why both
-- funPrec and opPrec exist.
opPrec = PprPrec 2 -- Infix operator
starPrec = PprPrec 3 -- Star syntax for the type of types, i.e. the * in (* -> *)
-- See Note [Star kind precedence]
appPrec = PprPrec 4 -- Constructor args; no parens for atomic
maybeParen :: PprPrec -> PprPrec -> SDoc -> SDoc
maybeParen ctxt_prec inner_prec pretty
| ctxt_prec < inner_prec = pretty
| otherwise = parens pretty
{- Note [Precedence in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Many pretty-printing functions have type
ppr_ty :: PprPrec -> Type -> SDoc
The PprPrec gives the binding strength of the context. For example, in
T ty1 ty2
we will pretty-print 'ty1' and 'ty2' with the call
(ppr_ty appPrec ty)
to indicate that the context is that of an argument of a TyConApp.
We use this consistently for Type and HsType.
Note [Type operator precedence]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't keep the fixity of type operators in the operator. So the
pretty printer follows the following precedence order:
TyConPrec Type constructor application
TyOpPrec/FunPrec Operator application and function arrow
We have funPrec and opPrec to represent the precedence of function
arrow and type operators respectively, but currently we implement
funPrec == opPrec, so that we don't distinguish the two. Reason:
it's hard to parse a type like
a ~ b => c * d -> e - f
By treating opPrec = funPrec we end up with more parens
(a ~ b) => (c * d) -> (e - f)
But the two are different constructors of PprPrec so we could make
(->) bind more or less tightly if we wanted.
Note [Star kind precedence]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
We parenthesize the (*) kind to avoid two issues:
1. Printing invalid or incorrect code.
For example, instead of type F @(*) x = x
GHC used to print type F @* x = x
However, (@*) is a type operator, not a kind application.
2. Printing kinds that are correct but hard to read.
Should Either * Int be read as Either (*) Int
or as (*) Either Int ?
This depends on whether -XStarIsType is enabled, but it would be
easier if we didn't have to check for the flag when reading the code.
At the same time, we cannot parenthesize (*) blindly.
Consider this Haskell98 kind: ((* -> *) -> *) -> *
With parentheses, it is less readable: (((*) -> (*)) -> (*)) -> (*)
The solution is to assign a special precedence to (*), 'starPrec', which is
higher than 'funPrec' but lower than 'appPrec':
F * * * becomes F (*) (*) (*)
F A * B becomes F A (*) B
Proxy * becomes Proxy (*)
a * -> * becomes a (*) -> *
-}
{-
************************************************************************
* *
Tuples
* *
************************************************************************
-}
data TupleSort
= BoxedTuple
| UnboxedTuple
| ConstraintTuple
deriving( Eq, Data )
instance Outputable TupleSort where
ppr ts = text $
case ts of
BoxedTuple -> "BoxedTuple"
UnboxedTuple -> "UnboxedTuple"
ConstraintTuple -> "ConstraintTuple"
tupleSortBoxity :: TupleSort -> Boxity
tupleSortBoxity BoxedTuple = Boxed
tupleSortBoxity UnboxedTuple = Unboxed
tupleSortBoxity ConstraintTuple = Boxed
boxityTupleSort :: Boxity -> TupleSort
boxityTupleSort Boxed = BoxedTuple
boxityTupleSort Unboxed = UnboxedTuple
tupleParens :: TupleSort -> SDoc -> SDoc
tupleParens BoxedTuple p = parens p
tupleParens UnboxedTuple p = text "(#" <+> p <+> ptext (sLit "#)")
tupleParens ConstraintTuple p -- In debug-style write (% Eq a, Ord b %)
= ifPprDebug (text "(%" <+> p <+> ptext (sLit "%)"))
(parens p)
{-
************************************************************************
* *
Sums
* *
************************************************************************
-}
sumParens :: SDoc -> SDoc
sumParens p = ptext (sLit "(#") <+> p <+> ptext (sLit "#)")
-- | Pretty print an alternative in an unboxed sum e.g. "| a | |".
pprAlternative :: (a -> SDoc) -- ^ The pretty printing function to use
-> a -- ^ The things to be pretty printed
-> ConTag -- ^ Alternative (one-based)
-> Arity -- ^ Arity
-> SDoc -- ^ 'SDoc' where the alternative havs been pretty
-- printed and finally packed into a paragraph.
pprAlternative pp x alt arity =
fsep (replicate (alt - 1) vbar ++ [pp x] ++ replicate (arity - alt) vbar)
{-
************************************************************************
* *
\subsection[Generic]{Generic flag}
* *
************************************************************************
This is the "Embedding-Projection pair" datatype, it contains
two pieces of code (normally either RenamedExpr's or Id's)
If we have a such a pair (EP from to), the idea is that 'from' and 'to'
represents functions of type
from :: T -> Tring
to :: Tring -> T
And we should have
to (from x) = x
T and Tring are arbitrary, but typically T is the 'main' type while
Tring is the 'representation' type. (This just helps us remember
whether to use 'from' or 'to'.
-}
-- | Embedding Projection pair
data EP a = EP { fromEP :: a, -- :: T -> Tring
toEP :: a } -- :: Tring -> T
{-
Embedding-projection pairs are used in several places:
First of all, each type constructor has an EP associated with it, the
code in EP converts (datatype T) from T to Tring and back again.
Secondly, when we are filling in Generic methods (in the typechecker,
tcMethodBinds), we are constructing bimaps by induction on the structure
of the type of the method signature.
************************************************************************
* *
\subsection{Occurrence information}
* *
************************************************************************
This data type is used exclusively by the simplifier, but it appears in a
SubstResult, which is currently defined in GHC.Types.Var.Env, which is pretty
near the base of the module hierarchy. So it seemed simpler to put the defn of
OccInfo here, safely at the bottom
-}
-- | identifier Occurrence Information
data OccInfo
= ManyOccs { occ_tail :: !TailCallInfo }
-- ^ There are many occurrences, or unknown occurrences
| IAmDead -- ^ Marks unused variables. Sometimes useful for
-- lambda and case-bound variables.
| OneOcc { occ_in_lam :: !InsideLam
, occ_one_br :: !OneBranch
, occ_int_cxt :: !InterestingCxt
, occ_tail :: !TailCallInfo }
-- ^ Occurs exactly once (per branch), not inside a rule
-- | This identifier breaks a loop of mutually recursive functions. The field
-- marks whether it is only a loop breaker due to a reference in a rule
| IAmALoopBreaker { occ_rules_only :: !RulesOnly
, occ_tail :: !TailCallInfo }
-- Note [LoopBreaker OccInfo]
deriving (Eq)
type RulesOnly = Bool
{-
Note [LoopBreaker OccInfo]
~~~~~~~~~~~~~~~~~~~~~~~~~~
IAmALoopBreaker True <=> A "weak" or rules-only loop breaker
Do not preInlineUnconditionally
IAmALoopBreaker False <=> A "strong" loop breaker
Do not inline at all
See OccurAnal Note [Weak loop breakers]
-}
noOccInfo :: OccInfo
noOccInfo = ManyOccs { occ_tail = NoTailCallInfo }
isNoOccInfo :: OccInfo -> Bool
isNoOccInfo ManyOccs { occ_tail = NoTailCallInfo } = True
isNoOccInfo _ = False
isManyOccs :: OccInfo -> Bool
isManyOccs ManyOccs{} = True
isManyOccs _ = False
seqOccInfo :: OccInfo -> ()
seqOccInfo occ = occ `seq` ()
-----------------
-- | Interesting Context
data InterestingCxt
= IsInteresting
-- ^ Function: is applied
-- Data value: scrutinised by a case with at least one non-DEFAULT branch
| NotInteresting
deriving (Eq)
-- | If there is any 'interesting' identifier occurrence, then the
-- aggregated occurrence info of that identifier is considered interesting.
instance Semi.Semigroup InterestingCxt where
NotInteresting <> x = x
IsInteresting <> _ = IsInteresting
instance Monoid InterestingCxt where
mempty = NotInteresting
mappend = (Semi.<>)
-----------------
-- | Inside Lambda
data InsideLam
= IsInsideLam
-- ^ Occurs inside a non-linear lambda
-- Substituting a redex for this occurrence is
-- dangerous because it might duplicate work.
| NotInsideLam
deriving (Eq)
-- | If any occurrence of an identifier is inside a lambda, then the
-- occurrence info of that identifier marks it as occurring inside a lambda
instance Semi.Semigroup InsideLam where
NotInsideLam <> x = x
IsInsideLam <> _ = IsInsideLam
instance Monoid InsideLam where
mempty = NotInsideLam
mappend = (Semi.<>)
-----------------
data OneBranch
= InOneBranch
-- ^ One syntactic occurrence: Occurs in only one case branch
-- so no code-duplication issue to worry about
| MultipleBranches
deriving (Eq)
-----------------
data TailCallInfo = AlwaysTailCalled JoinArity -- See Note [TailCallInfo]
| NoTailCallInfo
deriving (Eq)
tailCallInfo :: OccInfo -> TailCallInfo
tailCallInfo IAmDead = NoTailCallInfo
tailCallInfo other = occ_tail other
zapOccTailCallInfo :: OccInfo -> OccInfo
zapOccTailCallInfo IAmDead = IAmDead
zapOccTailCallInfo occ = occ { occ_tail = NoTailCallInfo }
isAlwaysTailCalled :: OccInfo -> Bool
isAlwaysTailCalled occ
= case tailCallInfo occ of AlwaysTailCalled{} -> True
NoTailCallInfo -> False
instance Outputable TailCallInfo where
ppr (AlwaysTailCalled ar) = sep [ text "Tail", int ar ]
ppr _ = empty
-----------------
strongLoopBreaker, weakLoopBreaker :: OccInfo
strongLoopBreaker = IAmALoopBreaker False NoTailCallInfo
weakLoopBreaker = IAmALoopBreaker True NoTailCallInfo
isWeakLoopBreaker :: OccInfo -> Bool
isWeakLoopBreaker (IAmALoopBreaker{}) = True
isWeakLoopBreaker _ = False
isStrongLoopBreaker :: OccInfo -> Bool
isStrongLoopBreaker (IAmALoopBreaker { occ_rules_only = False }) = True
-- Loop-breaker that breaks a non-rule cycle
isStrongLoopBreaker _ = False
isDeadOcc :: OccInfo -> Bool
isDeadOcc IAmDead = True
isDeadOcc _ = False
isOneOcc :: OccInfo -> Bool
isOneOcc (OneOcc {}) = True
isOneOcc _ = False
zapFragileOcc :: OccInfo -> OccInfo
-- Keep only the most robust data: deadness, loop-breaker-hood
zapFragileOcc (OneOcc {}) = noOccInfo
zapFragileOcc occ = zapOccTailCallInfo occ
instance Outputable OccInfo where
-- only used for debugging; never parsed. KSW 1999-07
ppr (ManyOccs tails) = pprShortTailCallInfo tails
ppr IAmDead = text "Dead"
ppr (IAmALoopBreaker rule_only tails)
= text "LoopBreaker" <> pp_ro <> pprShortTailCallInfo tails
where
pp_ro | rule_only = char '!'
| otherwise = empty
ppr (OneOcc inside_lam one_branch int_cxt tail_info)
= text "Once" <> pp_lam inside_lam <> pp_br one_branch <> pp_args int_cxt <> pp_tail
where
pp_lam IsInsideLam = char 'L'
pp_lam NotInsideLam = empty
pp_br MultipleBranches = char '*'
pp_br InOneBranch = empty
pp_args IsInteresting = char '!'
pp_args NotInteresting = empty
pp_tail = pprShortTailCallInfo tail_info
pprShortTailCallInfo :: TailCallInfo -> SDoc
pprShortTailCallInfo (AlwaysTailCalled ar) = char 'T' <> brackets (int ar)
pprShortTailCallInfo NoTailCallInfo = empty
{-
Note [TailCallInfo]
~~~~~~~~~~~~~~~~~~~
The occurrence analyser determines what can be made into a join point, but it
doesn't change the binder into a JoinId because then it would be inconsistent
with the occurrences. Thus it's left to the simplifier (or to simpleOptExpr) to
change the IdDetails.
The AlwaysTailCalled marker actually means slightly more than simply that the
function is always tail-called. See Note [Invariants on join points].
This info is quite fragile and should not be relied upon unless the occurrence
analyser has *just* run. Use 'Id.isJoinId_maybe' for the permanent state of
the join-point-hood of a binder; a join id itself will not be marked
AlwaysTailCalled.
Note that there is a 'TailCallInfo' on a 'ManyOccs' value. One might expect that
being tail-called would mean that the variable could only appear once per branch
(thus getting a `OneOcc { occ_one_br = True }` occurrence info), but a join
point can also be invoked from other join points, not just from case branches:
let j1 x = ...
j2 y = ... j1 z {- tail call -} ...
in case w of
A -> j1 v
B -> j2 u
C -> j2 q
Here both 'j1' and 'j2' will get marked AlwaysTailCalled, but j1 will get
ManyOccs and j2 will get `OneOcc { occ_one_br = True }`.
************************************************************************
* *
Default method specification
* *
************************************************************************
The DefMethSpec enumeration just indicates what sort of default method
is used for a class. It is generated from source code, and present in
interface files; it is converted to Class.DefMethInfo before begin put in a
Class object.
-}
-- | Default Method Specification
data DefMethSpec ty
= VanillaDM -- Default method given with polymorphic code
| GenericDM ty -- Default method given with code of this type
instance Outputable (DefMethSpec ty) where
ppr VanillaDM = text "{- Has default method -}"
ppr (GenericDM {}) = text "{- Has generic default method -}"
{-
************************************************************************
* *
\subsection{Success flag}
* *
************************************************************************
-}
data SuccessFlag = Succeeded | Failed
instance Outputable SuccessFlag where
ppr Succeeded = text "Succeeded"
ppr Failed = text "Failed"
successIf :: Bool -> SuccessFlag
successIf True = Succeeded
successIf False = Failed
succeeded, failed :: SuccessFlag -> Bool
succeeded Succeeded = True
succeeded Failed = False
failed Succeeded = False
failed Failed = True
{-
************************************************************************
* *
\subsection{Source Text}
* *
************************************************************************
Keeping Source Text for source to source conversions
Note [Pragma source text]
~~~~~~~~~~~~~~~~~~~~~~~~~
The lexer does a case-insensitive match for pragmas, as well as
accepting both UK and US spelling variants.
So
{-# SPECIALISE #-}
{-# SPECIALIZE #-}
{-# Specialize #-}
will all generate ITspec_prag token for the start of the pragma.
In order to be able to do source to source conversions, the original
source text for the token needs to be preserved, hence the
`SourceText` field.
So the lexer will then generate
ITspec_prag "{ -# SPECIALISE"
ITspec_prag "{ -# SPECIALIZE"
ITspec_prag "{ -# Specialize"
for the cases above.
[without the space between '{' and '-', otherwise this comment won't parse]
Note [Literal source text]
~~~~~~~~~~~~~~~~~~~~~~~~~~
The lexer/parser converts literals from their original source text
versions to an appropriate internal representation. This is a problem
for tools doing source to source conversions, so the original source
text is stored in literals where this can occur.
Motivating examples for HsLit
HsChar '\n' == '\x20`
HsCharPrim '\x41`# == `A`
HsString "\x20\x41" == " A"
HsStringPrim "\x20"# == " "#
HsInt 001 == 1
HsIntPrim 002# == 2#
HsWordPrim 003## == 3##
HsInt64Prim 004## == 4##
HsWord64Prim 005## == 5##
HsInteger 006 == 6
For OverLitVal
HsIntegral 003 == 0x003
HsIsString "\x41nd" == "And"
-}
-- Note [Literal source text],[Pragma source text]
data SourceText = SourceText String
| NoSourceText -- ^ For when code is generated, e.g. TH,
-- deriving. The pretty printer will then make
-- its own representation of the item.
deriving (Data, Show, Eq )
instance Outputable SourceText where
ppr (SourceText s) = text "SourceText" <+> text s
ppr NoSourceText = text "NoSourceText"
-- | Special combinator for showing string literals.
pprWithSourceText :: SourceText -> SDoc -> SDoc
pprWithSourceText NoSourceText d = d
pprWithSourceText (SourceText src) _ = text src
{-
************************************************************************
* *
\subsection{Activation}
* *
************************************************************************
When a rule or inlining is active
-}
-- | Phase Number
type PhaseNum = Int -- Compilation phase
-- Phases decrease towards zero
-- Zero is the last phase
data CompilerPhase
= Phase PhaseNum
| InitialPhase -- The first phase -- number = infinity!
instance Outputable CompilerPhase where
ppr (Phase n) = int n
ppr InitialPhase = text "InitialPhase"
activeAfterInitial :: Activation
-- Active in the first phase after the initial phase
-- Currently we have just phases [2,1,0]
activeAfterInitial = ActiveAfter NoSourceText 2
activeDuringFinal :: Activation
-- Active in the final simplification phase (which is repeated)
activeDuringFinal = ActiveAfter NoSourceText 0
-- See note [Pragma source text]
data Activation = NeverActive
| AlwaysActive
| ActiveBefore SourceText PhaseNum
-- Active only *strictly before* this phase
| ActiveAfter SourceText PhaseNum
-- Active in this phase and later
deriving( Eq, Data )
-- Eq used in comparing rules in GHC.Hs.Decls
-- | Rule Match Information
data RuleMatchInfo = ConLike -- See Note [CONLIKE pragma]
| FunLike
deriving( Eq, Data, Show )
-- Show needed for GHC.Parser.Lexer
data InlinePragma -- Note [InlinePragma]
= InlinePragma
{ inl_src :: SourceText -- Note [Pragma source text]
, inl_inline :: InlineSpec -- See Note [inl_inline and inl_act]
, inl_sat :: Maybe Arity -- Just n <=> Inline only when applied to n
-- explicit (non-type, non-dictionary) args
-- That is, inl_sat describes the number of *source-code*
-- arguments the thing must be applied to. We add on the
-- number of implicit, dictionary arguments when making
-- the Unfolding, and don't look at inl_sat further
, inl_act :: Activation -- Says during which phases inlining is allowed
-- See Note [inl_inline and inl_act]
, inl_rule :: RuleMatchInfo -- Should the function be treated like a constructor?
} deriving( Eq, Data )
-- | Inline Specification
data InlineSpec -- What the user's INLINE pragma looked like
= Inline -- User wrote INLINE
| Inlinable -- User wrote INLINABLE
| NoInline -- User wrote NOINLINE
| NoUserInline -- User did not write any of INLINE/INLINABLE/NOINLINE
-- e.g. in `defaultInlinePragma` or when created by CSE
deriving( Eq, Data, Show )
-- Show needed for GHC.Parser.Lexer
{- Note [InlinePragma]
~~~~~~~~~~~~~~~~~~~~~~
This data type mirrors what you can write in an INLINE or NOINLINE pragma in
the source program.
If you write nothing at all, you get defaultInlinePragma:
inl_inline = NoUserInline
inl_act = AlwaysActive
inl_rule = FunLike
It's not possible to get that combination by *writing* something, so
if an Id has defaultInlinePragma it means the user didn't specify anything.
If inl_inline = Inline or Inlineable, then the Id should have an InlineRule unfolding.
If you want to know where InlinePragmas take effect: Look in GHC.HsToCore.Binds.makeCorePair
Note [inl_inline and inl_act]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* inl_inline says what the user wrote: did she say INLINE, NOINLINE,
INLINABLE, or nothing at all
* inl_act says in what phases the unfolding is active or inactive
E.g If you write INLINE[1] then inl_act will be set to ActiveAfter 1
If you write NOINLINE[1] then inl_act will be set to ActiveBefore 1
If you write NOINLINE[~1] then inl_act will be set to ActiveAfter 1
So note that inl_act does not say what pragma you wrote: it just
expresses its consequences
* inl_act just says when the unfolding is active; it doesn't say what
to inline. If you say INLINE f, then f's inl_act will be AlwaysActive,
but in addition f will get a "stable unfolding" with UnfoldingGuidance
that tells the inliner to be pretty eager about it.
Note [CONLIKE pragma]
~~~~~~~~~~~~~~~~~~~~~
The ConLike constructor of a RuleMatchInfo is aimed at the following.
Consider first
{-# RULE "r/cons" forall a as. r (a:as) = f (a+1) #-}
g b bs = let x = b:bs in ..x...x...(r x)...
Now, the rule applies to the (r x) term, because GHC "looks through"
the definition of 'x' to see that it is (b:bs).
Now consider
{-# RULE "r/f" forall v. r (f v) = f (v+1) #-}
g v = let x = f v in ..x...x...(r x)...
Normally the (r x) would *not* match the rule, because GHC would be
scared about duplicating the redex (f v), so it does not "look
through" the bindings.
However the CONLIKE modifier says to treat 'f' like a constructor in
this situation, and "look through" the unfolding for x. So (r x)
fires, yielding (f (v+1)).
This is all controlled with a user-visible pragma:
{-# NOINLINE CONLIKE [1] f #-}
The main effects of CONLIKE are:
- The occurrence analyser (OccAnal) and simplifier (Simplify) treat
CONLIKE thing like constructors, by ANF-ing them
- New function GHC.Core.Utils.exprIsExpandable is like exprIsCheap, but
additionally spots applications of CONLIKE functions
- A CoreUnfolding has a field that caches exprIsExpandable
- The rule matcher consults this field. See
Note [Expanding variables] in GHC.Core.Rules.
-}
isConLike :: RuleMatchInfo -> Bool
isConLike ConLike = True
isConLike _ = False
isFunLike :: RuleMatchInfo -> Bool
isFunLike FunLike = True
isFunLike _ = False
noUserInlineSpec :: InlineSpec -> Bool
noUserInlineSpec NoUserInline = True
noUserInlineSpec _ = False
defaultInlinePragma, alwaysInlinePragma, neverInlinePragma, dfunInlinePragma
:: InlinePragma
defaultInlinePragma = InlinePragma { inl_src = SourceText "{-# INLINE"
, inl_act = AlwaysActive
, inl_rule = FunLike
, inl_inline = NoUserInline
, inl_sat = Nothing }
alwaysInlinePragma = defaultInlinePragma { inl_inline = Inline }
neverInlinePragma = defaultInlinePragma { inl_act = NeverActive }
inlinePragmaSpec :: InlinePragma -> InlineSpec
inlinePragmaSpec = inl_inline
-- A DFun has an always-active inline activation so that
-- exprIsConApp_maybe can "see" its unfolding
-- (However, its actual Unfolding is a DFunUnfolding, which is
-- never inlined other than via exprIsConApp_maybe.)
dfunInlinePragma = defaultInlinePragma { inl_act = AlwaysActive
, inl_rule = ConLike }
isDefaultInlinePragma :: InlinePragma -> Bool
isDefaultInlinePragma (InlinePragma { inl_act = activation
, inl_rule = match_info
, inl_inline = inline })
= noUserInlineSpec inline && isAlwaysActive activation && isFunLike match_info
isInlinePragma :: InlinePragma -> Bool
isInlinePragma prag = case inl_inline prag of
Inline -> True
_ -> False
isInlinablePragma :: InlinePragma -> Bool
isInlinablePragma prag = case inl_inline prag of
Inlinable -> True
_ -> False
isAnyInlinePragma :: InlinePragma -> Bool
-- INLINE or INLINABLE
isAnyInlinePragma prag = case inl_inline prag of
Inline -> True
Inlinable -> True
_ -> False
inlinePragmaSat :: InlinePragma -> Maybe Arity
inlinePragmaSat = inl_sat
inlinePragmaActivation :: InlinePragma -> Activation
inlinePragmaActivation (InlinePragma { inl_act = activation }) = activation
inlinePragmaRuleMatchInfo :: InlinePragma -> RuleMatchInfo
inlinePragmaRuleMatchInfo (InlinePragma { inl_rule = info }) = info
setInlinePragmaActivation :: InlinePragma -> Activation -> InlinePragma
setInlinePragmaActivation prag activation = prag { inl_act = activation }
setInlinePragmaRuleMatchInfo :: InlinePragma -> RuleMatchInfo -> InlinePragma
setInlinePragmaRuleMatchInfo prag info = prag { inl_rule = info }
instance Outputable Activation where
ppr AlwaysActive = empty
ppr NeverActive = brackets (text "~")
ppr (ActiveBefore _ n) = brackets (char '~' <> int n)
ppr (ActiveAfter _ n) = brackets (int n)
instance Outputable RuleMatchInfo where
ppr ConLike = text "CONLIKE"
ppr FunLike = text "FUNLIKE"
instance Outputable InlineSpec where
ppr Inline = text "INLINE"
ppr NoInline = text "NOINLINE"
ppr Inlinable = text "INLINABLE"
ppr NoUserInline = text "NOUSERINLINE" -- what is better?
instance Outputable InlinePragma where
ppr = pprInline
pprInline :: InlinePragma -> SDoc
pprInline = pprInline' True
pprInlineDebug :: InlinePragma -> SDoc
pprInlineDebug = pprInline' False
pprInline' :: Bool -- True <=> do not display the inl_inline field
-> InlinePragma
-> SDoc
pprInline' emptyInline (InlinePragma { inl_inline = inline, inl_act = activation
, inl_rule = info, inl_sat = mb_arity })
= pp_inl inline <> pp_act inline activation <+> pp_sat <+> pp_info
where
pp_inl x = if emptyInline then empty else ppr x
pp_act Inline AlwaysActive = empty
pp_act NoInline NeverActive = empty
pp_act _ act = ppr act
pp_sat | Just ar <- mb_arity = parens (text "sat-args=" <> int ar)
| otherwise = empty
pp_info | isFunLike info = empty
| otherwise = ppr info
isActive :: CompilerPhase -> Activation -> Bool
isActive InitialPhase AlwaysActive = True
isActive InitialPhase (ActiveBefore {}) = True
isActive InitialPhase _ = False
isActive (Phase p) act = isActiveIn p act
isActiveIn :: PhaseNum -> Activation -> Bool
isActiveIn _ NeverActive = False
isActiveIn _ AlwaysActive = True
isActiveIn p (ActiveAfter _ n) = p <= n
isActiveIn p (ActiveBefore _ n) = p > n
competesWith :: Activation -> Activation -> Bool
-- See Note [Activation competition]
competesWith NeverActive _ = False
competesWith _ NeverActive = False
competesWith AlwaysActive _ = True
competesWith (ActiveBefore {}) AlwaysActive = True
competesWith (ActiveBefore {}) (ActiveBefore {}) = True
competesWith (ActiveBefore _ a) (ActiveAfter _ b) = a < b
competesWith (ActiveAfter {}) AlwaysActive = False
competesWith (ActiveAfter {}) (ActiveBefore {}) = False
competesWith (ActiveAfter _ a) (ActiveAfter _ b) = a >= b
{- Note [Competing activations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes a RULE and an inlining may compete, or two RULES.
See Note [Rules and inlining/other rules] in GHC.HsToCore.
We say that act1 "competes with" act2 iff
act1 is active in the phase when act2 *becomes* active
NB: remember that phases count *down*: 2, 1, 0!
It's too conservative to ensure that the two are never simultaneously
active. For example, a rule might be always active, and an inlining
might switch on in phase 2. We could switch off the rule, but it does
no harm.
-}
isNeverActive, isAlwaysActive, isEarlyActive :: Activation -> Bool
isNeverActive NeverActive = True
isNeverActive _ = False
isAlwaysActive AlwaysActive = True
isAlwaysActive _ = False
isEarlyActive AlwaysActive = True
isEarlyActive (ActiveBefore {}) = True
isEarlyActive _ = False
-- | Integral Literal
--
-- Used (instead of Integer) to represent negative zegative zero which is
-- required for NegativeLiterals extension to correctly parse `-0::Double`
-- as negative zero. See also #13211.
data IntegralLit
= IL { il_text :: SourceText
, il_neg :: Bool -- See Note [Negative zero]
, il_value :: Integer
}
deriving (Data, Show)
mkIntegralLit :: Integral a => a -> IntegralLit
mkIntegralLit i = IL { il_text = SourceText (show i_integer)
, il_neg = i < 0
, il_value = i_integer }
where
i_integer :: Integer
i_integer = toInteger i
negateIntegralLit :: IntegralLit -> IntegralLit
negateIntegralLit (IL text neg value)
= case text of
SourceText ('-':src) -> IL (SourceText src) False (negate value)
SourceText src -> IL (SourceText ('-':src)) True (negate value)
NoSourceText -> IL NoSourceText (not neg) (negate value)
-- | Fractional Literal
--
-- Used (instead of Rational) to represent exactly the floating point literal that we
-- encountered in the user's source program. This allows us to pretty-print exactly what
-- the user wrote, which is important e.g. for floating point numbers that can't represented
-- as Doubles (we used to via Double for pretty-printing). See also #2245.
data FractionalLit
= FL { fl_text :: SourceText -- How the value was written in the source
, fl_neg :: Bool -- See Note [Negative zero]
, fl_value :: Rational -- Numeric value of the literal
}
deriving (Data, Show)
-- The Show instance is required for the derived GHC.Parser.Lexer.Token instance when DEBUG is on
mkFractionalLit :: Real a => a -> FractionalLit
mkFractionalLit r = FL { fl_text = SourceText (show (realToFrac r::Double))
-- Converting to a Double here may technically lose
-- precision (see #15502). We could alternatively
-- convert to a Rational for the most accuracy, but
-- it would cause Floats and Doubles to be displayed
-- strangely, so we opt not to do this. (In contrast
-- to mkIntegralLit, where we always convert to an
-- Integer for the highest accuracy.)
, fl_neg = r < 0
, fl_value = toRational r }
negateFractionalLit :: FractionalLit -> FractionalLit
negateFractionalLit (FL text neg value)
= case text of
SourceText ('-':src) -> FL (SourceText src) False value
SourceText src -> FL (SourceText ('-':src)) True value
NoSourceText -> FL NoSourceText (not neg) (negate value)
integralFractionalLit :: Bool -> Integer -> FractionalLit
integralFractionalLit neg i = FL { fl_text = SourceText (show i),
fl_neg = neg,
fl_value = fromInteger i }
-- Comparison operations are needed when grouping literals
-- for compiling pattern-matching (module GHC.HsToCore.Match.Literal)
instance Eq IntegralLit where
(==) = (==) `on` il_value
instance Ord IntegralLit where
compare = compare `on` il_value
instance Outputable IntegralLit where
ppr (IL (SourceText src) _ _) = text src
ppr (IL NoSourceText _ value) = text (show value)
instance Eq FractionalLit where
(==) = (==) `on` fl_value
instance Ord FractionalLit where
compare = compare `on` fl_value
instance Outputable FractionalLit where
ppr f = pprWithSourceText (fl_text f) (rational (fl_value f))
{-
************************************************************************
* *
IntWithInf
* *
************************************************************************
Represents an integer or positive infinity
-}
-- | An integer or infinity
data IntWithInf = Int {-# UNPACK #-} !Int
| Infinity
deriving Eq
-- | A representation of infinity
infinity :: IntWithInf
infinity = Infinity
instance Ord IntWithInf where
compare Infinity Infinity = EQ
compare (Int _) Infinity = LT
compare Infinity (Int _) = GT
compare (Int a) (Int b) = a `compare` b
instance Outputable IntWithInf where
ppr Infinity = char '∞'
ppr (Int n) = int n
instance Num IntWithInf where
(+) = plusWithInf
(*) = mulWithInf
abs Infinity = Infinity
abs (Int n) = Int (abs n)
signum Infinity = Int 1
signum (Int n) = Int (signum n)
fromInteger = Int . fromInteger
(-) = panic "subtracting IntWithInfs"
intGtLimit :: Int -> IntWithInf -> Bool
intGtLimit _ Infinity = False
intGtLimit n (Int m) = n > m
-- | Add two 'IntWithInf's
plusWithInf :: IntWithInf -> IntWithInf -> IntWithInf
plusWithInf Infinity _ = Infinity
plusWithInf _ Infinity = Infinity
plusWithInf (Int a) (Int b) = Int (a + b)
-- | Multiply two 'IntWithInf's
mulWithInf :: IntWithInf -> IntWithInf -> IntWithInf
mulWithInf Infinity _ = Infinity
mulWithInf _ Infinity = Infinity
mulWithInf (Int a) (Int b) = Int (a * b)
-- | Turn a positive number into an 'IntWithInf', where 0 represents infinity
treatZeroAsInf :: Int -> IntWithInf
treatZeroAsInf 0 = Infinity
treatZeroAsInf n = Int n
-- | Inject any integer into an 'IntWithInf'
mkIntWithInf :: Int -> IntWithInf
mkIntWithInf = Int
data SpliceExplicitFlag
= ExplicitSplice | -- ^ <=> $(f x y)
ImplicitSplice -- ^ <=> f x y, i.e. a naked top level expression
deriving Data
{- *********************************************************************
* *
Types vs Kinds
* *
********************************************************************* -}
-- | Flag to see whether we're type-checking terms or kind-checking types
data TypeOrKind = TypeLevel | KindLevel
deriving Eq
instance Outputable TypeOrKind where
ppr TypeLevel = text "TypeLevel"
ppr KindLevel = text "KindLevel"
isTypeLevel :: TypeOrKind -> Bool
isTypeLevel TypeLevel = True
isTypeLevel KindLevel = False
isKindLevel :: TypeOrKind -> Bool
isKindLevel TypeLevel = False
isKindLevel KindLevel = True
|