summaryrefslogtreecommitdiff
path: root/compiler/typecheck/TcSimplify.hs
blob: b99823e728a8bb5a160b65b46eb98c67cbb624a4 (plain)
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
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
{-# LANGUAGE CPP #-}

module TcSimplify(
       simplifyInfer,
       growThetaTyVars,
       simplifyAmbiguityCheck,
       simplifyDefault,
       simplifyTop, simplifyInteractive, solveEqualities,
       simplifyWantedsTcM,
       tcCheckSatisfiability,

       -- For Rules we need these
       solveWanteds, runTcSDeriveds
  ) where

#include "HsVersions.h"

import Bag
import Class         ( Class, classKey, classTyCon )
import DynFlags      ( WarningFlag ( Opt_WarnMonomorphism )
                     , WarnReason ( Reason )
                     , DynFlags( solverIterations ) )
import Inst
import ListSetOps
import Maybes
import Name
import Outputable
import Pair
import PrelInfo
import PrelNames
import TcErrors
import TcEvidence
import TcInteract
import TcCanonical   ( makeSuperClasses, mkGivensWithSuperClasses )
import TcMType   as TcM
import TcRnMonad as TcM
import TcSMonad  as TcS
import TcType
import TrieMap       () -- DV: for now
import Type
import TysWiredIn    ( ptrRepLiftedTy )
import Unify         ( tcMatchTy )
import Util
import Var
import VarSet
import BasicTypes    ( IntWithInf, intGtLimit )
import ErrUtils      ( emptyMessages )
import qualified GHC.LanguageExtensions as LangExt

import Control.Monad ( when, unless )
import Data.List     ( partition )
import Data.Foldable    ( fold )

{-
*********************************************************************************
*                                                                               *
*                           External interface                                  *
*                                                                               *
*********************************************************************************
-}

simplifyTop :: WantedConstraints -> TcM (Bag EvBind)
-- Simplify top-level constraints
-- Usually these will be implications,
-- but when there is nothing to quantify we don't wrap
-- in a degenerate implication, so we do that here instead
simplifyTop wanteds
  = do { traceTc "simplifyTop {" $ text "wanted = " <+> ppr wanteds
       ; ((final_wc, unsafe_ol), binds1) <- runTcS $
            do { final_wc <- simpl_top wanteds
               ; unsafe_ol <- getSafeOverlapFailures
               ; return (final_wc, unsafe_ol) }
       ; traceTc "End simplifyTop }" empty

       ; traceTc "reportUnsolved {" empty
       ; binds2 <- reportUnsolved final_wc
       ; traceTc "reportUnsolved }" empty

       ; traceTc "reportUnsolved (unsafe overlapping) {" empty
       ; unless (isEmptyCts unsafe_ol) $ do {
           -- grab current error messages and clear, warnAllUnsolved will
           -- update error messages which we'll grab and then restore saved
           -- messages.
           ; errs_var  <- getErrsVar
           ; saved_msg <- TcM.readTcRef errs_var
           ; TcM.writeTcRef errs_var emptyMessages

           ; warnAllUnsolved $ WC { wc_simple = unsafe_ol
                                  , wc_insol = emptyCts
                                  , wc_impl = emptyBag }

           ; whyUnsafe <- fst <$> TcM.readTcRef errs_var
           ; TcM.writeTcRef errs_var saved_msg
           ; recordUnsafeInfer whyUnsafe
           }
       ; traceTc "reportUnsolved (unsafe overlapping) }" empty

       ; return (evBindMapBinds binds1 `unionBags` binds2) }

-- | Type-check a thing that emits only equality constraints, then
-- solve those constraints. Fails outright if there is trouble.
solveEqualities :: TcM a -> TcM a
solveEqualities thing_inside
  = checkNoErrs $  -- See Note [Fail fast on kind errors]
    do { (result, wanted) <- captureConstraints thing_inside
       ; traceTc "solveEqualities {" $ text "wanted = " <+> ppr wanted
       ; final_wc <- runTcSEqualities $ simpl_top wanted
       ; traceTc "End solveEqualities }" empty

       ; traceTc "reportAllUnsolved {" empty
       ; reportAllUnsolved final_wc
       ; traceTc "reportAllUnsolved }" empty
       ; return result }

simpl_top :: WantedConstraints -> TcS WantedConstraints
    -- See Note [Top-level Defaulting Plan]
simpl_top wanteds
  = do { wc_first_go <- nestTcS (solveWantedsAndDrop wanteds)
                            -- This is where the main work happens
       ; try_tyvar_defaulting wc_first_go }
  where
    try_tyvar_defaulting :: WantedConstraints -> TcS WantedConstraints
    try_tyvar_defaulting wc
      | isEmptyWC wc
      = return wc
      | otherwise
      = do { free_tvs <- TcS.zonkTyCoVarsAndFV (tyCoVarsOfWC wc)
           ; let meta_tvs = varSetElems (filterVarSet isMetaTyVar free_tvs)
                   -- zonkTyCoVarsAndFV: the wc_first_go is not yet zonked
                   -- filter isMetaTyVar: we might have runtime-skolems in GHCi,
                   -- and we definitely don't want to try to assign to those!

           ; defaulted <- mapM defaultTyVarTcS meta_tvs   -- Has unification side effects
           ; if or defaulted
             then do { wc_residual <- nestTcS (solveWanteds wc)
                            -- See Note [Must simplify after defaulting]
                     ; try_class_defaulting wc_residual }
             else try_class_defaulting wc }     -- No defaulting took place

    try_class_defaulting :: WantedConstraints -> TcS WantedConstraints
    try_class_defaulting wc
      | isEmptyWC wc
      = return wc
      | otherwise  -- See Note [When to do type-class defaulting]
      = do { something_happened <- applyDefaultingRules wc
                                   -- See Note [Top-level Defaulting Plan]
           ; if something_happened
             then do { wc_residual <- nestTcS (solveWantedsAndDrop wc)
                     ; try_class_defaulting wc_residual }
                  -- See Note [Overview of implicit CallStacks] in TcEvidence
             else try_callstack_defaulting wc }

    try_callstack_defaulting :: WantedConstraints -> TcS WantedConstraints
    try_callstack_defaulting wc
      | isEmptyWC wc
      = return wc
      | otherwise
      = defaultCallStacks wc

-- | Default any remaining @CallStack@ constraints to empty @CallStack@s.
defaultCallStacks :: WantedConstraints -> TcS WantedConstraints
-- See Note [Overview of implicit CallStacks] in TcEvidence
defaultCallStacks wanteds
  = do simples <- handle_simples (wc_simple wanteds)
       implics <- mapBagM handle_implic (wc_impl wanteds)
       return (wanteds { wc_simple = simples, wc_impl = implics })

  where

  handle_simples simples
    = catBagMaybes <$> mapBagM defaultCallStack simples

  handle_implic implic = do
    wanteds <- defaultCallStacks (ic_wanted implic)
    return (implic { ic_wanted = wanteds })

  defaultCallStack ct
    | Just (cls, tys) <- getClassPredTys_maybe (ctPred ct)
    , Just _ <- isCallStackDict cls tys
    = do { solveCallStack (cc_ev ct) EvCsEmpty
         ; return Nothing }

  defaultCallStack ct
    = return (Just ct)


{- Note [Fail fast on kind errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
solveEqualities is used to solve kind equalities when kind-checking
user-written types. If solving fails we should fail outright, rather
than just accumulate an error message, for two reasons:

  * A kind-bogus type signature may cause a cascade of knock-on
    errors if we let it pass

  * More seriously, we don't have a convenient term-level place to add
    deferred bindings for unsolved kind-equality constraints, so we
    don't build evidence bindings (by usine reportAllUnsolved). That
    means that we'll be left with with a type that has coercion holes
    in it, something like
           <type> |> co-hole
    where co-hole is not filled in.  Eeek!  That un-filled-in
    hole actually causes GHC to crash with "fvProv falls into a hole"
    See Trac #11563, #11520, #11516, #11399

So it's important to use 'checkNoErrs' here!

Note [When to do type-class defaulting]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHC 7.6 and 7.8.2, we did type-class defaulting only if insolubleWC
was false, on the grounds that defaulting can't help solve insoluble
constraints.  But if we *don't* do defaulting we may report a whole
lot of errors that would be solved by defaulting; these errors are
quite spurious because fixing the single insoluble error means that
defaulting happens again, which makes all the other errors go away.
This is jolly confusing: Trac #9033.

So it seems better to always do type-class defaulting.

However, always doing defaulting does mean that we'll do it in
situations like this (Trac #5934):
   run :: (forall s. GenST s) -> Int
   run = fromInteger 0
We don't unify the return type of fromInteger with the given function
type, because the latter involves foralls.  So we're left with
    (Num alpha, alpha ~ (forall s. GenST s) -> Int)
Now we do defaulting, get alpha := Integer, and report that we can't
match Integer with (forall s. GenST s) -> Int.  That's not totally
stupid, but perhaps a little strange.

Another potential alternative would be to suppress *all* non-insoluble
errors if there are *any* insoluble errors, anywhere, but that seems
too drastic.

Note [Must simplify after defaulting]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We may have a deeply buried constraint
    (t:*) ~ (a:Open)
which we couldn't solve because of the kind incompatibility, and 'a' is free.
Then when we default 'a' we can solve the constraint.  And we want to do
that before starting in on type classes.  We MUST do it before reporting
errors, because it isn't an error!  Trac #7967 was due to this.

Note [Top-level Defaulting Plan]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We have considered two design choices for where/when to apply defaulting.
   (i) Do it in SimplCheck mode only /whenever/ you try to solve some
       simple constraints, maybe deep inside the context of implications.
       This used to be the case in GHC 7.4.1.
   (ii) Do it in a tight loop at simplifyTop, once all other constraints have
        finished. This is the current story.

Option (i) had many disadvantages:
   a) Firstly, it was deep inside the actual solver.
   b) Secondly, it was dependent on the context (Infer a type signature,
      or Check a type signature, or Interactive) since we did not want
      to always start defaulting when inferring (though there is an exception to
      this, see Note [Default while Inferring]).
   c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs:
          f :: Int -> Bool
          f x = const True (\y -> let w :: a -> a
                                      w a = const a (y+1)
                                  in w y)
      We will get an implication constraint (for beta the type of y):
               [untch=beta] forall a. 0 => Num beta
      which we really cannot default /while solving/ the implication, since beta is
      untouchable.

Instead our new defaulting story is to pull defaulting out of the solver loop and
go with option (ii), implemented at SimplifyTop. Namely:
     - First, have a go at solving the residual constraint of the whole
       program
     - Try to approximate it with a simple constraint
     - Figure out derived defaulting equations for that simple constraint
     - Go round the loop again if you did manage to get some equations

Now, that has to do with class defaulting. However there exists type variable /kind/
defaulting. Again this is done at the top-level and the plan is:
     - At the top-level, once you had a go at solving the constraint, do
       figure out /all/ the touchable unification variables of the wanted constraints.
     - Apply defaulting to their kinds

More details in Note [DefaultTyVar].

Note [Safe Haskell Overlapping Instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In Safe Haskell, we apply an extra restriction to overlapping instances. The
motive is to prevent untrusted code provided by a third-party, changing the
behavior of trusted code through type-classes. This is due to the global and
implicit nature of type-classes that can hide the source of the dictionary.

Another way to state this is: if a module M compiles without importing another
module N, changing M to import N shouldn't change the behavior of M.

Overlapping instances with type-classes can violate this principle. However,
overlapping instances aren't always unsafe. They are just unsafe when the most
selected dictionary comes from untrusted code (code compiled with -XSafe) and
overlaps instances provided by other modules.

In particular, in Safe Haskell at a call site with overlapping instances, we
apply the following rule to determine if it is a 'unsafe' overlap:

 1) Most specific instance, I1, defined in an `-XSafe` compiled module.
 2) I1 is an orphan instance or a MPTC.
 3) At least one overlapped instance, Ix, is both:
    A) from a different module than I1
    B) Ix is not marked `OVERLAPPABLE`

This is a slightly involved heuristic, but captures the situation of an
imported module N changing the behavior of existing code. For example, if
condition (2) isn't violated, then the module author M must depend either on a
type-class or type defined in N.

Secondly, when should these heuristics be enforced? We enforced them when the
type-class method call site is in a module marked `-XSafe` or `-XTrustworthy`.
This allows `-XUnsafe` modules to operate without restriction, and for Safe
Haskell inferrence to infer modules with unsafe overlaps as unsafe.

One alternative design would be to also consider if an instance was imported as
a `safe` import or not and only apply the restriction to instances imported
safely. However, since instances are global and can be imported through more
than one path, this alternative doesn't work.

Note [Safe Haskell Overlapping Instances Implementation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

How is this implemented? It's complicated! So we'll step through it all:

 1) `InstEnv.lookupInstEnv` -- Performs instance resolution, so this is where
    we check if a particular type-class method call is safe or unsafe. We do this
    through the return type, `ClsInstLookupResult`, where the last parameter is a
    list of instances that are unsafe to overlap. When the method call is safe,
    the list is null.

 2) `TcInteract.matchClassInst` -- This module drives the instance resolution
    / dictionary generation. The return type is `LookupInstResult`, which either
    says no instance matched, or one found, and if it was a safe or unsafe
    overlap.

 3) `TcInteract.doTopReactDict` -- Takes a dictionary / class constraint and
     tries to resolve it by calling (in part) `matchClassInst`. The resolving
     mechanism has a work list (of constraints) that it process one at a time. If
     the constraint can't be resolved, it's added to an inert set. When compiling
     an `-XSafe` or `-XTrustworthy` module, we follow this approach as we know
     compilation should fail. These are handled as normal constraint resolution
     failures from here-on (see step 6).

     Otherwise, we may be inferring safety (or using `-Wunsafe`), and
     compilation should succeed, but print warnings and/or mark the compiled module
     as `-XUnsafe`. In this case, we call `insertSafeOverlapFailureTcS` which adds
     the unsafe (but resolved!) constraint to the `inert_safehask` field of
     `InertCans`.

 4) `TcSimplify.simplifyTop`:
       * Call simpl_top, the top-level function for driving the simplifier for
         constraint resolution.

       * Once finished, call `getSafeOverlapFailures` to retrieve the
         list of overlapping instances that were successfully resolved,
         but unsafe. Remember, this is only applicable for generating warnings
         (`-Wunsafe`) or inferring a module unsafe. `-XSafe` and `-XTrustworthy`
         cause compilation failure by not resolving the unsafe constraint at all.

       * For unresolved constraints (all types), call `TcErrors.reportUnsolved`,
         while for resolved but unsafe overlapping dictionary constraints, call
         `TcErrors.warnAllUnsolved`. Both functions convert constraints into a
         warning message for the user.

       * In the case of `warnAllUnsolved` for resolved, but unsafe
         dictionary constraints, we collect the generated warning
         message (pop it) and call `TcRnMonad.recordUnsafeInfer` to
         mark the module we are compiling as unsafe, passing the
         warning message along as the reason.

 5) `TcErrors.*Unsolved` -- Generates error messages for constraints by
    actually calling `InstEnv.lookupInstEnv` again! Yes, confusing, but all we
    know is the constraint that is unresolved or unsafe. For dictionary, all we
    know is that we need a dictionary of type C, but not what instances are
    available and how they overlap. So we once again call `lookupInstEnv` to
    figure that out so we can generate a helpful error message.

 6) `TcRnMonad.recordUnsafeInfer` -- Save the unsafe result and reason in an
      IORef called `tcg_safeInfer`.

 7) `HscMain.tcRnModule'` -- Reads `tcg_safeInfer` after type-checking, calling
    `HscMain.markUnsafeInfer` (passing the reason along) when safe-inferrence
    failed.
-}

------------------
simplifyAmbiguityCheck :: Type -> WantedConstraints -> TcM ()
simplifyAmbiguityCheck ty wanteds
  = do { traceTc "simplifyAmbiguityCheck {" (text "type = " <+> ppr ty $$ text "wanted = " <+> ppr wanteds)
       ; (final_wc, _) <- runTcS $ simpl_top wanteds
       ; traceTc "End simplifyAmbiguityCheck }" empty

       -- Normally report all errors; but with -XAllowAmbiguousTypes
       -- report only insoluble ones, since they represent genuinely
       -- inaccessible code
       ; allow_ambiguous <- xoptM LangExt.AllowAmbiguousTypes
       ; traceTc "reportUnsolved(ambig) {" empty
       ; tc_lvl <- TcM.getTcLevel
       ; unless (allow_ambiguous && not (insolubleWC tc_lvl final_wc))
                (discardResult (reportUnsolved final_wc))
       ; traceTc "reportUnsolved(ambig) }" empty

       ; return () }

------------------
simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind)
simplifyInteractive wanteds
  = traceTc "simplifyInteractive" empty >>
    simplifyTop wanteds

------------------
simplifyDefault :: ThetaType    -- Wanted; has no type variables in it
                -> TcM ()       -- Succeeds if the constraint is soluble
simplifyDefault theta
  = do { traceTc "simplifyInteractive" empty
       ; loc <- getCtLocM DefaultOrigin Nothing
       ; let wanted = [ CtDerived { ctev_pred = pred
                                  , ctev_loc  = loc }
                      | pred <- theta ]
       ; unsolved <- runTcSDeriveds (solveWanteds (mkSimpleWC wanted))
       ; traceTc "reportUnsolved {" empty
       ; reportAllUnsolved unsolved
       ; traceTc "reportUnsolved }" empty
       ; return () }

------------------
tcCheckSatisfiability :: Bag EvVar -> TcM Bool
-- Return True if satisfiable, False if definitely contradictory
tcCheckSatisfiability given_ids
  = do { lcl_env <- TcM.getLclEnv
       ; let given_loc = mkGivenLoc topTcLevel UnkSkol lcl_env
       ; (res, _ev_binds) <- runTcS $
             do { traceTcS "checkSatisfiability {" (ppr given_ids)
                ; given_cts <- mkGivensWithSuperClasses given_loc (bagToList given_ids)
                     -- See Note [Superclases and satisfiability]
                ; insols <- solveSimpleGivens given_cts
                ; insols <- try_harder insols
                ; traceTcS "checkSatisfiability }" (ppr insols)
                ; return (isEmptyBag insols) }
       ; return res }
 where
    try_harder :: Cts -> TcS Cts
    -- Maybe we have to search up the superclass chain to find
    -- an unsatisfiable constraint.  Example: pmcheck/T3927b.
    -- At the moment we try just once
    try_harder insols
      | not (isEmptyBag insols)   -- We've found that it's definitely unsatisfiable
      = return insols             -- Hurrah -- stop now.
      | otherwise
      = do { pending_given <- getPendingScDicts
           ; new_given <- makeSuperClasses pending_given
           ; solveSimpleGivens new_given }

{- Note [Superclases and satisfiability]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand superclasses before starting, because (Int ~ Bool), has
(Int ~~ Bool) as a superclass, which in turn has (Int ~N# Bool)
as a superclass, and it's the latter that is insoluble.  See
Note [The equality types story] in TysPrim.

If we fail to prove unsatisfiability we (arbitrarily) try just once to
find superclasses, using try_harder.  Reason: we might have a type
signature
   f :: F op (Implements push) => ..
where F is a type function.  This happened in Trac #3972.

We could do more than once but we'd have to have /some/ limit: in the
the recurisve case, we would go on forever in the common case where
the constraints /are/ satisfiable (Trac #10592 comment:12!).

For stratightforard situations without type functions the try_harder
step does nothing.


***********************************************************************************
*                                                                                 *
*                            Inference
*                                                                                 *
***********************************************************************************

Note [Inferring the type of a let-bound variable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   f x = rhs

To infer f's type we do the following:
 * Gather the constraints for the RHS with ambient level *one more than*
   the current one.  This is done by the call
        pushLevelAndCaptureConstraints (tcMonoBinds...)
   in TcBinds.tcPolyInfer

 * Call simplifyInfer to simplify the constraints and decide what to
   quantify over. We pass in the level used for the RHS constraints,
   here called rhs_tclvl.

This ensures that the implication constraint we generate, if any,
has a strictly-increased level compared to the ambient level outside
the let binding.

-}

simplifyInfer :: TcLevel               -- Used when generating the constraints
              -> Bool                  -- Apply monomorphism restriction
              -> [TcIdSigInfo]         -- Any signatures (possibly partial)
              -> [(Name, TcTauType)]   -- Variables to be generalised,
                                       -- and their tau-types
              -> WantedConstraints
              -> TcM ([TcTyVar],    -- Quantify over these type variables
                      [EvVar],      -- ... and these constraints (fully zonked)
                      TcEvBinds)    -- ... binding these evidence variables
simplifyInfer rhs_tclvl apply_mr sigs name_taus wanteds
  | isEmptyWC wanteds
  = do { gbl_tvs <- tcGetGlobalTyCoVars
       ; qtkvs <- quantify_tvs sigs gbl_tvs $
                  splitDepVarsOfTypes (map snd name_taus)
       ; traceTc "simplifyInfer: empty WC" (ppr name_taus $$ ppr qtkvs)
       ; return (qtkvs, [], emptyTcEvBinds) }

  | otherwise
  = do { traceTc "simplifyInfer {"  $ vcat
             [ text "sigs =" <+> ppr sigs
             , text "binds =" <+> ppr name_taus
             , text "rhs_tclvl =" <+> ppr rhs_tclvl
             , text "apply_mr =" <+> ppr apply_mr
             , text "(unzonked) wanted =" <+> ppr wanteds
             ]

       -- First do full-blown solving
       -- NB: we must gather up all the bindings from doing
       -- this solving; hence (runTcSWithEvBinds ev_binds_var).
       -- And note that since there are nested implications,
       -- calling solveWanteds will side-effect their evidence
       -- bindings, so we can't just revert to the input
       -- constraint.

       ; ev_binds_var <- TcM.newTcEvBinds
       ; wanted_transformed_incl_derivs <- setTcLevel rhs_tclvl $
           do { sig_derived <- concatMapM mkSigDerivedWanteds sigs
                  -- the False says we don't really need to solve all Deriveds
              ; runTcSWithEvBinds False (Just ev_binds_var) $
                solveWanteds (wanteds `addSimples` listToBag sig_derived) }
       ; wanted_transformed_incl_derivs <- TcM.zonkWC wanted_transformed_incl_derivs

       -- Find quant_pred_candidates, the predicates that
       -- we'll consider quantifying over
       -- NB: We do not do any defaulting when inferring a type, this can lead
       -- to less polymorphic types, see Note [Default while Inferring]

       ; tc_lcl_env <- TcM.getLclEnv
       ; let wanted_transformed = dropDerivedWC wanted_transformed_incl_derivs
       ; quant_pred_candidates   -- Fully zonked
           <- if insolubleWC rhs_tclvl wanted_transformed_incl_derivs
              then return []   -- See Note [Quantification with errors]
                               -- NB: must include derived errors in this test,
                               --     hence "incl_derivs"

              else do { let quant_cand = approximateWC wanted_transformed
                            meta_tvs   = filter isMetaTyVar (varSetElems (tyCoVarsOfCts quant_cand))

                      ; gbl_tvs <- tcGetGlobalTyCoVars
                            -- Miminise quant_cand.  We are not interested in any evidence
                            -- produced, because we are going to simplify wanted_transformed
                            -- again later. All we want here are the predicates over which to
                            -- quantify.
                            --
                            -- If any meta-tyvar unifications take place (unlikely),
                            -- we'll pick that up later.

                      -- See Note [Promote _and_ default when inferring]
                      ; let def_tyvar tv
                              = when (not $ tv `elemVarSet` gbl_tvs) $
                                defaultTyVar tv
                      ; mapM_ def_tyvar meta_tvs
                      ; mapM_ (promoteTyVar rhs_tclvl) meta_tvs

                      ; WC { wc_simple = simples }
                           <- setTcLevel rhs_tclvl $
                              runTcSDeriveds       $
                              solveSimpleWanteds   $
                              mapBag toDerivedCt quant_cand
                                -- NB: we don't want evidence,
                                -- so use Derived constraints

                      ; simples <- TcM.zonkSimples simples

                      ; return [ ctEvPred ev | ct <- bagToList simples
                                             , let ev = ctEvidence ct ] }

       -- NB: quant_pred_candidates is already fully zonked

       -- Decide what type variables and constraints to quantify
       ; zonked_taus <- mapM (TcM.zonkTcType . snd) name_taus
       ; let zonked_tau_tkvs = splitDepVarsOfTypes zonked_taus
       ; (qtvs, bound_theta)
           <- decideQuantification apply_mr sigs name_taus
                                   quant_pred_candidates zonked_tau_tkvs

         -- Promote any type variables that are free in the inferred type
         -- of the function:
         --    f :: forall qtvs. bound_theta => zonked_tau
         -- These variables now become free in the envt, and hence will show
         -- up whenever 'f' is called.  They may currently at rhs_tclvl, but
         -- they had better be unifiable at the outer_tclvl!
         -- Example:   envt mentions alpha[1]
         --            tau_ty = beta[2] -> beta[2]
         --            consraints = alpha ~ [beta]
         -- we don't quantify over beta (since it is fixed by envt)
         -- so we must promote it!  The inferred type is just
         --   f :: beta -> beta
       ; outer_tclvl    <- TcM.getTcLevel
       ; zonked_tau_tvs <- fold <$>
                           traverse TcM.zonkTyCoVarsAndFV zonked_tau_tkvs
              -- decideQuantification turned some meta tyvars into
              -- quantified skolems, so we have to zonk again

       ; let phi_tvs     = tyCoVarsOfTypes bound_theta
                           `unionVarSet` zonked_tau_tvs

             promote_tvs = closeOverKinds phi_tvs `delVarSetList` qtvs
       ; MASSERT2( closeOverKinds promote_tvs `subVarSet` promote_tvs
                 , ppr phi_tvs $$
                   ppr (closeOverKinds phi_tvs) $$
                   ppr promote_tvs $$
                   ppr (closeOverKinds promote_tvs) )
           -- we really don't want a type to be promoted when its kind isn't!

           -- promoteTyVar ignores coercion variables
       ; mapM_ (promoteTyVar outer_tclvl) (varSetElems promote_tvs)

           -- Emit an implication constraint for the
           -- remaining constraints from the RHS
       ; bound_theta_vars <- mapM TcM.newEvVar bound_theta
       ; let skol_info   = InferSkol [ (name, mkSigmaTy [] bound_theta ty)
                                     | (name, ty) <- name_taus ]
                        -- Don't add the quantified variables here, because
                        -- they are also bound in ic_skols and we want them
                        -- to be tidied uniformly

             implic = Implic { ic_tclvl    = rhs_tclvl
                             , ic_skols    = qtvs
                             , ic_no_eqs   = False
                             , ic_given    = bound_theta_vars
                             , ic_wanted   = wanted_transformed
                             , ic_status   = IC_Unsolved
                             , ic_binds    = Just ev_binds_var
                             , ic_info     = skol_info
                             , ic_env      = tc_lcl_env }
       ; emitImplication implic

         -- All done!
       ; traceTc "} simplifyInfer/produced residual implication for quantification" $
         vcat [ text "quant_pred_candidates =" <+> ppr quant_pred_candidates
              , text "zonked_taus" <+> ppr zonked_taus
              , text "zonked_tau_tvs=" <+> ppr zonked_tau_tvs
              , text "promote_tvs=" <+> ppr promote_tvs
              , text "bound_theta =" <+> ppr bound_theta
              , text "qtvs =" <+> ppr qtvs
              , text "implic =" <+> ppr implic ]

       ; return ( qtvs, bound_theta_vars, TcEvBinds ev_binds_var ) }

mkSigDerivedWanteds :: TcIdSigInfo -> TcM [Ct]
-- See Note [Add deriveds for signature contexts]
mkSigDerivedWanteds (TISI { sig_bndr = PartialSig { sig_name = name }
                          , sig_theta = theta, sig_tau = tau })
 = do { let skol_info = InferSkol [(name, mkSigmaTy [] theta tau)]
      ; loc <- getCtLocM (GivenOrigin skol_info) (Just TypeLevel)
      ; return [ mkNonCanonical (CtDerived { ctev_pred = pred
                                           , ctev_loc = loc })
               | pred <- theta ] }
mkSigDerivedWanteds _ = return []

{- Note [Add deriveds for signature contexts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (Trac #11016):
  f2 :: (?x :: Int) => _
  f2 = ?x
We'll use plan InferGen because there are holes in the type.  But we want
to have the (?x :: Int) constraint floating around so that the functional
dependencies kick in.  Otherwise the occurrence of ?x on the RHS produces
constraint (?x :: alpha), and we wont unify alpha:=Int.

Solution: in simplifyInfer, just before simplifying the constraints
gathered from the RHS, add Derived constraints for the context of any
type signatures.  This is rare; if there is a type signature we'll usually
be doing CheckGen.  But it happens for signatures with holes.

************************************************************************
*                                                                      *
                Quantification
*                                                                      *
************************************************************************

Note [Deciding quantification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the monomorphism restriction does not apply, then we quantify as follows:
  * Take the global tyvars, and "grow" them using the equality constraints
    E.g.  if x:alpha is in the environment, and alpha ~ [beta] (which can
          happen because alpha is untouchable here) then do not quantify over
          beta, because alpha fixes beta, and beta is effectively free in
          the environment too
    These are the mono_tvs

  * Take the free vars of the tau-type (zonked_tau_tvs) and "grow" them
    using all the constraints.  These are tau_tvs_plus

  * Use quantifyTyVars to quantify over (tau_tvs_plus - mono_tvs), being
    careful to close over kinds, and to skolemise the quantified tyvars.
    (This actually unifies each quantifies meta-tyvar with a fresh skolem.)
    Result is qtvs.

  * Filter the constraints using pickQuantifiablePreds and the qtvs.
    We have to zonk the constraints first, so they "see" the freshly
    created skolems.

If the MR does apply, mono_tvs includes all the constrained tyvars --
including all covars -- and the quantified constraints are empty/insoluble.

-}

decideQuantification
  :: Bool                  -- try the MR restriction?
  -> [TcIdSigInfo]
  -> [(Name, TcTauType)]   -- variables to be generalised (for errors only)
  -> [PredType]            -- candidate theta
  -> Pair TcTyCoVarSet     -- dependent (kind) variables & type variables
  -> TcM ( [TcTyVar]       -- Quantify over these (skolems)
         , [PredType] )    -- and this context (fully zonked)
-- See Note [Deciding quantification]
decideQuantification apply_mr sigs name_taus constraints
                     zonked_pair@(Pair zonked_tau_kvs zonked_tau_tvs)
  | apply_mr     -- Apply the Monomorphism restriction
  = do { gbl_tvs <- tcGetGlobalTyCoVars
       ; let constrained_tvs = tyCoVarsOfTypes constraints `unionVarSet`
                               filterVarSet isCoVar zonked_tkvs
             mono_tvs = gbl_tvs `unionVarSet` constrained_tvs
       ; qtvs <- quantify_tvs sigs mono_tvs zonked_pair

           -- Warn about the monomorphism restriction
       ; warn_mono <- woptM Opt_WarnMonomorphism
       ; let mr_bites = constrained_tvs `intersectsVarSet` zonked_tkvs
       ; warnTc (Reason Opt_WarnMonomorphism) (warn_mono && mr_bites) $
         hang (text "The Monomorphism Restriction applies to the binding"
               <> plural bndrs <+> text "for" <+> pp_bndrs)
             2 (text "Consider giving a type signature for"
                <+> if isSingleton bndrs then pp_bndrs
                                         else text "these binders")

       -- All done
       ; traceTc "decideQuantification 1" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs
                                                , ppr qtvs, ppr mr_bites])
       ; return (qtvs, []) }

  | otherwise
  = do { gbl_tvs <- tcGetGlobalTyCoVars
       ; let mono_tvs     = growThetaTyVars equality_constraints gbl_tvs
             tau_tvs_plus = growThetaTyVars constraints zonked_tau_tvs
       ; qtvs <- quantify_tvs sigs mono_tvs (Pair zonked_tau_kvs tau_tvs_plus)
          -- We don't grow the kvs, as there's no real need to. Recall
          -- that quantifyTyVars uses the separation between kvs and tvs
          -- only for defaulting, and we don't want (ever) to default a tv
          -- to *. So, don't grow the kvs.

       ; constraints <- TcM.zonkTcTypes constraints
                 -- quantiyTyVars turned some meta tyvars into
                 -- quantified skolems, so we have to zonk again

       ; let theta     = pickQuantifiablePreds (mkVarSet qtvs) constraints
             min_theta = mkMinimalBySCs theta
               -- See Note [Minimize by Superclasses]

       ; traceTc "decideQuantification 2"
           (vcat [ text "constraints:"  <+> ppr constraints
                 , text "gbl_tvs:"      <+> ppr gbl_tvs
                 , text "mono_tvs:"     <+> ppr mono_tvs
                 , text "zonked_kvs:"   <+> ppr zonked_tau_kvs
                 , text "tau_tvs_plus:" <+> ppr tau_tvs_plus
                 , text "qtvs:"         <+> ppr qtvs
                 , text "min_theta:"    <+> ppr min_theta ])
       ; return (qtvs, min_theta) }
  where
    zonked_tkvs = zonked_tau_kvs `unionVarSet` zonked_tau_tvs
    bndrs    = map fst name_taus
    pp_bndrs = pprWithCommas (quotes . ppr) bndrs
    equality_constraints = filter isEqPred constraints

quantify_tvs :: [TcIdSigInfo]
             -> TcTyVarSet   -- the monomorphic tvs
             -> Pair TcTyVarSet   -- kvs, tvs to quantify
             -> TcM [TcTyVar]
-- See Note [Which type variables to quantify]
quantify_tvs sigs mono_tvs (Pair tau_kvs tau_tvs)
  = quantifyTyVars (mono_tvs `delVarSetList` sig_qtvs)
                   (Pair tau_kvs
                         (tau_tvs `extendVarSetList` sig_qtvs
                                  `extendVarSetList` sig_wcs))
                   -- NB: quantifyTyVars zonks its arguments
  where
    sig_qtvs = [ skol | sig <- sigs, (_, skol) <- sig_skols sig ]
    sig_wcs  = [ wc   | TISI { sig_bndr = PartialSig { sig_wcs = wcs } } <- sigs
                      , (_, wc) <- wcs ]


------------------
growThetaTyVars :: ThetaType -> TyCoVarSet -> TyVarSet
-- See Note [Growing the tau-tvs using constraints]
-- NB: only returns tyvars, never covars
growThetaTyVars theta tvs
  | null theta = tvs_only
  | otherwise  = filterVarSet isTyVar $
                 transCloVarSet mk_next seed_tvs
  where
    tvs_only = filterVarSet isTyVar tvs
    seed_tvs = tvs `unionVarSet` tyCoVarsOfTypes ips
    (ips, non_ips) = partition isIPPred theta
                         -- See Note [Inheriting implicit parameters] in TcType

    mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones
    mk_next so_far = foldr (grow_one so_far) emptyVarSet non_ips
    grow_one so_far pred tvs
       | pred_tvs `intersectsVarSet` so_far = tvs `unionVarSet` pred_tvs
       | otherwise                          = tvs
       where
         pred_tvs = tyCoVarsOfType pred

{- Note [Which type variables to quantify]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When choosing type variables to quantify, the basic plan is to
quantify over all type variables that are
 * free in the tau_tvs, and
 * not forced to be monomorphic (mono_tvs),
   for example by being free in the environment.

However, for a pattern binding, or with wildcards, we might
be doing inference *in the presence of a type signature*.
Mostly, if there is a signature we use CheckGen, not InferGen,
but with pattern bindings or wildcards we might do InferGen
and still have a type signature.  For example:
   f :: _ -> a
   f x = ...
or
   g :: (Eq _a) => _b -> _b
or
   p :: a -> a
   (p,q) = e
In all these cases we use plan InferGen, and hence call simplifyInfer.
But those 'a' variables are skolems, and we should be sure to quantify
over them, regardless of the monomorphism restriction etc.  If we
don't, when reporting a type error we panic when we find that a
skolem isn't bound by any enclosing implication.

Moreover we must quantify over all wildcards that are not free in
the environment.  In the case of 'g' for example, silly though it is,
we want to get the inferred type
   g :: forall t. Eq t => Int -> Int
and then report ambiguity, rather than *not* quantifying over 't'
and getting some much more mysterious error later.  A similar case
is
  h :: F _a -> Int

That's why we pass sigs to simplifyInfer, and make sure (in
quantify_tvs) that we do quantify over them.  Trac #10615 is
a case in point.

Note [Quantifying over equality constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Should we quantify over an equality constraint (s ~ t)?  In general, we don't.
Doing so may simply postpone a type error from the function definition site to
its call site.  (At worst, imagine (Int ~ Bool)).

However, consider this
         forall a. (F [a] ~ Int) => blah
Should we quantify over the (F [a] ~ Int)?  Perhaps yes, because at the call
site we will know 'a', and perhaps we have instance  F [Bool] = Int.
So we *do* quantify over a type-family equality where the arguments mention
the quantified variables.

Note [Growing the tau-tvs using constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(growThetaTyVars insts tvs) is the result of extending the set
    of tyvars, tvs, using all conceivable links from pred

E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e}
Then growThetaTyVars preds tvs = {a,b,c}

Notice that
   growThetaTyVars is conservative       if v might be fixed by vs
                                         => v `elem` grow(vs,C)

Note [Quantification with errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we find that the RHS of the definition has some absolutely-insoluble
constraints, we abandon all attempts to find a context to quantify
over, and instead make the function fully-polymorphic in whatever
type we have found.  For two reasons
  a) Minimise downstream errors
  b) Avoid spurious errors from this function

But NB that we must include *derived* errors in the check. Example:
    (a::*) ~ Int#
We get an insoluble derived error *~#, and we don't want to discard
it before doing the isInsolubleWC test!  (Trac #8262)

Note [Default while Inferring]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Our current plan is that defaulting only happens at simplifyTop and
not simplifyInfer.  This may lead to some insoluble deferred constraints.
Example:

instance D g => C g Int b

constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha
type inferred       = gamma -> gamma

Now, if we try to default (alpha := Int) we will be able to refine the implication to
  (forall b. 0 => C gamma Int b)
which can then be simplified further to
  (forall b. 0 => D gamma)
Finally, we /can/ approximate this implication with (D gamma) and infer the quantified
type:  forall g. D g => g -> g

Instead what will currently happen is that we will get a quantified type
(forall g. g -> g) and an implication:
       forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha

Which, even if the simplifyTop defaults (alpha := Int) we will still be left with an
unsolvable implication:
       forall g. 0 => (forall b. 0 => D g)

The concrete example would be:
       h :: C g a s => g -> a -> ST s a
       f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1)

But it is quite tedious to do defaulting and resolve the implication constraints, and
we have not observed code breaking because of the lack of defaulting in inference, so
we don't do it for now.



Note [Minimize by Superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we quantify over a constraint, in simplifyInfer we need to
quantify over a constraint that is minimal in some sense: For
instance, if the final wanted constraint is (Eq alpha, Ord alpha),
we'd like to quantify over Ord alpha, because we can just get Eq alpha
from superclass selection from Ord alpha. This minimization is what
mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint
to check the original wanted.


Note [Avoid unnecessary constraint simplification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -------- NB NB NB (Jun 12) -------------
    This note not longer applies; see the notes with Trac #4361.
    But I'm leaving it in here so we remember the issue.)
    ----------------------------------------
When inferring the type of a let-binding, with simplifyInfer,
try to avoid unnecessarily simplifying class constraints.
Doing so aids sharing, but it also helps with delicate
situations like

   instance C t => C [t] where ..

   f :: C [t] => ....
   f x = let g y = ...(constraint C [t])...
         in ...
When inferring a type for 'g', we don't want to apply the
instance decl, because then we can't satisfy (C t).  So we
just notice that g isn't quantified over 't' and partition
the constraints before simplifying.

This only half-works, but then let-generalisation only half-works.

*********************************************************************************
*                                                                                 *
*                                 Main Simplifier                                 *
*                                                                                 *
***********************************************************************************

-}

simplifyWantedsTcM :: [CtEvidence] -> TcM WantedConstraints
-- Solve the specified Wanted constraints
-- Discard the evidence binds
-- Discards all Derived stuff in result
-- Postcondition: fully zonked and unflattened constraints
simplifyWantedsTcM wanted
  = do { traceTc "simplifyWantedsTcM {" (ppr wanted)
       ; (result, _) <- runTcS (solveWantedsAndDrop $ mkSimpleWC wanted)
       ; result <- TcM.zonkWC result
       ; traceTc "simplifyWantedsTcM }" (ppr result)
       ; return result }

solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints
-- Since solveWanteds returns the residual WantedConstraints,
-- it should always be called within a runTcS or something similar,
-- Result is not zonked
solveWantedsAndDrop wanted
  = do { wc <- solveWanteds wanted
       ; return (dropDerivedWC wc) }

solveWanteds :: WantedConstraints -> TcS WantedConstraints
-- so that the inert set doesn't mindlessly propagate.
-- NB: wc_simples may be wanted /or/ derived now
solveWanteds wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
  = do { traceTcS "solveWanteds {" (ppr wc)

         -- Try the simple bit, including insolubles. Solving insolubles a
         -- second time round is a bit of a waste; but the code is simple
         -- and the program is wrong anyway, and we don't run the danger
         -- of adding Derived insolubles twice; see
         -- TcSMonad Note [Do not add duplicate derived insolubles]
       ; wc1 <- solveSimpleWanteds simples
       ; (no_new_scs, wc1) <- expandSuperClasses wc1
       ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1

       ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1)

       ; dflags <- getDynFlags
       ; final_wc <- simpl_loop 0 (solverIterations dflags) floated_eqs no_new_scs
                                (WC { wc_simple = simples1, wc_impl = implics2
                                    , wc_insol  = insols `unionBags` insols1 })

       ; bb <- TcS.getTcEvBindsMap
       ; traceTcS "solveWanteds }" $
                 vcat [ text "final wc =" <+> ppr final_wc
                      , text "current evbinds  =" <+> ppr (evBindMapBinds bb) ]

       ; return final_wc }

simpl_loop :: Int -> IntWithInf -> Cts -> Bool
           -> WantedConstraints
           -> TcS WantedConstraints
simpl_loop n limit floated_eqs no_new_scs
           wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics })
  | isEmptyBag floated_eqs && no_new_scs
  = return wc  -- Done!

  | n `intGtLimit` limit
  = do { -- Add an error (not a warning) if we blow the limit,
         -- Typically if we blow the limit we are going to report some other error
         -- (an unsolved constraint), and we don't want that error to suppress
         -- the iteration limit warning!
         addErrTcS (hang (text "solveWanteds: too many iterations"
                   <+> parens (text "limit =" <+> ppr limit))
                2 (vcat [ text "Unsolved:" <+> ppr wc
                        , ppUnless (isEmptyBag floated_eqs) $
                          text "Floated equalities:" <+> ppr floated_eqs
                        , ppUnless no_new_scs $
                          text "New superclasses found"
                        , text "Set limit with -fconstraint-solver-iterations=n; n=0 for no limit"
                  ]))
       ; return wc }

  | otherwise
  = do { let n_floated = lengthBag floated_eqs
       ; csTraceTcS $
         text "simpl_loop iteration=" <> int n
         <+> (parens $ hsep [ text "no new scs =" <+> ppr no_new_scs <> comma
                            , int n_floated <+> text "floated eqs" <> comma
                            , int (lengthBag simples) <+> text "simples to solve" ])

       -- solveSimples may make progress if either float_eqs hold
       ; (unifs1, wc1) <- reportUnifications $
                          solveSimpleWanteds (floated_eqs `unionBags` simples)
                               -- Put floated_eqs first so they get solved first
                               -- NB: the floated_eqs may include /derived/ equalities
                               --     arising from fundeps inside an implication

       ; (no_new_scs, wc1) <- expandSuperClasses wc1
       ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1

       -- We have already tried to solve the nested implications once
       -- Try again only if we have unified some meta-variables
       -- (which is a bit like adding more givens
       -- See Note [Cutting off simpl_loop]
       ; (floated_eqs2, implics2) <- if unifs1 == 0 && isEmptyBag implics1
                                     then return (emptyBag, implics)
                                     else solveNestedImplications (implics `unionBags` implics1)

       ; simpl_loop (n+1) limit floated_eqs2 no_new_scs
                    (WC { wc_simple = simples1, wc_impl = implics2
                        , wc_insol  = insols `unionBags` insols1 }) }

expandSuperClasses :: WantedConstraints -> TcS (Bool, WantedConstraints)
-- If there are any unsolved wanteds, expand one step of superclasses for
-- unsolved wanteds or givens
-- See Note [The superclass story] in TcCanonical
expandSuperClasses wc@(WC { wc_simple = unsolved, wc_insol = insols })
  | not (anyBag superClassesMightHelp unsolved)
  = return (True, wc)
  | otherwise
  = do { traceTcS "expandSuperClasses {" empty
       ; let (pending_wanted, unsolved') = mapAccumBagL get [] unsolved
             get acc ct = case isPendingScDict ct of
                            Just ct' -> (ct':acc, ct')
                            Nothing  -> (acc,     ct)
       ; pending_given <- getPendingScDicts
       ; if null pending_given && null pending_wanted
         then do { traceTcS "End expandSuperClasses no-op }" empty
                 ; return (True, wc) }
         else
    do { new_given  <- makeSuperClasses pending_given
       ; new_insols <- solveSimpleGivens new_given
       ; new_wanted <- makeSuperClasses pending_wanted
       ; traceTcS "End expandSuperClasses }"
                  (vcat [ text "Given:" <+> ppr pending_given
                        , text "Insols from given:" <+> ppr new_insols
                        , text "Wanted:" <+> ppr new_wanted ])
       ; return (False, wc { wc_simple = unsolved' `unionBags` listToBag new_wanted
                           , wc_insol = insols `unionBags` new_insols }) } }

solveNestedImplications :: Bag Implication
                        -> TcS (Cts, Bag Implication)
-- Precondition: the TcS inerts may contain unsolved simples which have
-- to be converted to givens before we go inside a nested implication.
solveNestedImplications implics
  | isEmptyBag implics
  = return (emptyBag, emptyBag)
  | otherwise
  = do { traceTcS "solveNestedImplications starting {" empty
       ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics
       ; let floated_eqs = concatBag floated_eqs_s

       -- ... and we are back in the original TcS inerts
       -- Notice that the original includes the _insoluble_simples so it was safe to ignore
       -- them in the beginning of this function.
       ; traceTcS "solveNestedImplications end }" $
                  vcat [ text "all floated_eqs ="  <+> ppr floated_eqs
                       , text "unsolved_implics =" <+> ppr unsolved_implics ]

       ; return (floated_eqs, catBagMaybes unsolved_implics) }

solveImplication :: Implication    -- Wanted
                 -> TcS (Cts,      -- All wanted or derived floated equalities: var = type
                         Maybe Implication) -- Simplified implication (empty or singleton)
-- Precondition: The TcS monad contains an empty worklist and given-only inerts
-- which after trying to solve this implication we must restore to their original value
solveImplication imp@(Implic { ic_tclvl  = tclvl
                             , ic_binds  = m_ev_binds
                             , ic_skols  = skols
                             , ic_given  = given_ids
                             , ic_wanted = wanteds
                             , ic_info   = info
                             , ic_status = status
                             , ic_env    = env })
  | IC_Solved {} <- status
  = return (emptyCts, Just imp)  -- Do nothing

  | otherwise  -- Even for IC_Insoluble it is worth doing more work
               -- The insoluble stuff might be in one sub-implication
               -- and other unsolved goals in another; and we want to
               -- solve the latter as much as possible
  = do { inerts <- getTcSInerts
       ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts)

         -- Solve the nested constraints
       ; ((no_given_eqs, given_insols, residual_wanted), used_tcvs)
             <- nestImplicTcS m_ev_binds (mkVarSet (skols ++ given_ids)) tclvl $
               do { let loc = mkGivenLoc tclvl info env
                  ; givens_w_scs <- mkGivensWithSuperClasses loc given_ids
                  ; given_insols <- solveSimpleGivens givens_w_scs

                  ; residual_wanted <- solveWanteds wanteds
                        -- solveWanteds, *not* solveWantedsAndDrop, because
                        -- we want to retain derived equalities so we can float
                        -- them out in floatEqualities

                  ; no_eqs <- getNoGivenEqs tclvl skols
                        -- Call getNoGivenEqs /after/ solveWanteds, because
                        -- solveWanteds can augment the givens, via expandSuperClasses,
                        -- to reveal given superclass equalities

                  ; return (no_eqs, given_insols, residual_wanted) }

       ; (floated_eqs, residual_wanted)
             <- floatEqualities skols no_given_eqs residual_wanted

       ; traceTcS "solveImplication 2"
           (ppr given_insols $$ ppr residual_wanted $$ ppr used_tcvs)
       ; let final_wanted = residual_wanted `addInsols` given_insols

       ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs
                                                 , ic_wanted = final_wanted })
                                            used_tcvs

       ; evbinds <- TcS.getTcEvBindsMap
       ; traceTcS "solveImplication end }" $ vcat
             [ text "no_given_eqs =" <+> ppr no_given_eqs
             , text "floated_eqs =" <+> ppr floated_eqs
             , text "res_implic =" <+> ppr res_implic
             , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds) ]

       ; return (floated_eqs, res_implic) }

----------------------
setImplicationStatus :: Implication -> TyCoVarSet  -- needed variables
                     -> TcS (Maybe Implication)
-- Finalise the implication returned from solveImplication:
--    * Set the ic_status field
--    * Trim the ic_wanted field to remove Derived constraints
-- Return Nothing if we can discard the implication altogether
setImplicationStatus implic@(Implic { ic_binds = m_ev_binds_var
                                    , ic_info = info
                                    , ic_tclvl  = tc_lvl
                                    , ic_wanted = wc
                                    , ic_given = givens })
                     used_tcvs
 | some_insoluble
 = return $ Just $
   implic { ic_status = IC_Insoluble
          , ic_wanted = wc { wc_simple = pruned_simples
                           , wc_insol  = pruned_insols } }

 | some_unsolved
 = return $ Just $
   implic { ic_status = IC_Unsolved
          , ic_wanted = wc { wc_simple = pruned_simples
                           , wc_insol  = pruned_insols } }

 | otherwise  -- Everything is solved; look at the implications
              -- See Note [Tracking redundant constraints]
 = do { ev_binds <- case m_ev_binds_var of
                      Just (EvBindsVar ref _) -> TcS.readTcRef ref
                      Nothing                 -> return emptyEvBindMap
      ; let all_needs = neededEvVars ev_binds
                                     (used_tcvs `unionVarSet` implic_needs)

            dead_givens | warnRedundantGivens info
                        = filterOut (`elemVarSet` all_needs) givens
                        | otherwise = []   -- None to report

            final_needs = all_needs `delVarSetList` givens

            discard_entire_implication  -- Can we discard the entire implication?
              =  null dead_givens           -- No warning from this implication
              && isEmptyBag pruned_implics  -- No live children
              && isEmptyVarSet final_needs  -- No needed vars to pass up to parent

            final_status = IC_Solved { ics_need = final_needs
                                     , ics_dead = dead_givens }
            final_implic = implic { ic_status = final_status
                                  , ic_wanted = wc { wc_simple = pruned_simples
                                                   , wc_insol  = pruned_insols
                                                   , wc_impl   = pruned_implics } }
               -- We can only prune the child implications (pruned_implics)
               -- in the IC_Solved status case, because only then we can
               -- accumulate their needed evidence variales into the
               -- IC_Solved final_status field of the parent implication.

      ; return $ if discard_entire_implication
                 then Nothing
                 else Just final_implic }
 where
   WC { wc_simple = simples, wc_impl = implics, wc_insol = insols } = wc

   some_insoluble = insolubleWC tc_lvl wc
   some_unsolved = not (isEmptyBag simples && isEmptyBag insols)
                 || isNothing mb_implic_needs

   pruned_simples = dropDerivedSimples simples
   pruned_insols  = dropDerivedInsols insols
   pruned_implics = filterBag need_to_keep_implic implics

   mb_implic_needs :: Maybe VarSet
        -- Just vs => all implics are IC_Solved, with 'vs' needed
        -- Nothing => at least one implic is not IC_Solved
   mb_implic_needs   = foldrBag add_implic (Just emptyVarSet) implics
   Just implic_needs = mb_implic_needs

   add_implic implic acc
      | Just vs_acc <- acc
      , IC_Solved { ics_need = vs } <- ic_status implic
      = Just (vs `unionVarSet` vs_acc)
      | otherwise = Nothing

   need_to_keep_implic ic
     | IC_Solved { ics_dead = [] } <- ic_status ic
           -- Fully solved, and no redundant givens to report
     , isEmptyBag (wc_impl (ic_wanted ic))
           -- And no children that might have things to report
     = False
     | otherwise
     = True

warnRedundantGivens :: SkolemInfo -> Bool
warnRedundantGivens (SigSkol ctxt _)
  = case ctxt of
       FunSigCtxt _ warn_redundant -> warn_redundant
       ExprSigCtxt                 -> True
       _                           -> False
  -- To think about: do we want to report redundant givens for
  -- pattern synonyms, PatSynCtxt? c.f Trac #9953, comment:21.

warnRedundantGivens (InstSkol {}) = True
warnRedundantGivens _             = False

neededEvVars :: EvBindMap -> VarSet -> VarSet
-- Find all the evidence variables that are "needed",
--    and then delete all those bound by the evidence bindings
-- See note [Tracking redundant constraints]
neededEvVars ev_binds initial_seeds
 = needed `minusVarSet` bndrs
 where
   seeds  = foldEvBindMap add_wanted initial_seeds ev_binds
   needed = transCloVarSet also_needs seeds
   bndrs  = foldEvBindMap add_bndr emptyVarSet ev_binds

   add_wanted :: EvBind -> VarSet -> VarSet
   add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs
     | is_given  = needs  -- Add the rhs vars of the Wanted bindings only
     | otherwise = evVarsOfTerm rhs `unionVarSet` needs

   also_needs :: VarSet -> VarSet
   also_needs needs
     = foldVarSet add emptyVarSet needs
     where
       add v needs
        | Just ev_bind <- lookupEvBind ev_binds v
        , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind
        , is_given
        = evVarsOfTerm rhs `unionVarSet` needs
        | otherwise
        = needs

   add_bndr :: EvBind -> VarSet -> VarSet
   add_bndr (EvBind { eb_lhs = v }) vs = extendVarSet vs v


{-
Note [Tracking redundant constraints]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With Opt_WarnRedundantConstraints, GHC can report which
constraints of a type signature (or instance declaration) are
redundant, and can be omitted.  Here is an overview of how it
works:

----- What is a redundant constraint?

* The things that can be redundant are precisely the Given
  constraints of an implication.

* A constraint can be redundant in two different ways:
  a) It is implied by other givens.  E.g.
       f :: (Eq a, Ord a)     => blah   -- Eq a unnecessary
       g :: (Eq a, a~b, Eq b) => blah   -- Either Eq a or Eq b unnecessary
  b) It is not needed by the Wanted constraints covered by the
     implication E.g.
       f :: Eq a => a -> Bool
       f x = True  -- Equality not used

*  To find (a), when we have two Given constraints,
   we must be careful to drop the one that is a naked variable (if poss).
   So if we have
       f :: (Eq a, Ord a) => blah
   then we may find [G] sc_sel (d1::Ord a) :: Eq a
                    [G] d2 :: Eq a
   We want to discard d2 in favour of the superclass selection from
   the Ord dictionary.  This is done by TcInteract.solveOneFromTheOther
   See Note [Replacement vs keeping].

* To find (b) we need to know which evidence bindings are 'wanted';
  hence the eb_is_given field on an EvBind.

----- How tracking works

* When the constraint solver finishes solving all the wanteds in
  an implication, it sets its status to IC_Solved

  - The ics_dead field, of IC_Solved, records the subset of this implication's
    ic_given that are redundant (not needed).

  - The ics_need field of IC_Solved then records all the
    in-scope (given) evidence variables bound by the context, that
    were needed to solve this implication, including all its nested
    implications.  (We remove the ic_given of this implication from
    the set, of course.)

* We compute which evidence variables are needed by an implication
  in setImplicationStatus.  A variable is needed if
    a) it is free in the RHS of a Wanted EvBind,
    b) it is free in the RHS of an EvBind whose LHS is needed,
    c) it is in the ics_need of a nested implication.
    d) it is listed in the tcs_used_tcvs field of the nested TcSEnv

* We need to be careful not to discard an implication
  prematurely, even one that is fully solved, because we might
  thereby forget which variables it needs, and hence wrongly
  report a constraint as redundant.  But we can discard it once
  its free vars have been incorporated into its parent; or if it
  simply has no free vars. This careful discarding is also
  handled in setImplicationStatus.

----- Reporting redundant constraints

* TcErrors does the actual warning, in warnRedundantConstraints.

* We don't report redundant givens for *every* implication; only
  for those which reply True to TcSimplify.warnRedundantGivens:

   - For example, in a class declaration, the default method *can*
     use the class constraint, but it certainly doesn't *have* to,
     and we don't want to report an error there.

   - More subtly, in a function definition
       f :: (Ord a, Ord a, Ix a) => a -> a
       f x = rhs
     we do an ambiguity check on the type (which would find that one
     of the Ord a constraints was redundant), and then we check that
     the definition has that type (which might find that both are
     redundant).  We don't want to report the same error twice, so we
     disable it for the ambiguity check.  Hence using two different
     FunSigCtxts, one with the warn-redundant field set True, and the
     other set False in
        - TcBinds.tcSpecPrag
        - TcBinds.tcTySig

  This decision is taken in setImplicationStatus, rather than TcErrors
  so that we can discard implication constraints that we don't need.
  So ics_dead consists only of the *reportable* redundant givens.

----- Shortcomings

Consider (see Trac #9939)
    f2 :: (Eq a, Ord a) => a -> a -> Bool
    -- Ord a redundant, but Eq a is reported
    f2 x y = (x == y)

We report (Eq a) as redundant, whereas actually (Ord a) is.  But it's
really not easy to detect that!


Note [Cutting off simpl_loop]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is very important not to iterate in simpl_loop unless there is a chance
of progress.  Trac #8474 is a classic example:

  * There's a deeply-nested chain of implication constraints.
       ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int

  * From the innermost one we get a [D] alpha ~ Int,
    but alpha is untouchable until we get out to the outermost one

  * We float [D] alpha~Int out (it is in floated_eqs), but since alpha
    is untouchable, the solveInteract in simpl_loop makes no progress

  * So there is no point in attempting to re-solve
       ?yn:betan => [W] ?x:Int
    via solveNestedImplications, because we'll just get the
    same [D] again

  * If we *do* re-solve, we'll get an ininite loop. It is cut off by
    the fixed bound of 10, but solving the next takes 10*10*...*10 (ie
    exponentially many) iterations!

Conclusion: we should call solveNestedImplications only if we did
some unifiction in solveSimpleWanteds; because that's the only way
we'll get more Givens (a unificaiton is like adding a Given) to
allow the implication to make progress.
-}

promoteTyVar :: TcLevel -> TcTyVar  -> TcM ()
-- When we float a constraint out of an implication we must restore
-- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
-- See Note [Promoting unification variables]
promoteTyVar tclvl tv
  | isFloatedTouchableMetaTyVar tclvl tv
  = do { cloned_tv <- TcM.cloneMetaTyVar tv
       ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
       ; TcM.writeMetaTyVar tv (mkTyVarTy rhs_tv) }
  | otherwise
  = return ()

promoteTyVarTcS :: TcLevel -> TcTyVar  -> TcS ()
-- When we float a constraint out of an implication we must restore
-- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType
-- See Note [Promoting unification variables]
-- We don't just call promoteTyVar because we want to use unifyTyVar,
-- not writeMetaTyVar
promoteTyVarTcS tclvl tv
  | isFloatedTouchableMetaTyVar tclvl tv
  = do { cloned_tv <- TcS.cloneMetaTyVar tv
       ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl
       ; unifyTyVar tv (mkTyVarTy rhs_tv) }
  | otherwise
  = return ()

-- | If the tyvar is a RuntimeRep var, set it to PtrRepLifted. Returns whether or
-- not this happened.
defaultTyVar :: TcTyVar -> TcM ()
-- Precondition: MetaTyVars only
-- See Note [DefaultTyVar]
defaultTyVar the_tv
  | isRuntimeRepVar the_tv
  = do { traceTc "defaultTyVar RuntimeRep" (ppr the_tv)
       ; writeMetaTyVar the_tv ptrRepLiftedTy }

  | otherwise = return ()    -- The common case

-- | Like 'defaultTyVar', but in the TcS monad.
defaultTyVarTcS :: TcTyVar -> TcS Bool
defaultTyVarTcS the_tv
  | isRuntimeRepVar the_tv
  = do { traceTcS "defaultTyVarTcS RuntimeRep" (ppr the_tv)
       ; unifyTyVar the_tv ptrRepLiftedTy
       ; return True }
  | otherwise
  = return False  -- the common case

approximateWC :: WantedConstraints -> Cts
-- Postcondition: Wanted or Derived Cts
-- See Note [ApproximateWC]
approximateWC wc
  = float_wc emptyVarSet wc
  where
    float_wc :: TcTyCoVarSet -> WantedConstraints -> Cts
    float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics })
      = filterBag is_floatable simples `unionBags`
        do_bag (float_implic new_trapping_tvs) implics
      where
        is_floatable ct = tyCoVarsOfCt ct `disjointVarSet` new_trapping_tvs
        new_trapping_tvs = transCloVarSet grow trapping_tvs

        grow :: VarSet -> VarSet  -- Maps current trapped tyvars to newly-trapped ones
        grow so_far = foldrBag (grow_one so_far) emptyVarSet simples
        grow_one so_far ct tvs
          | ct_tvs `intersectsVarSet` so_far = tvs `unionVarSet` ct_tvs
          | otherwise                        = tvs
          where
            ct_tvs = tyCoVarsOfCt ct

    float_implic :: TcTyCoVarSet -> Implication -> Cts
    float_implic trapping_tvs imp
      | ic_no_eqs imp                 -- No equalities, so float
      = float_wc new_trapping_tvs (ic_wanted imp)
      | otherwise                     -- Don't float out of equalities
      = emptyCts                      -- See Note [ApproximateWC]
      where
        new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp
    do_bag :: (a -> Bag c) -> Bag a -> Bag c
    do_bag f = foldrBag (unionBags.f) emptyBag

{-
Note [ApproximateWC]
~~~~~~~~~~~~~~~~~~~~
approximateWC takes a constraint, typically arising from the RHS of a
let-binding whose type we are *inferring*, and extracts from it some
*simple* constraints that we might plausibly abstract over.  Of course
the top-level simple constraints are plausible, but we also float constraints
out from inside, if they are not captured by skolems.

The same function is used when doing type-class defaulting (see the call
to applyDefaultingRules) to extract constraints that that might be defaulted.

There are two caveats:

1.  We do *not* float anything out if the implication binds equality
    constraints, because that defeats the OutsideIn story.  Consider
       data T a where
         TInt :: T Int
         MkT :: T a

       f TInt = 3::Int

    We get the implication (a ~ Int => res ~ Int), where so far we've decided
      f :: T a -> res
    We don't want to float (res~Int) out because then we'll infer
      f :: T a -> Int
    which is only on of the possible types. (GHC 7.6 accidentally *did*
    float out of such implications, which meant it would happily infer
    non-principal types.)

2. We do not float out an inner constraint that shares a type variable
   (transitively) with one that is trapped by a skolem.  Eg
       forall a.  F a ~ beta, Integral beta
   We don't want to float out (Integral beta).  Doing so would be bad
   when defaulting, because then we'll default beta:=Integer, and that
   makes the error message much worse; we'd get
       Can't solve  F a ~ Integer
   rather than
       Can't solve  Integral (F a)

   Moreover, floating out these "contaminated" constraints doesn't help
   when generalising either. If we generalise over (Integral b), we still
   can't solve the retained implication (forall a. F a ~ b).  Indeed,
   arguably that too would be a harder error to understand.

Note [DefaultTyVar]
~~~~~~~~~~~~~~~~~~~
defaultTyVar is used on any un-instantiated meta type variables to
default any RuntimeRep variables to PtrRepLifted.  This is important
to ensure that instance declarations match.  For example consider

     instance Show (a->b)
     foo x = show (\_ -> True)

Then we'll get a constraint (Show (p ->q)) where p has kind (TYPE r),
and that won't match the typeKind (*) in the instance decl.  See tests
tc217 and tc175.

We look only at touchable type variables. No further constraints
are going to affect these type variables, so it's time to do it by
hand.  However we aren't ready to default them fully to () or
whatever, because the type-class defaulting rules have yet to run.

An alternate implementation would be to emit a derived constraint setting
the RuntimeRep variable to PtrRepLifted, but this seems unnecessarily indirect.

Note [Promote _and_ default when inferring]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we are inferring a type, we simplify the constraint, and then use
approximateWC to produce a list of candidate constraints.  Then we MUST

  a) Promote any meta-tyvars that have been floated out by
     approximateWC, to restore invariant (MetaTvInv) described in
     Note [TcLevel and untouchable type variables] in TcType.

  b) Default the kind of any meta-tyyvars that are not mentioned in
     in the environment.

To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we
have an instance (C ((x:*) -> Int)).  The instance doesn't match -- but it
should!  If we don't solve the constraint, we'll stupidly quantify over
(C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over
(b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332.
Trac #7641 is a simpler example.

Note [Promoting unification variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we float an equality out of an implication we must "promote" free
unification variables of the equality, in order to maintain Invariant
(MetaTvInv) from Note [TcLevel and untouchable type variables] in TcType.  for the
leftover implication.

This is absolutely necessary. Consider the following example. We start
with two implications and a class with a functional dependency.

    class C x y | x -> y
    instance C [a] [a]

    (I1)      [untch=beta]forall b. 0 => F Int ~ [beta]
    (I2)      [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c]

We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2.
They may react to yield that (beta := [alpha]) which can then be pushed inwards
the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that
(alpha := a). In the end we will have the skolem 'b' escaping in the untouchable
beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs:

    class C x y | x -> y where
     op :: x -> y -> ()

    instance C [a] [a]

    type family F a :: *

    h :: F Int -> ()
    h = undefined

    data TEx where
      TEx :: a -> TEx

    f (x::beta) =
        let g1 :: forall b. b -> ()
            g1 _ = h [x]
            g2 z = case z of TEx y -> (h [[undefined]], op x [y])
        in (g1 '3', g2 undefined)


Note [Solving Family Equations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
After we are done with simplification we may be left with constraints of the form:
     [Wanted] F xis ~ beta
If 'beta' is a touchable unification variable not already bound in the TyBinds
then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'.

When is it ok to do so?
    1) 'beta' must not already be defaulted to something. Example:

           [Wanted] F Int  ~ beta   <~ Will default [beta := F Int]
           [Wanted] F Char ~ beta   <~ Already defaulted, can't default again. We
                                       have to report this as unsolved.

    2) However, we must still do an occurs check when defaulting (F xis ~ beta), to
       set [beta := F xis] only if beta is not among the free variables of xis.

    3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS
       of type family equations. See Inert Set invariants in TcInteract.

This solving is now happening during zonking, see Note [Unflattening while zonking]
in TcMType.


*********************************************************************************
*                                                                               *
*                          Floating equalities                                  *
*                                                                               *
*********************************************************************************

Note [Float Equalities out of Implications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For ordinary pattern matches (including existentials) we float
equalities out of implications, for instance:
     data T where
       MkT :: Eq a => a -> T
     f x y = case x of MkT _ -> (y::Int)
We get the implication constraint (x::T) (y::alpha):
     forall a. [untouchable=alpha] Eq a => alpha ~ Int
We want to float out the equality into a scope where alpha is no
longer untouchable, to solve the implication!

But we cannot float equalities out of implications whose givens may
yield or contain equalities:

      data T a where
        T1 :: T Int
        T2 :: T Bool
        T3 :: T a

      h :: T a -> a -> Int

      f x y = case x of
                T1 -> y::Int
                T2 -> y::Bool
                T3 -> h x y

We generate constraint, for (x::T alpha) and (y :: beta):
   [untouchables = beta] (alpha ~ Int => beta ~ Int)   -- From 1st branch
   [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch
   (alpha ~ beta)                                      -- From 3rd branch

If we float the equality (beta ~ Int) outside of the first implication and
the equality (beta ~ Bool) out of the second we get an insoluble constraint.
But if we just leave them inside the implications, we unify alpha := beta and
solve everything.

Principle:
    We do not want to float equalities out which may
    need the given *evidence* to become soluble.

Consequence: classes with functional dependencies don't matter (since there is
no evidence for a fundep equality), but equality superclasses do matter (since
they carry evidence).
-}

floatEqualities :: [TcTyVar] -> Bool
                -> WantedConstraints
                -> TcS (Cts, WantedConstraints)
-- Main idea: see Note [Float Equalities out of Implications]
--
-- Precondition: the wc_simple of the incoming WantedConstraints are
--               fully zonked, so that we can see their free variables
--
-- Postcondition: The returned floated constraints (Cts) are only
--                Wanted or Derived
--
-- Also performs some unifications (via promoteTyVar), adding to
-- monadically-carried ty_binds. These will be used when processing
-- floated_eqs later
--
-- Subtleties: Note [Float equalities from under a skolem binding]
--             Note [Skolem escape]
floatEqualities skols no_given_eqs
                wanteds@(WC { wc_simple = simples })
  | not no_given_eqs  -- There are some given equalities, so don't float
  = return (emptyBag, wanteds)   -- Note [Float Equalities out of Implications]
  | otherwise
  = do { outer_tclvl <- TcS.getTcLevel
       ; mapM_ (promoteTyVarTcS outer_tclvl)
               (varSetElems (tyCoVarsOfCts float_eqs))
           -- See Note [Promoting unification variables]

       ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols
                                          , text "Simples =" <+> ppr simples
                                          , text "Floated eqs =" <+> ppr float_eqs])
       ; return ( float_eqs
                , wanteds { wc_simple = remaining_simples } ) }
  where
    skol_set = mkVarSet skols
    (float_eqs, remaining_simples) = partitionBag (usefulToFloat skol_set) simples

usefulToFloat :: VarSet -> Ct -> Bool
usefulToFloat skol_set ct   -- The constraint is un-flattened and de-canonicalised
  = is_meta_var_eq pred &&
    (tyCoVarsOfType pred `disjointVarSet` skol_set)
  where
    pred = ctPred ct

      -- Float out alpha ~ ty, or ty ~ alpha
      -- which might be unified outside
      -- See Note [Which equalities to float]
    is_meta_var_eq pred
      | EqPred NomEq ty1 ty2 <- classifyPredType pred
      = case (tcGetTyVar_maybe ty1, tcGetTyVar_maybe ty2) of
          (Just tv1, _) -> float_tv_eq tv1 ty2
          (_, Just tv2) -> float_tv_eq tv2 ty1
          _             -> False
      | otherwise
      = False

    float_tv_eq tv1 ty2  -- See Note [Which equalities to float]
      =  isMetaTyVar tv1
      && (not (isSigTyVar tv1) || isTyVarTy ty2)

{- Note [Float equalities from under a skolem binding]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which of the simple equalities can we float out?  Obviously, only
ones that don't mention the skolem-bound variables.  But that is
over-eager. Consider
   [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int
The second constraint doesn't mention 'a'.  But if we float it,
we'll promote gamma[2] to gamma'[1].  Now suppose that we learn that
beta := Bool, and F a Bool = a, and G Bool _ = Int.  Then we'll
we left with the constraint
   [2] forall a. a ~ gamma'[1]
which is insoluble because gamma became untouchable.

Solution: float only constraints that stand a jolly good chance of
being soluble simply by being floated, namely ones of form
      a ~ ty
where 'a' is a currently-untouchable unification variable, but may
become touchable by being floated (perhaps by more than one level).

We had a very complicated rule previously, but this is nice and
simple.  (To see the notes, look at this Note in a version of
TcSimplify prior to Oct 2014).

Note [Which equalities to float]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Which equalities should we float?  We want to float ones where there
is a decent chance that floating outwards will allow unification to
happen.  In particular:

   Float out equalities of form (alpaha ~ ty) or (ty ~ alpha), where

   * alpha is a meta-tyvar.

   * And 'alpha' is not a SigTv with 'ty' being a non-tyvar.  In that
     case, floating out won't help either, and it may affect grouping
     of error messages.

Note [Skolem escape]
~~~~~~~~~~~~~~~~~~~~
You might worry about skolem escape with all this floating.
For example, consider
    [2] forall a. (a ~ F beta[2] delta,
                   Maybe beta[2] ~ gamma[1])

The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and
solve with gamma := beta. But what if later delta:=Int, and
  F b Int = b.
Then we'd get a ~ beta[2], and solve to get beta:=a, and now the
skolem has escaped!

But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2]
to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be.


*********************************************************************************
*                                                                               *
*                          Defaulting and disamgiguation                        *
*                                                                               *
*********************************************************************************
-}

applyDefaultingRules :: WantedConstraints -> TcS Bool
-- True <=> I did some defaulting, by unifying a meta-tyvar
-- Imput WantedConstraints are not necessarily zonked

applyDefaultingRules wanteds
  | isEmptyWC wanteds
  = return False
  | otherwise
  = do { info@(default_tys, _) <- getDefaultInfo
       ; wanteds               <- TcS.zonkWC wanteds

       ; let groups = findDefaultableGroups info wanteds

       ; traceTcS "applyDefaultingRules {" $
                  vcat [ text "wanteds =" <+> ppr wanteds
                       , text "groups  =" <+> ppr groups
                       , text "info    =" <+> ppr info ]

       ; something_happeneds <- mapM (disambigGroup default_tys) groups

       ; traceTcS "applyDefaultingRules }" (ppr something_happeneds)

       ; return (or something_happeneds) }

findDefaultableGroups
    :: ( [Type]
       , (Bool,Bool) )     -- (Overloaded strings, extended default rules)
    -> WantedConstraints   -- Unsolved (wanted or derived)
    -> [(TyVar, [Ct])]
findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds
  | null default_tys
  = []
  | otherwise
  = [ (tv, map fstOf3 group)
    | group@((_,_,tv):_) <- unary_groups
    , defaultable_tyvar tv
    , defaultable_classes (map sndOf3 group) ]
  where
    simples                = approximateWC wanteds
    (unaries, non_unaries) = partitionWith find_unary (bagToList simples)
    unary_groups           = equivClasses cmp_tv unaries

    unary_groups :: [[(Ct, Class, TcTyVar)]]  -- (C tv) constraints
    unaries      ::  [(Ct, Class, TcTyVar)]   -- (C tv) constraints
    non_unaries  :: [Ct]                      -- and *other* constraints

        -- Finds unary type-class constraints
        -- But take account of polykinded classes like Typeable,
        -- which may look like (Typeable * (a:*))   (Trac #8931)
    find_unary cc
        | Just (cls,tys)   <- getClassPredTys_maybe (ctPred cc)
        , [ty] <- filterOutInvisibleTypes (classTyCon cls) tys
              -- Ignore invisible arguments for this purpose
        , Just tv <- tcGetTyVar_maybe ty
        , isMetaTyVar tv  -- We might have runtime-skolems in GHCi, and
                          -- we definitely don't want to try to assign to those!
        = Left (cc, cls, tv)
    find_unary cc = Right cc  -- Non unary or non dictionary

    bad_tvs :: TcTyCoVarSet  -- TyVars mentioned by non-unaries
    bad_tvs = mapUnionVarSet tyCoVarsOfCt non_unaries

    cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2

    defaultable_tyvar tv
        = let b1 = isTyConableTyVar tv  -- Note [Avoiding spurious errors]
              b2 = not (tv `elemVarSet` bad_tvs)
          in b1 && b2

    defaultable_classes clss
        | extended_defaults = any isInteractiveClass clss
        | otherwise         = all is_std_class clss && (any is_num_class clss)

    -- In interactive mode, or with -XExtendedDefaultRules,
    -- we default Show a to Show () to avoid graututious errors on "show []"
    isInteractiveClass cls
        = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey
                                                   , ordClassKey, foldableClassKey
                                                   , traversableClassKey])

    is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
    -- is_num_class adds IsString to the standard numeric classes,
    -- when -foverloaded-strings is enabled

    is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey))
    -- Similarly is_std_class

------------------------------
disambigGroup :: [Type]            -- The default types
              -> (TcTyVar, [Ct])   -- All classes of the form (C a)
                                   --  sharing same type variable
              -> TcS Bool   -- True <=> something happened, reflected in ty_binds

disambigGroup [] _
  = return False
disambigGroup (default_ty:default_tys) group@(the_tv, wanteds)
  = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ])
       ; fake_ev_binds_var <- TcS.newTcEvBinds
       ; tclvl             <- TcS.getTcLevel
       ; (success, _) <- nestImplicTcS (Just fake_ev_binds_var) emptyVarSet
                                       (pushTcLevel tclvl) try_group

       ; if success then
             -- Success: record the type variable binding, and return
             do { unifyTyVar the_tv default_ty
                ; wrapWarnTcS $ warnDefaulting wanteds default_ty
                ; traceTcS "disambigGroup succeeded }" (ppr default_ty)
                ; return True }
         else
             -- Failure: try with the next type
             do { traceTcS "disambigGroup failed, will try other default types }"
                           (ppr default_ty)
                ; disambigGroup default_tys group } }
  where
    try_group
      | Just subst <- mb_subst
      = do { lcl_env <- TcS.getLclEnv
           ; let loc = CtLoc { ctl_origin = GivenOrigin UnkSkol
                             , ctl_env    = lcl_env
                             , ctl_t_or_k = Nothing
                             , ctl_depth  = initialSubGoalDepth }
           ; wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred)
                                wanteds
           ; fmap isEmptyWC $
             solveSimpleWanteds $ listToBag $
             map mkNonCanonical wanted_evs }

      | otherwise
      = return False

    the_ty   = mkTyVarTy the_tv
    mb_subst = tcMatchTy the_ty default_ty
      -- Make sure the kinds match too; hence this call to tcMatchTy
      -- E.g. suppose the only constraint was (Typeable k (a::k))
      -- With the addition of polykinded defaulting we also want to reject
      -- ill-kinded defaulting attempts like (Eq []) or (Foldable Int) here.


{-
Note [Avoiding spurious errors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When doing the unification for defaulting, we check for skolem
type variables, and simply don't default them.  For example:
   f = (*)      -- Monomorphic
   g :: Num a => a -> a
   g x = f x x
Here, we get a complaint when checking the type signature for g,
that g isn't polymorphic enough; but then we get another one when
dealing with the (Num a) context arising from f's definition;
we try to unify a with Int (to default it), but find that it's
already been unified with the rigid variable from g's type sig.
-}