h-$ku C C      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefgh ijklmnopqrstuvwxyz{|}~                                                                                                                                                  !!!!""""###$%%%$%%%$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$%%%%%$%%%%%%%%%&&&&&&&&&&&'&&&&&&''''''''('''''''((((('((((((('('(('(('''(((&&&&&&&&&&&&&&&&&&&&&&(&&((''((''''''''''''''(((((('(''''''''(((('''''''''''''''('''(((((((&&&&&&&&&&&&'&&&&&&&&&&&&&&&&&&&&&&&&&&'''''''''''''''''''''''''''''''''''''''''''''    )))))))))))*++++++++++++++++++++                                                             , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , - - - - - - - - - - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . / / / / / / / / / / / / / / / / / / / / / / / / / / / 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1111122222222222222333333333333333333345666666677778888888899999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999:::::::::::::::::::::::::::::::::;;;;;;<<<<<<<<<===>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>??????????@@@@@@@@AAABCCCCCCCDDDEEFFFFFFEGEEEEFGGFHIIIIIIIIIIJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUVVVVVWWWWWWWWXYYYYYYYZZZZZZZZZ[[[[[[[[[[[[\\\\\\\\\]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^______________________________________________________________```````````````````````````aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccdddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeefffffffffffffffffffffffffffffffffffffffffffffffffggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllmmmmmnnnnnnoooooooooppppppppppppqqqqqqqqqqrrrrrrrrrrrrsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssttuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u!u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"u"v"v"v"v"v"v"v"v"v"v"v"v"v"v"v"v"v"w"w"w"w"w"w"w"w"w"x"x"x"x"x"x"x"y"y"y"y"y"y"y"y"y"z"z"z"z"z"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8"8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#8#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#{#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$|$}$}$}$}$}$}$}$}$}$}$}$}$}$}$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$~$$$$$$$$$$$$$$$$$$$$$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))))))))F)F)))))))))))))))))))))))))7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7)7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7*7***********************************++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?+?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,------------------@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.F.F.F.F.F.F.F.F.F.F.F.F.F.F.F.F.F.F.F.F.F........................................................................./// / ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555566666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777778888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888899999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<================================================================================================================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJ J J J J J J J J J J J J J J J J J J J J J J J J J J JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKEKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCLCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMCMMMMMMMMHMFMFMFMFMFMFMFMENENENENENGNGNGNENENENGNENENENENENENENENGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNFNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNFNGNFNGNGNFNFNNNFNFNFNFNFNFNFNFNFNFNFNFNFNFNGNENGNENFNFNFNGNENHNHNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGNGOGOGOGOGOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP P P P P P P P P P P P P P P P P P P P P P P Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q Q QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFRFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVHVHVHVHVHVHVHVHVHVHVHVHVHVHVHVHVVVVVVVVVVVVVVVVVVV6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6V6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6W6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6X6XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZJZJZJZJZJZJZJZJZJZJZJZJZJZJZJZJZJZJZJZJZJZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZEZE[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[E[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_____A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A_A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A`A``````````````aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;b;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;c;cBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBcBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdBdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdDdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggh5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5h5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5j5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5k5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5l5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5m5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5n5nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooootototoooooooooooooooooooooooooooooooooooooooooooooooppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqEC~|y{}zb`acijk]_^*x)873FNO56#$ &/+ml n o-' (rusptqB.01%\,WXYVZ[DAQRP?:@LK9JM;<=>EC4"w v!NoneNoneGghc ghc ghc ghc ghc       None „Ä!None":(c) Clark Gaebel 2012 (c) Johan Tibel 2012 BSD-stylelibraries@haskell.orgportableNone<0Return a word where only the highest bit is set.#None'The same as a regular Haskell pair, but  (x :*: _|_) = (_|_ :*: y) = _|_ )Convert a strict pair to a standard pair.%>(c) Daan Leijen 2002 (c) Joachim Breitner 2011 BSD-stylelibraries@haskell.orgportableNone !9A set of integers.O(n+m). See .O(1). Is the set empty?O(n). Cardinality of the set. O(\min(n,W))#. Is the value a member of the set? O(\min(n,W)) . Is the element not in the set? O(\min(n,W))2. Find largest element smaller than the given one. lookupLT 3 (fromList [3, 5]) == Nothing lookupLT 5 (fromList [3, 5]) == Just 3 O(\min(n,W))3. Find smallest element greater than the given one. lookupGT 4 (fromList [3, 5]) == Just 5 lookupGT 5 (fromList [3, 5]) == Nothing O(\min(n,W))9. Find largest element smaller or equal to the given one. lookupLE 2 (fromList [3, 5]) == Nothing lookupLE 4 (fromList [3, 5]) == Just 3 lookupLE 5 (fromList [3, 5]) == Just 5 O(\min(n,W)):. Find smallest element greater or equal to the given one. lookupGE 3 (fromList [3, 5]) == Just 3 lookupGE 4 (fromList [3, 5]) == Just 5 lookupGE 6 (fromList [3, 5]) == NothingO(1). The empty set.O(1). A set of one element. O(\min(n,W)). Add a value to the set. There is no left- or right bias for Word64Sets. O(\min(n,W)). Delete a value in the set. Returns the original set when the value was not present.ghc O(\min(n,W)). ( f x s) can delete or insert x in s0 depending on whether it is already present in s. In short:  x <$>  f x s = f ( x s) Note:  is a variant of the at combinator from Control.Lens.At.The union of a list of sets.O(n+m). The union of two sets.O(n+m). Difference between two sets.O(n+m). The intersection of two sets.O(n+m)8. Is this a proper subset? (ie. a subset but not equal).O(n+m). Is this a subset? (s1 `isSubsetOf` s2) tells whether s1 is a subset of s2.ghc O(n+m). Check whether two sets are disjoint (i.e. their intersection is empty). disjoint (fromList [2,4,6]) (fromList [1,3]) == True disjoint (fromList [2,4,6,8]) (fromList [2,3,5,7]) == False disjoint (fromList [1,2]) (fromList [1,2,3,4]) == False disjoint (fromList []) (fromList []) == TrueO(n)2. Filter all elements that satisfy some predicate.O(n)0. partition the set according to some predicate.ghc O(\min(n,W)). Take while a predicate on the elements holds. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k. See note at . takeWhileAntitone p =  .  p .  takeWhileAntitone p =  p ghc O(\min(n,W)). Drop while a predicate on the elements holds. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k. See note at . dropWhileAntitone p =  .  p .  dropWhileAntitone p =  (not . p) ghc O(\min(n,W)). Divide a set at the point where a predicate on the elements stops holding. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k. spanAntitone p xs = ( p xs,  p xs) spanAntitone p xs =  p xs  Note: if p is not actually antitone, then  spanAntitone will split the set at some  unspecified point. O(\min(n,W)). The expression ( x set ) is a pair  (set1,set2) where set1 comprises the elements of set less than x and set2 comprises the elements of set greater than x. =split 3 (fromList [1..5]) == (fromList [1,2], fromList [4,5]) O(\min(n,W)) . Performs a  but also returns whether the pivot element was found in the original set. O(\min(n,W)). Retrieves the maximal key of the set, and the set stripped of that element, or K if passed an empty set. O(\min(n,W)). Retrieves the minimal key of the set, and the set stripped of that element, or K if passed an empty set. O(\min(n,W))&. Delete and find the minimal element. 0deleteFindMin set = (findMin set, deleteMin set) O(\min(n,W))&. Delete and find the maximal element. 0deleteFindMax set = (findMax set, deleteMax set) O(\min(n,W))!. The minimal element of the set. O(\min(n,W)). The maximal element of a set. O(\min(n,W)). Delete the minimal element. Returns an empty set if the set is empty.=Note that this is a change of behaviour for consistency with 0 @ versions prior to 0.5 threw an error if the  was already empty. O(\min(n,W)). Delete the maximal element. Returns an empty set if the set is empty.=Note that this is a change of behaviour for consistency with 0 @ versions prior to 0.5 threw an error if the  was already empty.O(n \min(n,W)).  f s! is the set obtained by applying f to each element of s.It's worth noting that the size of the result may be smaller if, for some (x,y), x /= y && f x == f yghcO(n). The f s ==  f s, but works only when f is strictly increasing.  The precondition is not checked. Semi-formally, we have: and [x < y ==> f x < f y | x <- ls, y <- ls] ==> mapMonotonic f s == map f s where ls = toList sO(n). Fold the elements in the set using the given right-associative binary operator. This function is an equivalent of ( and is present for compatibility only.Please note that fold will be deprecated in the future and removed.O(n). Fold the elements in the set using the given right-associative binary operator, such that  f z ==  f z . . For example,  toAscList set = foldr (:) [] setO(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the elements in the set using the given left-associative binary operator, such that  f z ==  f z . . For example, (toDescList set = foldl (flip (:)) [] setO(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). An alias of . The elements of a set in ascending order. Subject to list fusion.O(n). Convert the set to a list of elements. Subject to list fusion.O(n). Convert the set to an ascending list of elements. Subject to list fusion.O(n). Convert the set to a descending list of elements. Subject to list fusion.O(n \min(n,W))'. Create a set from a list of integers.O(n)3. Build a set from an ascending list of elements. :The precondition (input list is ascending) is not checked.O(n)<. Build a set from an ascending list of distinct elements. The precondition (input list is strictly ascending) is not checked.ĄO(n)0. Build a set from a monotonic list of elements.The precise conditions under which this function works are subtle: For any branch mask, keys with the same prefix w.r.t. the branch mask must occur consecutively in the list.O(n \min(n,W)). Show the tree that implements the set. The tree is shown in a compressed, hanging format.O(n \min(n,W)). The expression ( hang wide map.) shows the tree that implements the set. If hang is M, a hanging6 tree is shown otherwise a rotated tree is shown. If wide is M!, an extra wide version is shown.O(1). Decompose a set into pieces based on the structure of the underlying tree. This function is useful for consuming a set in parallel.No guarantee is made as to the sizes of the pieces; an internal, but deterministic process determines this. However, it is guaranteed that the pieces returned will be in ascending order (all elements in the first submap less than all elements in the second, and so on). Examples: splitRoot (fromList [1..120]) == [fromList [1..63],fromList [64..120]] splitRoot empty == []Note that the current implementation does not return more than two subsets, but you should not depend on this behaviour because it can change in the future without notice. Also, the current version does not continue splitting all the way to individual singleton sets -- it stops at some point.ghcghc          #$>(c) Daan Leijen 2002 (c) Joachim Breitner 2011 BSD-stylelibraries@haskell.orgportableNone77&(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 (c) wren romano 2016 BSD-stylelibraries@haskell.orgportableNone !ghc 7A tactic for dealing with keys present in both maps in .A tactic of type SimpleWhenMatched x y z6 is an abstract representation of a function of type Key -> x -> y -> Maybe z.ghc 7A tactic for dealing with keys present in both maps in  or .A tactic of type WhenMatched f x y z6 is an abstract representation of a function of type Key -> x -> y -> f (Maybe z).ghc A tactic for dealing with keys present in one map but not the other in .A tactic of type SimpleWhenMissing x z6 is an abstract representation of a function of type Key -> x -> Maybe z.ghc A tactic for dealing with keys present in one map but not the other in  or .A tactic of type WhenMissing f k x z6 is an abstract representation of a function of type Key -> x -> f (Maybe z).A map of integers to values a. O(\min(n,W))". Find the value at a key. Calls i# when the element can not be found. fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map fromList [(5,'a'), (3,'b')] ! 5 == 'a'ghc  O(\min(n,W))$. Find the value at a key. Returns K# when the element can not be found. fromList [(5,'a'), (3,'b')] !? 1 == Nothing fromList [(5,'a'), (3,'b')] !? 5 == Just 'a'Same as .O(1). Is the map empty? Data.Word64Map.null (empty) == True Data.Word64Map.null (singleton 1 'a') == FalseO(n) . Number of elements in the map. size empty == 0 size (singleton 1 'a') == 1 size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3 O(\min(n,W))!. Is the key a member of the map? member 5 (fromList [(5,'a'), (3,'b')]) == True member 1 (fromList [(5,'a'), (3,'b')]) == False O(\min(n,W))%. Is the key not a member of the map? notMember 5 (fromList [(5,'a'), (3,'b')]) == False notMember 1 (fromList [(5,'a'), (3,'b')]) == True O(\min(n,W))1. Lookup the value at a key in the map. See also . O(\min(n,W)). The expression ( def k map) returns the value at key k or returns def, when the key is not an element of the map. findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x' findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a' O(\min(n,W)). Find largest key smaller than the given one and return the corresponding (key, value) pair. lookupLT 3 (fromList [(3,'a'), (5,'b')]) == Nothing lookupLT 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a') O(\min(n,W)). Find smallest key greater than the given one and return the corresponding (key, value) pair. lookupGT 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b') lookupGT 5 (fromList [(3,'a'), (5,'b')]) == Nothing O(\min(n,W)). Find largest key smaller or equal to the given one and return the corresponding (key, value) pair. lookupLE 2 (fromList [(3,'a'), (5,'b')]) == Nothing lookupLE 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a') lookupLE 5 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b') O(\min(n,W)). Find smallest key greater or equal to the given one and return the corresponding (key, value) pair. lookupGE 3 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a') lookupGE 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b') lookupGE 6 (fromList [(3,'a'), (5,'b')]) == NothingghcO(n+m). Check whether the key sets of two maps are disjoint (i.e. their  is empty). disjoint (fromList [(2,'a')]) (fromList [(1,()), (3,())]) == True disjoint (fromList [(2,'a')]) (fromList [(1,'a'), (2,'b')]) == False disjoint (fromList []) (fromList []) == True 'disjoint a b == null (intersection a b)ghcRelate the keys of one map to the values of the other, by using the values of the former as keys for lookups in the latter. Complexity:  O(n * \min(m,W)) , where m" is the size of the first argument compose (fromList [('a', "A"), ('b', "B")]) (fromList [(1,'a'),(2,'b'),(3,'z')]) = fromList [(1,"A"),(2,"B")] ( bc ab ) = (bc  ) <=< (ab ) Note: Prior to v0.6.4, Data.Word64Map.Strict exposed a version of & that forced the values of the output ,. This version does not force these values.O(1). The empty map. )empty == fromList [] size empty == 0O(1). A map of one element. singleton 1 'a' == fromList [(1, 'a')] size (singleton 1 'a') == 1 O(\min(n,W)). Insert a new key/value pair in the map. If the key is already present in the map, the associated value is replaced with the supplied value, i.e.  is equivalent to  {. insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')] insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')] insert 5 'x' empty == singleton 5 'x' O(\min(n,W))%. Insert with a combining function.  f key value mp) will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert f new_value old_value. insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")] insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] insertWith (++) 5 "xxx" empty == singleton 5 "xxx" O(\min(n,W))%. Insert with a combining function.  f key value mp) will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert f key new_value old_value. let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")] insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] insertWithKey f 5 "xxx" empty == singleton 5 "xxx" O(\min(n,W)). The expression ( f k x map2) is a pair where the first element is equal to ( k map$) and the second element equal to ( f k x map). let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")]) insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")]) insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")This is how to define  insertLookup using insertLookupWithKey: let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")]) insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")]) O(\min(n,W)). Delete a key and its value from the map. When the key is not a member of the map, the original map is returned. delete 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" delete 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] delete 5 empty == empty O(\min(n,W)). Adjust a value at a specific key. When the key is not a member of the map, the original map is returned. adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] adjust ("new " ++) 7 empty == empty O(\min(n,W)). Adjust a value at a specific key. When the key is not a member of the map, the original map is returned. let f key x = (show key) ++ ":new " ++ x adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] adjustWithKey f 7 empty == empty O(\min(n,W)). The expression ( f k map) updates the value x at k (if it is in the map). If (f x) is K%, the element is deleted. If it is (L y ), the key k is bound to the new value y. let f x = if x == "a" then Just "new a" else Nothing update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" O(\min(n,W)). The expression ( f k map) updates the value x at k (if it is in the map). If (f k x) is K%, the element is deleted. If it is (L y ), the key k is bound to the new value y. let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" O(\min(n,W)). Lookup and update. The function returns original value, if it is updated. This is different behavior than >. Returns the original key value if the map entry is deleted. let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:new a")]) updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")]) updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a") O(\min(n,W)). The expression ( f k map) alters the value x at k, or absence thereof. 8 can be used to insert, delete, or update a value in an . In short :  k ( f k m) = f ( k m).ghc O(\min(n,W)). The expression ( f k map) alters the value x at k, or absence thereof.  can be used to inspect, insert, delete, or update a value in an . In short :  k  $  f k m = f ( k m).Example: interactiveAlter :: Int -> Word64Map String -> IO (Word64Map String) interactiveAlter k m = alterF f k m where f Nothing = do putStrLn $ show k ++ " was not found in the map. Would you like to add it?" getUserResponse1 :: IO (Maybe String) f (Just old) = do putStrLn $ "The key is currently bound to " ++ show old ++ ". Would you like to change or delete it?" getUserResponse2 :: IO (Maybe String)  is the most general operation for working with an individual key that may or may not be in a given map.Note:  is a flipped version of the at combinator from Control.Lens.At.The union of a list of maps. unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] == fromList [(3, "b"), (5, "a"), (7, "C")] unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])] == fromList [(3, "B3"), (5, "A3"), (7, "C")]8The union of a list of maps, with a combining operation. unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]O(n+m). The (left-biased) union of two maps. It prefers the first map when duplicate keys are encountered, i.e. ( ==  {). union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]O(n+m)&. The union with a combining function. unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]O(n+m)&. The union with a combining function. let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]O(n+m).. Difference between two maps (based on keys). difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b"O(n+m)'. Difference with a combining function. let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")]) == singleton 3 "b:B"O(n+m). Difference with a combining function. When two equal keys are encountered, the combining function is applied to the key and both values. If it returns K, the element is discarded (proper set difference). If it returns (L y+), the element is updated with a new value y. let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")]) == singleton 3 "3:b|B"ghcO(n+m)0. Remove all the keys in a given set from a map. m `withoutKeys` s =  (\k _ -> k  s) m O(n+m)=. The (left-biased) intersection of two maps (based on keys). intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a"ghcO(n+m)0. The restriction of a map to the keys in a set. m `restrictKeys` s =  (\k _ -> k  s) m ń O(\min(n,W))?. Restrict to the sub-map with all keys matching a key prefix.O(n+m)-. The intersection with a combining function. intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"O(n+m)-. The intersection with a combining function. let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"O(n+m):. A high-performance universal combining function. Using , all combining functions can be defined without any loss of efficiency (with exception of ,  and ,, where sharing of some nodes is lost with ).6Please make sure you know what is going on when using , otherwise you can be surprised by unexpected code growth or even corruption of the data structure.When  is given three arguments, it is inlined to the call site. You should therefore use  only to define your custom combining functions. For example, you could define ,  and  as myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2 myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2 myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2 When calling  combine only1 only2, a function combining two s is created, such thatif a key is present in both maps, it is passed with both corresponding values to the combine function. Depending on the result, the key is either present in the result with specified value, or is left out;>a nonempty subtree present only in the first map is passed to only1* and the output is added to the result;?a nonempty subtree present only in the second map is passed to only2* and the output is added to the result.The only1 and only2 methods must return a map with a subset (possibly empty) of the keys of the given map. The values can be modified arbitrarily. Most common variants of only1 and only2 are z and { , but for example  f or  f could be used for any f.ghc Map covariantly over a  f x.Map covariantly over a  f x', using only a 'Functor f' constraint.Map covariantly over a  f k x', using only a 'Functor f' constraint.ghc Map contravariantly over a  f _ x.ghc Map contravariantly over a  f _ y z.ghc Map contravariantly over a  f x _ z.ghc Along with zipWithMaybeAMatched, witnesses the isomorphism between WhenMatched f x y z and Key -> x -> y -> f (Maybe z).ghc Along with traverseMaybeMissing, witnesses the isomorphism between WhenMissing f x y and Key -> x -> f (Maybe y).ghc Map covariantly over a  f x y.ghc When a key is found in both maps, apply a function to the key and values and use the result in the merged map. zipWithMatched :: (Key -> x -> y -> z) -> SimpleWhenMatched x y zghc When a key is found in both maps, apply a function to the key and values to produce an action and use its result in the merged map.ghc When a key is found in both maps, apply a function to the key and values and maybe use the result in the merged map. zipWithMaybeMatched :: (Key -> x -> y -> Maybe z) -> SimpleWhenMatched x y zghc When a key is found in both maps, apply a function to the key and values, perform the resulting action, and maybe use the result in the merged map.This is the fundamental  tactic.ghc Drop all the entries whose keys are missing from the other map. $dropMissing :: SimpleWhenMissing x y/dropMissing = mapMaybeMissing (\_ _ -> Nothing)but  dropMissing is much faster.ghc Preserve, unchanged, the entries whose keys are missing from the other map. (preserveMissing :: SimpleWhenMissing x x=preserveMissing = Merge.Lazy.mapMaybeMissing (\_ x -> Just x)but preserveMissing is much faster.ghc ?Map over the entries whose keys are missing from the other map. 4mapMissing :: (k -> x -> y) -> SimpleWhenMissing x y5mapMissing f = mapMaybeMissing (\k x -> Just $ f k x)but  mapMissing is somewhat faster.ghc Map over the entries whose keys are missing from the other map, optionally removing some. This is the most powerful / tactic, but others are usually more efficient. mapMaybeMissing :: (Key -> x -> Maybe y) -> SimpleWhenMissing x y?mapMaybeMissing f = traverseMaybeMissing (\k x -> pure (f k x))but mapMaybeMissing uses fewer unnecessary 4 operations.ghc =Filter the entries whose keys are missing from the other map. :filterMissing :: (k -> x -> Bool) -> SimpleWhenMissing x xfilterMissing f = Merge.Lazy.mapMaybeMissing $ \k x -> guard (f k x) *> Just x#but this should be a little faster.ghc Filter the entries whose keys are missing from the other map using some 4 action. filterAMissing f = Merge.Lazy.traverseMaybeMissing $ \k x -> (\b -> guard b *> Just x) <$> f k x#but this should be a little faster.ƄO(n)". Filter keys and values using an 4 predicate.DŽ:This wasn't in Data.Bool until 4.7.0, so we define it hereghc Traverse over the entries whose keys are missing from the other map.ghc Traverse over the entries whose keys are missing from the other map, optionally producing values to put in the result. This is the most powerful 0 tactic, but others are usually more efficient.ghcO(n)'. Traverse keys/values and collect the L results.ghc Merge two maps. takes two  tactics, a  tactic and two maps. It uses the tactics to merge the maps. Its behavior is best understood via its fundamental tactics,  and .Consider merge (mapMaybeMissing g1) (mapMaybeMissing g2) (zipWithMaybeMatched f) m1 m2 Take, for example, m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] & will first "align" these maps by key: m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] It will then pass the individual entries and pairs of entries to g1, g2, or f as appropriate: maybes = [g1 0 'a', f 1 'b' "one", g2 2 "two", g1 3 'c', f 4 'd' "three"] This produces a @ for each key: keys = 0 1 2 3 4 results = [Nothing, Just True, Just False, Nothing, Just True]  Finally, the Just" results are collected into a map: 2return value = [(1, True), (2, False), (4, True)] The other tactics below are optimizations or simplifications of % for special cases. Most importantly, drops all the keys. leaves all the entries alone.When  is given three arguments, it is inlined at the call site. To prevent excessive inlining, you should typically use + to define your custom combining functions. Examples:unionWithKey f = merge preserveMissing preserveMissing (zipWithMatched f)intersectionWithKey f = merge dropMissing dropMissing (zipWithMatched f)0differenceWith f = merge diffPreserve diffDrop fsymmetricDifference = merge diffPreserve diffPreserve (\ _ _ _ -> Nothing)mapEachPiece f g h = merge (diffMapWithKey f) (diffMapWithKey g)ghc An applicative version of . takes two  tactics, a  tactic and two maps. It uses the tactics to merge the maps. Its behavior is best understood via its fundamental tactics,  and .Consider mergeA (traverseMaybeMissing g1) (traverseMaybeMissing g2) (zipWithMaybeAMatched f) m1 m2 Take, for example, m1 = [(0, 'a'), (1, 'b'), (3,'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] & will first "align" these maps by key: m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] It will then pass the individual entries and pairs of entries to g1, g2, or f as appropriate: actions = [g1 0 'a', f 1 'b' "one", g2 2 "two", g1 3 'c', f 4 'd' "three"] )Next, it will perform the actions in the actions# list in order from left to right. keys = 0 1 2 3 4 results = [Nothing, Just True, Just False, Nothing, Just True]  Finally, the Just" results are collected into a map: 2return value = [(1, True), (2, False), (4, True)] The other tactics below are optimizations or simplifications of % for special cases. Most importantly, drops all the keys. leaves all the entries alone. does not use the 4 context.When  is given three arguments, it is inlined at the call site. To prevent excessive inlining, you should generally only use & to define custom combining functions. O(\min(n,W))&. Update the value at the minimal key. updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")] updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" O(\min(n,W))&. Update the value at the maximal key. updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")] updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" O(\min(n,W)). Retrieves the maximal (key,value) pair of the map, and the map stripped of that element, or K if passed an empty map. maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b") maxViewWithKey empty == Nothing O(\min(n,W)). Retrieves the minimal (key,value) pair of the map, and the map stripped of that element, or K if passed an empty map. minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a") minViewWithKey empty == Nothing O(\min(n,W))&. Update the value at the maximal key. updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")] updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" O(\min(n,W))&. Update the value at the minimal key. updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")] updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" O(\min(n,W)). Retrieves the maximal key of the map, and the map stripped of that element, or K if passed an empty map. O(\min(n,W)). Retrieves the minimal key of the map, and the map stripped of that element, or K if passed an empty map. O(\min(n,W)). Delete and find the maximal element. This function throws an error if the map is empty. Use  if the map may be empty. O(\min(n,W)). Delete and find the minimal element. This function throws an error if the map is empty. Use  if the map may be empty. O(\min(n,W))&. The minimal key of the map. Returns K if the map is empty. O(\min(n,W))$. The minimal key of the map. Calls i if the map is empty. Use  if the map may be empty. O(\min(n,W))&. The maximal key of the map. Returns K if the map is empty. O(\min(n,W))$. The maximal key of the map. Calls i if the map is empty. Use  if the map may be empty. O(\min(n,W)). Delete the minimal key. Returns an empty map if the map is empty.=Note that this is a change of behaviour for consistency with 0 @ versions prior to 0.5 threw an error if the  was already empty. O(\min(n,W)). Delete the maximal key. Returns an empty map if the map is empty.=Note that this is a change of behaviour for consistency with 0 @ versions prior to 0.5 threw an error if the  was already empty.O(n+m). Is this a proper submap? (ie. a submap but not equal). Defined as ( =  (==)).O(n+m). Is this a proper submap? (ie. a submap but not equal). The expression ( f m1 m2 ) returns M when keys m1 and keys m2 are not equal, all keys in m1 are in m2 , and when f returns M when applied to their respective values. For example, the following expressions are all M: isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])But the following are all J: isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)]) isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)]) isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])O(n+m)!. Is this a submap? Defined as ( =  (==)).O(n+m). The expression ( f m1 m2 ) returns M if all keys in m1 are in m2 , and when f returns M when applied to their respective values. For example, the following expressions are all M: isSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) isSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])But the following are all J: isSubmapOfBy (==) (fromList [(1,2)]) (fromList [(1,1),(2,2)]) isSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])O(n),. Map a function over all values in the map. map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]O(n),. Map a function over all values in the map. let f key x = (show key) ++ ":" ++ x mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]O(n).  f s ==   $  ((k, v) -> (,) k  $ f k v) ( m)* That is, behaves exactly like a regular  except that the traversing function also has access to the key associated with a value. traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')]) traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == NothingO(n). The function  threads an accumulating argument through the map in ascending order of keys. let f a b = (a ++ b, b ++ "X") mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])O(n). The function  threads an accumulating argument through the map in ascending order of keys. let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X") mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])ȄO(n). The function Ȅ threads an accumulating argument through the map in ascending order of keys.O(n). The function  threads an accumulating argument through the map in descending order of keys.O(n \min(n,W)).  f s! is the map obtained by applying f to each key of s.)The size of the result may be smaller if f maps two or more distinct keys to the same new key. In this case the value at the greatest of the original keys is retained. mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")] mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c" mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"O(n \min(n,W)).  c f s! is the map obtained by applying f to each key of s.)The size of the result may be smaller if f maps two or more distinct keys to the same new key. In this case the associated values will be combined using c. mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab" mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"O(n \min(n,W)).  f s ==  f s, but works only when f2 is strictly monotonic. That is, for any values x and y, if x < y then f x < f y.  The precondition is not checked. Semi-formally, we have: and [x < y ==> f x < f y | x <- ls, y <- ls] ==> mapKeysMonotonic f s == mapKeys f s where ls = keys sThis means that f maps distinct original keys to distinct resulting keys. This function has slightly better performance than . mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]O(n)0. Filter all values that satisfy some predicate. filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" filter (> "x") (fromList [(5,"a"), (3,"b")]) == empty filter (< "a") (fromList [(5,"a"), (3,"b")]) == emptyO(n)5. Filter all keys/values that satisfy some predicate. filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"O(n). Partition the map according to some predicate. The first map contains all elements that satisfy the predicate, the second all elements that fail the predicate. See also . partition (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a") partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty) partition (> "x") (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])O(n). Partition the map according to some predicate. The first map contains all elements that satisfy the predicate, the second all elements that fail the predicate. See also . partitionWithKey (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b") partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty) partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])ghc O(\min(n,W)). Take while a predicate on the keys holds. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k. See note at . takeWhileAntitone p =  .  (p . fst) .  takeWhileAntitone p =  (\k _ -> p k) ghc O(\min(n,W)). Drop while a predicate on the keys holds. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k. See note at . dropWhileAntitone p =  .  (p . fst) .  dropWhileAntitone p =  (\k _ -> not (p k)) ghc O(\min(n,W)). Divide a map at the point where a predicate on the keys stops holding. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k. spanAntitone p xs = ( p xs,  p xs) spanAntitone p xs =  (\k _ -> p k) xs  Note: if p is not actually antitone, then  spanAntitone will split the map at some  unspecified point.O(n). Map values and collect the L results. let f x = if x == "a" then Just "new a" else Nothing mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"O(n)". Map keys/values and collect the L results. let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"O(n). Map values and separate the N and O results. let f a = if a < "c" then Left a else Right a mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")]) mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])O(n)#. Map keys/values and separate the N and O results. let f k a = if k < 5 then Left (k * 2) else Right (a ++ a) mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")]) mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")]) O(\min(n,W)). The expression ( k map ) is a pair  (map1,map2) where all keys in map1 are lower than k and all keys in map2 larger than k. Any key equal to k is found in neither map1 nor map2. split 2 (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3,"b"), (5,"a")]) split 3 (fromList [(5,"a"), (3,"b")]) == (empty, singleton 5 "a") split 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a") split 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", empty) split 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], empty) O(\min(n,W)) . Performs a  but also returns whether the pivot key was found in the original map. splitLookup 2 (fromList [(5,"a"), (3,"b")]) == (empty, Nothing, fromList [(3,"b"), (5,"a")]) splitLookup 3 (fromList [(5,"a"), (3,"b")]) == (empty, Just "b", singleton 5 "a") splitLookup 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Nothing, singleton 5 "a") splitLookup 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Just "a", empty) splitLookup 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], Nothing, empty)O(n). Fold the values in the map using the given right-associative binary operator, such that  f z ==  f z . . For example, elems map = foldr (:) [] map let f a len = len + (length a) foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the values in the map using the given left-associative binary operator, such that  f z ==  f z . . For example, %elems = reverse . foldl (flip (:)) [] let f len a = len + (length a) foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the keys and values in the map using the given right-associative binary operator, such that  f z ==  (c f) z . . For example, 0keys map = foldrWithKey (\k x ks -> k:ks) [] map let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")" foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the keys and values in the map using the given left-associative binary operator, such that  f z ==  (\z' (kx, x) -> f z' kx x) z . . For example, 2keys = reverse . foldlWithKey (\ks k x -> k:ks) [] let f result k a = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")" foldlWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (3:b)(5:a)"O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.ghcO(n). Fold the keys and values in the map using the given monoid, such that  f =  .  f*This can be an asymptotically faster than  or  for some monoids.O(n). Return all elements of the map in the ascending order of their keys. Subject to list fusion. elems (fromList [(5,"a"), (3,"b")]) == ["b","a"] elems empty == []O(n). Return all keys of the map in ascending order. Subject to list fusion.  replicate k 'a') (Data.Word64Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")] fromSet undefined Data.Word64Set.empty == emptyO(n). Convert the map to a list of key/value pairs. Subject to list fusion. toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")] toList empty == []O(n). Convert the map to a list of key/value pairs where the keys are in ascending order. Subject to list fusion. =toAscList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]O(n). Convert the map to a list of key/value pairs where the keys are in descending order. Subject to list fusion. >toDescList (fromList [(5,"a"), (3,"b")]) == [(5,"a"), (3,"b")]O(n \min(n,W)).. Create a map from a list of key/value pairs. fromList [] == empty fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")] fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]O(n \min(n,W)). Create a map from a list of key/value pairs with a combining function. See also . fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "ab"), (5, "cba")] fromListWith (++) [] == emptyO(n \min(n,W)). Build a map from a list of key/value pairs with a combining function. See also fromAscListWithKey'. let f key new_value old_value = show key ++ ":" ++ new_value ++ "|" ++ old_value fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "3:a|b"), (5, "5:c|5:b|a")] fromListWithKey f [] == emptyO(n). Build a map from a list of key/value pairs where the keys are in ascending order. fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]O(n). Build a map from a list of key/value pairs where the keys are in ascending order, with a combining function on equal keys. :The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]O(n). Build a map from a list of key/value pairs where the keys are in ascending order, with a combining function on equal keys. :The precondition (input list is ascending) is not checked. let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "5:b|a")]O(n). Build a map from a list of key/value pairs where the keys are in ascending order and all distinct. The precondition (input list is strictly ascending) is not checked. fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]ɄO(n). Build a map from a list of key/value pairs with monotonic keys and a combining function.The precise conditions under which this function works are subtle: For any branch mask, keys with the same prefix w.r.t. the branch mask must occur consecutively in the list.-Should this key follow the left subtree of a  with switching bit m&? N.B., the answer is only valid when  match i p m is true. Does the key i differ from the prefix p& before getting to the switching bit m? Does the key i match the prefix p (up to but not including bit m)?The prefix of key i. up to (but not including) the switching bit m.The prefix of key i. up to (but not including) the switching bit m.5Does the left switching bit specify a shorter prefix?8The first switching bit where the two prefixes disagree.O(1). Decompose a map into pieces based on the structure of the underlying tree. This function is useful for consuming a map in parallel.No guarantee is made as to the sizes of the pieces; an internal, but deterministic process determines this. However, it is guaranteed that the pieces returned will be in ascending order (all elements in the first submap less than all elements in the second, and so on). Examples: splitRoot (fromList (zip [1..6::Int] ['a'..])) == [fromList [(1,'a'),(2,'b'),(3,'c')],fromList [(4,'d'),(5,'e'),(6,'f')]] splitRoot empty == []Note that the current implementation does not return more than two submaps, but you should not depend on this behaviour because it can change in the future without notice.O(n \min(n,W)). Show the tree that implements the map. The tree is shown in a compressed, hanging format.O(n \min(n,W)). The expression ( hang wide map.) shows the tree that implements the map. If hang is M, a hanging6 tree is shown otherwise a rotated tree is shown. If wide is M!, an extra wide version is shown.ghc ghc ghc ghc ghc%Traverses in order of increasing key.!Folds in order of increasing key.ghcghc Equivalent to  ReaderT k (ReaderT x (MaybeT f)).ghc Equivalent to  ReaderT k (ReaderT x (MaybeT f)).ghc ghc ghc Equivalent to .ReaderT Key (ReaderT x (ReaderT y (MaybeT f)))ghc Equivalent to .ReaderT Key (ReaderT x (ReaderT y (MaybeT f)))ghc ghc What to do with keys in m1 but not m2What to do with keys in m2 but not m1What to do with keys in both m1 and m2Map m1Map m2What to do with keys in m1 but not m2What to do with keys in m2 but not m1What to do with keys in both m1 and m2Map m1Map m2    (  &   $  " & & *  % !  =   ? ?   2'(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableNoneCH/ O(\min(n,W)). The expression ( def k map) returns the value at key k or returns def, when the key is not an element of the map. findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x' findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'O(1). A map of one element. singleton 1 'a' == fromList [(1, 'a')] size (singleton 1 'a') == 1 O(\min(n,W)). Insert a new key/value pair in the map. If the key is already present in the map, the associated value is replaced with the supplied value, i.e.  is equivalent to  {. insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')] insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')] insert 5 'x' empty == singleton 5 'x' O(\min(n,W))%. Insert with a combining function.  f key value mp) will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert f new_value old_value. insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")] insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] insertWith (++) 5 "xxx" empty == singleton 5 "xxx" O(\min(n,W))%. Insert with a combining function.  f key value mp) will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert f key new_value old_value. let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")] insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")] insertWithKey f 5 "xxx" empty == singleton 5 "xxx"7If the key exists in the map, this function is lazy in value but strict in the result of f. O(\min(n,W)). The expression ( f k x map2) is a pair where the first element is equal to ( k map$) and the second element equal to ( f k x map). let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")]) insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")]) insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")This is how to define  insertLookup using insertLookupWithKey: let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")]) insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")]) O(\min(n,W)). Adjust a value at a specific key. When the key is not a member of the map, the original map is returned. adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] adjust ("new " ++) 7 empty == empty O(\min(n,W)). Adjust a value at a specific key. When the key is not a member of the map, the original map is returned. let f key x = (show key) ++ ":new " ++ x adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] adjustWithKey f 7 empty == empty O(\min(n,W)). The expression ( f k map) updates the value x at k (if it is in the map). If (f x) is K%, the element is deleted. If it is (L y ), the key k is bound to the new value y. let f x = if x == "a" then Just "new a" else Nothing update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")] update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" O(\min(n,W)). The expression ( f k map) updates the value x at k (if it is in the map). If (f k x) is K%, the element is deleted. If it is (L y ), the key k is bound to the new value y. let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")] updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" O(\min(n,W)). Lookup and update. The function returns original value, if it is updated. This is different behavior than >. Returns the original key value if the map entry is deleted. let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:new a")]) updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")]) updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a") O(\min(n,W)). The expression ( f k map) alters the value x at k, or absence thereof. 8 can be used to insert, delete, or update a value in an . In short :  k ( f k m) = f ( k m). O(\log n). The expression ( f k map) alters the value x at k, or absence thereof.  can be used to inspect, insert, delete, or update a value in an . In short :  k  $  f k m = f ( k m).Example: interactiveAlter :: Int -> Word64Map String -> IO (Word64Map String) interactiveAlter k m = alterF f k m where f Nothing = do putStrLn $ show k ++ " was not found in the map. Would you like to add it?" getUserResponse1 :: IO (Maybe String) f (Just old) = do putStrLn $ "The key is currently bound to " ++ show old ++ ". Would you like to change or delete it?" getUserResponse2 :: IO (Maybe String)  is the most general operation for working with an individual key that may or may not be in a given map.8The union of a list of maps, with a combining operation. unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]O(n+m)&. The union with a combining function. unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]O(n+m)&. The union with a combining function. let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]O(n+m)'. Difference with a combining function. let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")]) == singleton 3 "b:B"O(n+m). Difference with a combining function. When two equal keys are encountered, the combining function is applied to the key and both values. If it returns K, the element is discarded (proper set difference). If it returns (L y+), the element is updated with a new value y. let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")]) == singleton 3 "3:b|B"O(n+m)-. The intersection with a combining function. intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"O(n+m)-. The intersection with a combining function. let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"O(n+m):. A high-performance universal combining function. Using , all combining functions can be defined without any loss of efficiency (with exception of ,  and ,, where sharing of some nodes is lost with ).6Please make sure you know what is going on when using , otherwise you can be surprised by unexpected code growth or even corruption of the data structure.When  is given three arguments, it is inlined to the call site. You should therefore use  only to define your custom combining functions. For example, you could define ,  and  as myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2 myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2 myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2 When calling  combine only1 only2, a function combining two s is created, such thatif a key is present in both maps, it is passed with both corresponding values to the combine function. Depending on the result, the key is either present in the result with specified value, or is left out;>a nonempty subtree present only in the first map is passed to only1* and the output is added to the result;?a nonempty subtree present only in the second map is passed to only2* and the output is added to the result.The only1 and only2 methods must return a map with a subset (possibly empty) of the keys of the given map. The values can be modified arbitrarily. Most common variants of only1 and only2 are z and { , but for example  f or  f could be used for any f. O(\log n)&. Update the value at the minimal key. updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")] updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" O(\log n)&. Update the value at the maximal key. updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")] updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" O(\log n)&. Update the value at the maximal key. updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")] updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" O(\log n)&. Update the value at the minimal key. updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")] updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"O(n),. Map a function over all values in the map. map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]O(n),. Map a function over all values in the map. let f key x = (show key) ++ ":" ++ x mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]O(n).  f s ==   $  ((k, v) -> (,) k  $ f k v) ( m)* That is, behaves exactly like a regular  except that the traversing function also has access to the key associated with a value. traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')]) traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == NothingghcO(n)'. Traverse keys/values and collect the L results.O(n). The function  threads an accumulating argument through the map in ascending order of keys. let f a b = (a ++ b, b ++ "X") mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])O(n). The function  threads an accumulating argument through the map in ascending order of keys. let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X") mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])ʄO(n). The function ʄ threads an accumulating argument through the map in ascending order of keys. Strict in the accumulating argument and the both elements of the result of the function.O(n). The function  threads an accumulating argument through the map in descending order of keys. O(n \log n).  c f s! is the map obtained by applying f to each key of s.)The size of the result may be smaller if f maps two or more distinct keys to the same new key. In this case the associated values will be combined using c. mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab" mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"O(n). Map values and collect the L results. let f x = if x == "a" then Just "new a" else Nothing mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"O(n)". Map keys/values and collect the L results. let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"O(n). Map values and separate the N and O results. let f a = if a < "c" then Left a else Right a mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")]) mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])O(n)#. Map keys/values and separate the N and O results. let f k a = if k < 5 then Left (k * 2) else Right (a ++ a) mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")]) mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")]) == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])O(n). Build a map from a set of keys and a function which for each key computes its value. fromSet (\k -> replicate k 'a') (Data.Word64Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")] fromSet undefined Data.Word64Set.empty == emptyO(n \min(n,W)).. Create a map from a list of key/value pairs. fromList [] == empty fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")] fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]O(n \min(n,W)). Create a map from a list of key/value pairs with a combining function. See also . fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")] fromListWith (++) [] == emptyO(n \min(n,W)). Build a map from a list of key/value pairs with a combining function. See also fromAscListWithKey'. let f key new_value old_value = show key ++ ":" ++ new_value ++ "|" ++ old_value fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "3:a|b"), (5, "5:c|5:b|a")] fromListWithKey f [] == emptyO(n). Build a map from a list of key/value pairs where the keys are in ascending order. fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]O(n). Build a map from a list of key/value pairs where the keys are in ascending order, with a combining function on equal keys. :The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]O(n). Build a map from a list of key/value pairs where the keys are in ascending order, with a combining function on equal keys. :The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]O(n). Build a map from a list of key/value pairs where the keys are in ascending order and all distinct. The precondition (input list is strictly ascending) is not checked. fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]˄O(n). Build a map from a list of key/value pairs with monotonic keys and a combining function.The precise conditions under which this function works are subtle: For any branch mask, keys with the same prefix w.r.t. the branch mask must occur consecutively in the list.(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableNone((c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableNone(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableNone3 NonehhNone S S)None  *None+None(This type is very similar to :, but it omits the constructors that involve pretty-printing via 9 . Due to the implementation of  for : , this type can be caught as a :.Note that this should only be used for throwing exceptions, not for catching, as :3 will not be converted to this type when catching.(Some other fatal signal (SIGHUP,SIGTERM)*Prints the short usage msg after the errorA problem with the command line arguments, but don't print usage.The  impossible happened.The user tickled something that's known not to work yet, but we're not counting it as a bug.An installation problem.&An error in the user's code, probably.̄Short usage information to display when we are given the wrong cmd line arguments.;Append a description of the given exception to this string.Panics and asserts.Panics and asserts.Panics and asserts.Throw a failed assertion exception for a given filename and line number. ? ?%None+'A call stack constraint, but only when  isDebugOn.+Apply a function iff some condition is met.Apply a function n times to a given value.3Like filter, only it reverses the sense of the testUses a function to determine which of two output lists an input element should joinMonadic version of  takes a list of Bools and a list of some elements and filters out these elements for which the corresponding value in the list of Bools is False. This function does not check whether the lists have equal length. takes a list of Bools and two lists as input, and outputs a new list consisting of elements from the last two input lists. For each Bool in the list, if it is M;, then it takes an element from the former list. If it is J, it takes an element from the latter list. The elements taken correspond to the index of the Bool in its list. For example: filterByLists [True, False, True, False] "abcd" "wxyz" = "axcz" This function does not check whether the lists have equal length. takes a list of Bools and a list of some elements and partitions the list according to the list of Bools. Elements corresponding to M+ go to the left; elements corresponding to J go to the right. For example, ;partitionByList [True, False, True] [1,2,3] == ([1,3], [2]) This function does not check whether the lists have equal length; when one list runs out, the function stops.stretchZipWith p z f xs ys stretches ys by inserting z in the places where p returns TrueThis has the effect of making the two lists have equal length by dropping the tail of the longer one.atLength atLen atEnd ls n unravels list ls to position n . Precisely:  atLength atLenPred atEndPred ls n | n < 0 = atLenPred ls | length ls < n = atEndPred (n - length ls) | otherwise = atLenPred (drop n ls)  &(lengthExceeds xs n) = (length xs > n) '(lengthAtLeast xs n) = (length xs >= n) "(lengthIs xs n) = (length xs == n) %(lengthIsNot xs n) = (length xs /= n) &(lengthAtMost xs n) = (length xs <= n) ((lengthLessThan xs n) == (length xs < n)True if length xs == length ysTrue if length xs <= length ysTrue if length xs < length ys=Utility function to go from a singleton list to it's element.Wether or not the argument is a singleton list is only checked in debug builds.Extract the single element of a list and panic with the given message if there are more elements or the list was empty. Like  expectJust, but for lists. >Compute all the ways of removing a single element from a list. 4holes [1,2,3] = [(1, [2,3]), (2, [1,3]), (3, [1,2])] 8Replace the last element of a list with another element. Like expectJust msg . nonEmpty; a better alternative to . 4Merge an unsorted list of sorted lists, for example: mergeListsBy compare [ [2,5,15], [1,10,100] ] = [1,2,5,10,15,100] O(n \log{} k) =Remove duplicates but keep elements in order. O(n * log n) =Remove duplicates but keep elements in order. O(n * log n) ;Given two lists xs and ys, return `splitAt (length xs) ys`. drop from the end of a list +spanEnd p l == reverse (span p (reverse l)). The first list returns actually comes after the second list (when you look at the input list). $Get the last two elements in a list.  onJust x m f? applies f to the value inside the Just or returns the default. Split a list into its last element and the initial part of the list. %snocView xs = Just (init xs, last xs) for non-empty lists. snocView xs = Nothing otherwise. Unless both parts of the result are guaranteed to be used prefer separate calls to last + init. If you are guaranteed to use both, this will be more efficient. =Convert a word to title case by capitalising the first letter̈́Find the "restricted" Damerau-Levenshtein edit distance between two strings. See:  9http://en.wikipedia.org/wiki/Damerau-Levenshtein_distance. Based on the algorithm presented in "A Bit-Vector Algorithm for Computing Levenshtein and Damerau Edit Distances" in PSC'02 (Heikki Hyyro). See  *http://www.cs.uta.fi/~helmu/pubs/psc02.pdf and  ,http://www.cs.uta.fi/~helmu/pubs/PSCerr.html for an explanation Search for possible matches to the users input in the given list, returning a small number of ranked results *Determine the $log_2$ of exact powers of 2 Parse a string into a significand and exponent. A trivial example might be: ghci> readSignificandExponentPair "1E2" (1,2) In a more complex case we might return a exponent different than that which the user wrote. This is needed in order to use a Integer significand. ghci> readSignificandExponentPair "-1.11E5" (-111,3) Parse a string into a significand and exponent according to the "Hexadecimal Floats in Haskell" proposal. A trivial example might be: ghci> readHexSignificandExponentPair "0x1p+1" (1,1) Behaves similar to readSignificandExponentPair but the base is 16 and numbers are given in hexadecimal: ghci> readHexSignificandExponentPair "0xAp-4" (10,-4) ghci> readHexSignificandExponentPair "0x1.2p3" (18,-1) A sample hash function for Strings. We keep multiplying by the golden ratio and adding. The implementation is: hashString = foldl' f golden where f m c = fromIntegral (ord c) * magic + hashInt32 m magic = 0xdeadbeef2Where hashInt32 works just as hashInt shown above.Knuth argues that repeated multiplication by the golden ratio will minimize gaps in the hash space, and thus it's a good choice for combining together multiple keys to form one.Here we know that individual characters c are often small, and this produces frequent collisions if we use ord c alone. A particular problem are the shorter low ASCII and ISO-8859-1 character strings. We pre-multiply by a magic twiddle factor to obtain a good distribution. In fact, given the following test: testp :: Int32 -> Int testp k = (n - ) . length . group . sort . map hs . take n $ ls where ls = [] : [c : l | l <- ls, c <- ['\0'..'\xff']] hs = foldl' f golden f m c = fromIntegral (ord c) * k + hashInt32 m n = 100000!We discover that testp magic = 0.΄A sample (and useful) hash function for Int32, implemented by extracting the uppermost 32 bits of the 64-bit result of multiplying by a 33-bit constant. The constant is from Knuth, derived from the golden ratio: $golden = round ((sqrt 5 - 1) * 2^32)We get good key uniqueness on small inputs (a problem with previous versions): (length $ group $ sort $ map hashInt32 [-32767..65536]) == 65536 + 32768                   d         d  ,None  4 A  5 is a pointer to some array of Latin-1 encoded chars. Lexical FastStringThis is a simple FastString wrapper with an Ord instance using   (i.e. which compares FastStrings on their String representation). Hence it is deterministic from one run to the other. Non-deterministic FastStringThis is a simple FastString wrapper with an Ord instance using   (i.e. which compares FastStrings on their Uniques). Hence it is not deterministic from one run to the other. A   is a Modified UTF-8 encoded string together with a unique ID. All  s are stored in a global hashtable to support fast O(1) comparison.It is also associated with a lazy reference to the Z-encoding of this string which is used by the compiler internally. Lazily computed Z-encoding of this string. See Note [Z-Encoding] in GHC.Utils.Encoding.Since  s are globally memoized this is computed at most once for any given string. :Gives the Modified UTF-8 encoded bytes corresponding to a  :Gives the Modified UTF-8 encoded bytes corresponding to a  zStringTakeN n =  n .   but is performed in  O(\min(n,l)) rather than O(l) , where l is the length of the  . Compare FastString lexically2If you don't care about the lexical ordering, use   instead. 3Compare FastString by their Unique (not lexically).Much cheaper than   but non-deterministic!  Create a   by copying an existing τ  Create a   from an existing Є without copying. Creates a UTF-8 encoded   from a :  Creates a   from a UTF-8 encoded [Word8]фCreates a (lazy) Z-encoded   from a Є= and account the number of forced z-strings into the passed . Returns the length of the   in characters Returns True if the   is empty )Lazily unpacks and decodes the FastString !Returns a Z-encoded version of a  . This might be the original, if it was already Z-encoded. The first time this function is applied to a particular  , the results are memoized.  Outputs a   with no decoding at all,, that is, you get the actual bytes in the   written to the ҄. Wrap an unboxed address into a  .  Decode a   back into a : using Latin-1 encoding. This does not free the memory associated with  . unpackPtrStringTakeN n =  n .   but is performed in  O(\min(n,l)) rather than O(l) , where l is the length of the  . Return the length of a  ӄ-The unique ID counter shared with all bucketsWe unpack the + counter as it is always consumed strictly./Number of computed z-encodings for all buckets.We mark this as NOUNPACK as this  is retained by a thunk in Ԅ and needs to be boxed any way. If this is unpacked, then we box this single % once for each allocated FastString.concurrent segments2 2   Deprecated: Use   instead          #        "          -None( Replicate an 8-bit character ."(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)!David Terei stableportableNone- Rendering mode. Normal With zig-zag cuts %No indentation, infinitely long lines All on one line A rendering style. %Ratio of line length to ribbon length Length of line, in chars The rendering mode The TextDetails data typeA TextDetails represents a fragment of text that will be output at some point. A single Char fragment A whole String fragmentՄRDoc is a "reduced GDoc", guaranteed not to have a top-level Above or Beside. The abstract type of documents. A Doc represents a *set* of layouts. A Doc with no occurrences of Union or NoDoc represents just one layout. A document of height and width 1, containing a literal character. 5A document of height 1 containing a literal string.   satisfies the following laws:   s     t =   (st)  ""   x = x, if x non-empty8The side condition on the last law is necessary because   "" has height 1, while   has no height. Some text with any width. (text s = sizedText (length s) s) Some text, but without any width. Use for non-printing text such as a HTML or Latex tags *Empty text (one line high but no width). (emptyText = text "") 2The empty document, with no height and no width.   is the identity for  ,  ,   and  ), and anywhere in the argument list for  ,  ,  ,  ,   etc. Returns M if the document is empty Get the first character of a document. We also return a new document, equivalent to the original one but faster to render. Use it to avoid work duplication. Apply   to   if boolean is true.ք*Perform some simplification of a built up GDoc. List version of  . List version of  . List version of  . Nest (or indent) a document by a given number of positions (which may also be negative).   satisfies the laws:   0 x = x   k (  k' x) =   (k+k') x   k (x   y) =   k z     k y   k (x   y) =   k x     k y   k   =  x     k y = x   y, if x non-empty6The side condition on the last law is needed because   is a left identity for  . "hang d1 n d2 = sep [d1, nest n d2] Apply   to the arguments if the first   is not empty. punctuate p [d1, ... dn] = [d1 <> p, d2 <> p, ... dn-1 <> p, dn] Above, except that if the last line of the first argument stops at least one position before the first line of the second begins, these two lines are overlapped. For example: % text "hi" $$ nest 5 (text "there") lays out as  hi there rather than  hi there  is associative, with identity  , and also satisfies(x   y)   z = x   (y   z), if y non-empty. Above, with no overlapping.   is associative, with identity  .  Beside.   is associative, with identity  . ;Beside, separated by space, unless one of the arguments is  .   is associative, with identity  . Either   or  . Either   or  . "Paragraph fill" version of  . "Paragraph fill" version of  .ׄfirst returns its first argument if it is non-empty, otherwise its second. The default style (7mode=PageMode False, lineLength=100, ribbonsPerLine=1.5).؄Can we output an ascii space character for spaces? Mostly true, but not for e.g. UTF16 See Note [putSpaces optimizations] for why we bother to track this.  Render the Doc to a String using the given Style. Default TextDetails printer  The general rendering interface. A ';' character A ',' character A : character A space character A '=' character A '(' character A ')' character A '[' character A ']' character A '{' character A '}' character  int n = text (show n)  integer n = text (show n)  float n = text (show n)  double n = text (show n)  rational n = text (show n) %See Note [Print Hexadecimal Literals] Wrap document in `...' Wrap document in '...' Wrap document in "..." Wrap document in (...) Wrap document in [...] Wrap document in {...} Rendering mode Line lengthRibbons per lineWhat to do with textWhat to do at the end The documentResult       /None  A colour/style for use with coloured. ;Parse the colour scheme from a string (presumably from the  GHC_COLORS environment variable). Allow colours to be combined (e.g. bold + red); In case of conflict, right side takes precedence.      "0NoneW Captures the fixity of declarations as they are parsed. This is not necessarily the same as the fixity declaration, as the normal fixity may be overridden using parens or backticks. Source Unpackedness$What unpackedness the user requested {-# UNPACK #-} specified {-# NOUNPACK #-} specified no unpack pragma Source Strictness)What strictness annotation the user wrote  Lazy, ie ~  Strict, ie ! no strictness annotation  Haskell Bang8Bangs on data constructor arguments written by the user.(HsBang SrcUnpack SrcLazy) and (HsBang SrcUnpack NoSrcStrict) (without StrictData) makes no sense, we emit a warning (in checkValidDataCon) and treat it like (HsBang NoSrcUnpack SrcLazy)2 is a wrapper around this, associating it with a j* as written by the user. In the AST, the  SourceText' is hidden inside the extension point 1. %See Note [Roles] in GHC.Core.CoercionOrder of constructors matters: the Ord instance coincides with the *super*typing relation on roles. Field labels are just represented as strings; they are not necessarily unique (even within a module) A *one-index* constructor tagType of the tags associated with each constructor possibility or superclass selector The width of an unboxed sum       /1 37           ; ; ;; ;;   1None  !+3 See Note [NoGhcTc] in GHC.Hs.Extension. It has to be in this module because it is used like an extension point (in the data definitions of types that should be parameter-agnostic. *Maps the "normal" id type for a given pass The trivial wrapper that carries no additional information See Note [XRec and SrcSpans in the AST] 4We can map over the underlying type contained in an XRec( while preserving the annotation as is. We can strip off the XRec to access the underlying data. See Note [XRec and SrcSpans in the AST] GHC's L prefixed variants wrap their vanilla variant in this type family, to add SrcLoc info via Located. Other passes than GhcPass= not interested in location information can define this as "type instance XRec NoLocated a = a*. See Note [XRec and SrcSpans in the AST] A placeholder type for TTG extension points that are not currently used to represent any particular value.!This should not be confused with  ', which are found in unused extension  constructors8 and therefore should never be inhabited. In contrast,   is used in extension points (e.g., as the field of some constructor), so it must have an inhabitant to construct AST passes that manipulate fields with that extension point as their type. =Used when constructing a term with an unused extension point.  Eliminate a  &. See Note [Constructor cannot occur].      2None@2A ModuleName is essentially a simple string, e.g.  Data.List.6Compares module names lexically, rather than by their UniquesReturns the string version of the module name, with dots replaced by slashes.Returns the string version of the module name, with dots replaced by colons.     6 : < >9None !%A class of types that represent a multiline document, with support for vertical composition.See Note [HLine versus HDoc] and Note [The outputable class hierarchy] for more details. Join two docs together vertically. If there is no vertical overlap it "dovetails" the two onto one line. Concatenate docs vertically with dovetailing.Prints as either the given  or the given , depending on which type the result is instantiated to. This should generally be avoided; see Note [dualLine and dualDoc] for details.A class of types that represent a single logical line of text, with support for horizontal composition.See Note [HLine versus HDoc] and Note [The outputable class hierarchy] for more details. Join two doc&s together horizontally without a gap. Join two doc0s together horizontally with a gap between them.Separate: is either like  or like , depending on what fits.,A paragraph-fill combinator. It's much like , only it keeps fitting things on one line until it can't fit any more. Concatenate docs horizontally without gaps. Concatenate doc-s horizontally with a space between each one.Prints as either the given  or the given , depending on which type the result is instantiated to. This should generally be avoided; see Note [dualLine and dualDoc] for details.A superclass for  and  that provides an identity, #, as well as access to the shared .;See Note [The outputable class hierarchy] for more details.Represents a (possibly empty) sequence of lines that can be efficiently printed directly to a  (actually a  ). See Note [SDoc versus HDoc] and Note [HLine versus HDoc] for more details.Represents a single line of output that can be efficiently printed directly to a  (actually a  ). See Note [SDoc versus HDoc] and Note [HLine versus HDoc] for more details. is used to tell the thing that prints binder what language construct is binding the identifier. This can be used to decide how much info to print. Also see Note [Binding-site specific printing] in  GHC.Core.PprThe x in (x. e)+The x in case scrut of x { (y,z) -> ... }+The y,z in case scrut of x { (y,z) -> ... }The x in (let x = rhs in e)When we print a binder, we often want to print its type too. The OutputableBndr class encapsulates this idea.Wrapper for types having a Outputable instance when an OutputableP instance is required.5Outputable class with an additional environment value See Note [The OutputableP class](Class designating that some type has an  representationUsed to map UnitIds to more friendly "package-version:component" strings while pretty-printing.Use  to set it. Users should never have to set it to pretty-print SDocs emitted by GHC, otherwise it's a bug. It's an internal field used to thread the UnitState so that the Outputable instance of UnitId can use it.%See Note [Pretty-printing UnitId] in GHC.Unit for more details.Note that we use   instead of UnitId1 to avoid boring module inter-dependency issues.True if Unicode encoding is supported and not disabled by GHC_NO_UNICODE environment variable stopUse  field as depth!Print code; either C or assembler$NB: This won't ever show package IDsDefault style for error messages, when we don't know NamePprCtx It's a bit of a hack because it doesn't take into account what's in scope Only used for desugarer warnings, and typechecker errors in interface sigs!Style for printing error messagesDefault pretty-printing options6Truncate a list that is longer than the current depth.'Indicate if -dppr-debug mode is enabled,Says what to do with and without -dppr-debug7Says what to do with -dppr-debug; without, return emptyThe analog of  for , which tries to make sure the terminal doesn't get screwed up by the ANSI color codes if an exception is thrown during pretty-printing.Like  but appends an extra newline.An efficient variant of  specialized for   that outputs to a  .doublePrec p n shows a floating point number n with p. digits of precision after the decimal point.Indent  some specified amount Join two  together verticallyA paragraph-fill combinator. It's much like sep, only it keeps fitting things on one line until it can't fit any more.This behaves like , but it uses ( for horizontal composition rather than This behaves like , but does not indent the second document when the header is empty.,Punctuate a list, e.g. with commas and dots. sep $ punctuateFinal comma dot [text "ab", text "cd", text "ef"] ab, cd, ef..Apply the given colour/style for the argument.)Only takes effect if colours are enabled.2Special combinator for showing character literals./Special combinator for showing string literals.3Special combinator for showing bytestring literals.0Special combinator for showing unboxed literals.9Normalise, escape and render a string representing a pathe.g. "c:\whatever"Returns the separated concatenation of the pretty printed things.Returns the comma-separated concatenation of the pretty printed things.Returns the comma-separated concatenation of the quoted pretty printed things. ,y,z] ==> `x', `y', `z'&Converts an integer to a verbal index: speakNth 1 = text "first" speakNth 5 = text "fifth" speakNth 21 = text "21st"-Converts an integer to a verbal multiplicity: speakN 0 = text "none" speakN 5 = text "five" speakN 10 = text "10"Converts an integer and object description to a statement about the multiplicity of those objects: speakNOf 0 (text "melon") = text "no melons" speakNOf 1 (text "melon") = text "one melon" speakNOf 3 (text "melon") = text "three melons"Determines the pluralisation suffix appropriate for the length of a list: plural [] = char 's' plural ["Hello"] = empty plural ["Hello", "World"] = char 's'Determines the singular verb suffix appropriate for the length of a list: singular [] = empty singular["Hello"] = char 's' singular ["Hello", "World"] = emptyDetermines the form of to be appropriate for the length of a list: isOrAre [] = text "are" isOrAre ["Hello"] = text "is" isOrAre ["Hello", "World"] = text "are"Determines the form of to do appropriate for the length of a list: doOrDoes [] = text "do" doOrDoes ["Hello"] = text "does" doOrDoes ["Hello", "World"] = text "do"Determines the form of possessive appropriate for the length of a list: itsOrTheir [x] = text "its" itsOrTheir [x,y] = text "their" itsOrTheir [] = text "their" -- probably avoid thisit or they', depeneding on the length of the list. itOrThey [x] = text "it" itOrThey [x,y] = text "they" itOrThey [] = text "they" -- probably avoid thisDetermines the form of subject appropriate for the length of a list: thisOrThese [x] = text "This" thisOrThese [x,y] = text "These" thisOrThese [] = text "These" -- probably avoid this"has" or "have"# depending on the length of a list. The headerAmount to indent the hung body3The hung body, indented and placed below the headerThe punctuationThe list that will have punctuation added between every adjacent pair of elementsPunctuated listThe interstitial punctuationThe final punctuationThe list that will have punctuation added between every adjacent pair of elementsPunctuated list#The pretty printing function to useThe things to be pretty printed where the things have been pretty printed, comma-separated and finally packed into a paragraph.#The pretty printing function to useThe things to be pretty printed where the things have been pretty printed, semicolon-separated and finally packed into a paragraph.#The pretty printing function to useThe things to be pretty printed where the things have been pretty printed, bar-separated and finally packed into a paragraph.  8  " ( . 3 *                 6     8 2 2       " 8      * ' $ !   . ; >            ,   76:None=GHC's own exception type error messages all take the form:  : If the location is on the command line, or in GHC itself, then ="ghc". All of the error types below correspond to a of "ghc", except for ProgramError (where the string is assumed to contain a location already, so we don't print one).(Some other fatal signal (SIGHUP,SIGTERM)*Prints the short usage msg after the errorA problem with the command line arguments, but don't print usage.The  impossible happened.The user tickled something that's known not to work yet, but we're not counting it as a bug.An installation problem.&An error in the user's code, probably.Show an exception as a string.Show an exception which can possibly throw other exceptions. Used when displaying exception thrown within TH code.;Append a description of the given exception to this string.Note that this uses >, which doesn't use the options set by the user via DynFlags.;Append a description of the given exception to this string.7Throw an exception saying "bug in GHC" with a callstack&Throw an exception saying "bug in GHC"3Throw an exception saying "this isn't finished yet"Throw an exception saying "bug in pgm being compiled" (used for unusual program errors)Like try, but pass through UserInterrupt and Panic exceptions. Used when we want soft failures when reading interface files, for example. TODO: I'm not entirely sure if this is catching what we really want to catchل-We use reference counting for signal handlersTemporarily install standard signal handlers for catching ^C, which just throw an exception in the current thread.Panic with an assertion failure, recording the given file and line number. Should typically be accessed with the ASSERT family of macros8&  None!If debug output is on, show some  on the screenpprTraceWith desc f x is equivalent to pprTrace desc (f x) x. This allows you to print details from the returned value as well as from ambient variables.pprTraceIt desc x is equivalent to pprTrace desc (ppr x) xpprTraceException desc x action< runs action, printing a message if it throws an exception.!If debug output is on, show some 7 on the screen along with a call stack when available.Just warn about an assertion failure, recording the given file and line number.For when we want to show the user a non-fatal WARNING so that they can report a GHC bug, but don't want to panic.  None~|y{}zb`acijk]_^4"w v!*x)873FNO56#$ &/+ml n o-' (rusptqB.01%\,WXYVZ[DAQRP?:@LK9JM;<=>EC =NoneNoneA4Set the mtime of the given file to the current time.NNone_+A state monad which is strict in the state s, but lazy in the value a.See Note [Strict State monad] for the particular notion of strictness and implementation details.ڄForces the state component of the unboxed representation pair of . See Note [Strict State monad]. This is The Place doing the forcing!     None. .-+ +,( (" " # NoneK for ۄ lists.mapAndUnzipM for triplesMonadic version of mapAccumLMonadic version of mapSndMonadic version of concatMapApplicative version of mapMaybeMonadic version of &, aborts the computation at the first True valueMonad version of &, aborts the computation at the first False valueMonadic version of or܄Monadic version of and1Monadic version of foldl that discards its resultMonadic version of Monadic version of when#, taking the condition in the monadMonadic version of unless#, taking the condition in the monadLike ݄), only it reverses the sense of the test.Monadic version of  partitioncombining function initial stateinputsfinal state, outputs#4"w v!2#4"w v!2None $Is this an acceptable variable name?'Is this an acceptable constructor name? Is this an acceptable type name?Is this an acceptable alphanumeric variable name, assuming it starts with an acceptable letter?Is this an acceptable symbolic variable name, assuming it starts with an acceptable character?Is this an acceptable alphanumeric constructor name, assuming it starts with an acceptable letter?Is this an acceptable symbolic constructor name, assuming it starts with an acceptable character?ބIs this string an acceptable id, possibly with a suffix of hashes, but not worrying about case or clashing with reserved words?߄Is this character acceptable in an identifier (after the first letter)? See alexGetByte in GHC.Parser.LexerAll reserved identifiers. Taken from section 2.4 of the 2010 Report, plus the GHC-specific forall! keyword (see GHC Proposal #281).All reserved operators. Taken from section 2.4 of the 2010 Report, excluding @ and ~1 that are allowed by GHC (see GHC Proposal #229).Does this string contain only dashes and has at least 2 of them?VNoneWhen invoking external tools as part of the compilation pipeline, we pass these a sequence of options on the command-line. Rather than just using a list of Strings, we use a type that allows us to distinguish between filepaths and 'other stuff'. The reason for this is that this type gives us a handle on transforming filenames, and filenames only, to whatever format they're expected to be on a particular platform. WNone-What kind of {-# SCC #-} to add automaticallyno SCC annotations added,top-level and nested functions are annotated"top-level functions annotated only!exported functions annotated onlyannotate call-sites \NoneBThis is used to signal if one of my imports used HPC instrumentation even if there is no module-local HPC usage;Information about a modules use of Haskell Program Coverage*Is hpc used anywhere on the module *tree*?Find out if HPC is used by this module or any of the modules it depends upon  UNoneType alias for ; the convention is we'll use this for mutable bits of data in the typechecker which are updated during typechecking and returned at the end.XNoneDoes the controlling terminal support ANSI color sequences? This memoized to avoid thread-safety issues in ncurses (see #17922).Check if ANSI escape sequences can be used to control color in stderr.None#&  File bytes. File size.› File mode.Û File group.ě File owner.śFile modification time.ƛ File name. >>>>>>>#>%>->/>:><> #%-/:<None  Stream m a b is a computation in some Monad m/ that delivers a sequence of elements of type a followed by a result of type b.!More concretely, a value of type  Stream m a b can be run using runStreamInternal in the Monad m, and it delivers eitherthe final result: Done b, or Yield a str where a( is the next element in the stream, and str is the rest of the stream Effect mstr where mstr is some action running in m* which generates the rest of the stream.4Stream is itself a Monad, and provides an operation  that produces a new element of the stream. This makes it convenient to turn existing monadic computations into streams.The idea is that Stream is useful for making a monadic computation that produces values from time to time. This can be used for knitting together two complex monadic operations, so that the producer does not have to produce all its values before the consumer starts consuming them. We make the producer into a Stream, and the consumer pulls on the stream each time it wants a new value. is implemented in the "yoneda" style for efficiency. By representing a stream in this manner  and  operations are accumulated in the function parameters before being applied once when the stream is destroyed. In the old implementation each usage of  and  would traverse the entire stream in order to apply the substitution at the leaves.The >>= operation for . was a hot-spot in the ticky profile for the ManyConstructors test which called the cg function many times in  StgToCmm.hsTurn a Stream into an ordinary list, by demanding all the elements.Turn a list into a #, by yielding each element in turn.&Apply a function to each element of a , lazily/Apply a monadic operation to each element of a , lazilyNote this is not very efficient because it traverses the whole stream before rebuilding it, avoid using it if you can. mapAccumL used to implemented but it wasn't used anywhere in the compiler and has similar efficiency problems.Lift an effect into the StreamHoist the underlying Stream effect Note this is not very efficience since, just like :, it also needs to traverse and rebuild the whole stream. ( . +  "  RNone/+Copy and freeze a slice of a mutable array.!Freeze a mutable array (no copy!)Get the size of a )Index a small-array (no bounds checking!)&Map a function over the elements of a Fold the values of a  into a 'Monoid m' of choice Force the elements of the given Convert a list into an array.sizeinitial contentsarrayindex new elementsourceoffsetlengtharrayindexNoneTakes a list of Maybes and returns the first Just if there is one, or Nothing otherwise.Takes computations returnings Maybes6; tries each one in order. The first one to return a Just wins. Returns Nothing if all computations return Nothing.Flipped version of  fromMaybe, useful for chaining.Try performing an D action, failing on error.@LK  $SNone-Store elements in a flattened representation.A  is a data structure that stores an ordered list of elements in a flat structure, avoiding the overhead of a linked list. Use this data structure, if the code requires the following properties:Elements are stored in a long-lived object, and benefit from a flattened representation.The 0 will be traversed but not extended or filtered.'The number of elements should be known.4Sharing of the empty case improves memory behaviour.A FlagBag aims to have as little overhead as possible to store its elements. To achieve that, it distinguishes between the empty case, singleton, tuple and general case. Thus, we only pay for the additional three words of an Array% if we have at least three elements.Create an empty . The empty  is shared over all instances.Create a singleton .Calculate the size of(Get all elements that are stored in the . Combine two s.The new ! contains all elements from both s.If one of the s is empty, the old  is reused.Store the list in a flattened memory representation, avoiding the memory overhead of a linked list. The size n needs to be smaller or equal to the length of the list. If it is smaller than the length of the list, overflowing elements are discarded. It is undefined behaviour to set n+ to be bigger than the length of the list. Convert a  into its flattened representation. A 'FlatBag a' is more memory efficient than '[a]', if no further modification is necessary.   (; ;3 3- -MNoneNone   NoneThe (inclusive) lower bound on the LLVM Version that is currently supported.The (not-inclusive) upper bound bound on the LLVM Version that is currently supported.None  None&maybeFlipCond c returns Just c'= if it is possible to flip the arguments to the conditional c", and the new condition should be c'. If we apply maybeInvertCond to the condition of a jump we turn jumps taken into jumps not taken and vice versa.Careful! If the used comparison and the conditional jump don't match the above behaviour will NOT hold. When used for FP comparisons this does not consider unordered numbers. Also inverting twice might return a synonym for the original condition.NoneCondition codes.Used in conditional branches and bit setters. According to the available instruction set, some conditions are encoded as their negated opposites. I.e. these are logical things that don't necessarily map 1:1 to hardware/ISA. int and float int and floatsigned less thansigned less than or equalsigned greater than or equalsigned greater thanunsigned less thanunsigned less than or equalunsigned greater than or equalunsigned greater thanfloating point instruction fltfloating point instruction flefloating point instruction fgefloating point instruction fgt* ***(c) Matt Morrow 2009BSD3stableportableNone  Dominators. Complexity as for idomPost-dominators. Complexity as for idom.Dominator tree. Complexity as for idom.Post-dominator tree. Complexity as for idom.Immediate dominators. O(|E|*alpha(|E|,|V|)), where  alpha(m,n)4 is "a functional inverse of Ackermann's function".This Complexity bound assumes O(1) indexing. Since we're using IntMap, it has an additional lg |V|0 factor somewhere in there. I'm not sure where.Immediate post-dominators. Complexity as for idom.!Post-dominated depth-first search.)Reverse post-dominated depth-first search. arr .= x idx => write x to indexrenum n g: Rename all nodesGives nodes sequential names starting at n. Returns the new graph and a mapping. (renamed, old -> new)ƜǜȜœŜÜĜœÜĜȜǜŜƜɜ ʜ ˜ None̜͜ΜϜڜٜۜ؜ҜӜќМ֜ל՜Ԝޜߜݜܜ̜͜ΜϜڜٜۜ؜ҜӜќМ֜ל՜ԜޜߜݜܜNone +3 2A sequence of nodes. May be any of four shapes (OO, OC, CO, CC). Open at the entry means single entry, mutatis mutandis for exit. A closedclosed block is a basic/ block and can't be extended further. Clients should avoid manipulating blocks and should stick to either nodes or graphs.!Maybe type indexed by open/closed6Either type indexed by closed/open using type familiesUsed at the type level to indicate "open" vs "closed" structure.An "open" structure with a unique, unnamed control-flow edge flowing in or out. "Fallthrough" and concatenation are permitted at an open point.A "closed" structure which supports control transfer only through the use of named labels---no "fallthrough" is permitted. The number of control-flow edges is unconstrained.Split a closed block into its entry node, open middle block, and exit node.#map a function over the nodes of a  A strict map over a block, with different functions to apply to first nodes, middle nodes and last nodes respectively. The map is strict.Fold a function over every node in a block, forward or backward. The fold function must be polymorphic in the shape of the nodes.**&NoneExpand occurrences of the $tooldir interpolation in a string on Windows, leave the string untouched otherwise..Returns a Unix-format path pointing to TopDir.*whether we use the ambient mingw toolchaintooldir,Maybe TopDir path (without the '-B' prefix).TopDir (in Unix format  separated)*whether we use the ambient mingw toolchaintopdirNonejThe predicates below look costly, but aren't, GHC+GCC do a great job at the big case below.None Decode an  to , throwing an i if decoding failed. Prefer  and gracious error handling.  None,OrdGr comes equipped with an Ord instance, so that graphs can be used as e.g. Map keys. Merge the  into the .Context adjacencies should only refer to either a Node already in a graph or the node in the Context itself (for loops).(Behaviour is undefined if the specified  already exists in the graph.Minimum implementation: , , , ,  An empty .True if the given  is empty. Decompose a  into the - found for the given node and the remaining . Create a  from the list of s and s.&For graphs that are also instances of , mkGraph ns es should be equivalent to (֝ es . ՝ ns) .A list of all  s in the .Decompose a graph into the  for an arbitrarily-chosen  and the remaining .The number of s in a .The minimum and maximum  in a .A list of all  s in the .Unlabeled decomposition.Unlabeled context. The same as , only more sure of itself., decomposition - the context removed from a , and the rest of the . Links to the , the ! itself, a label, links from the .In other words, this captures all information regarding the specified  within a graph.Labeled links to or from a .Quasi-unlabeled path Labeled pathUnlabeled pathQuasi-unlabeled edge Labeled edgeUnlabeled edgeQuasi-unlabeled node Labeled nodeUnlabeled node0The number of nodes in the graph. An alias for .!The number of edges in the graph.Note that this counts every edge found, so if you are representing an unordered graph by having each edge mirrored this will be incorrect.If you created an unordered graph by either mirroring every edge (including loops!) or using the undir function in Data.Graph.Inductive.Basic9 then you can safely halve the value returned by this.Ý6Fold a function over the graph by recursively calling .ĝ5Map a function over the graph by recursively calling .ŝMap a function over the  labels in a graph.ƝMap a function over the  labels in a graph.ǝMap functions over both the  and  labels in a graph.ȝ List all  s in the .ɝ List all  s in the .ʝ$Drop the label component of an edge.˝Add a label to an edge.̝The label in an edge.͝List N available s, i.e. s that are not used in the .ΝM if the  is present in the .ϝ Insert a  into the .Н Insert a  into the .ѝ Remove a  from the .ҝ Remove an  from the .6NOTE: in the case of multiple edges, this will delete all such edges from the graph as there is no way to distinguish between them. If you need to delete only a single such edge, please use ӝ.ӝ Remove an  from the .NOTE: in the case of multiple edges with the same label, this will only delete the first5 such edge. To delete all such edges, please use  delAllLedge.ԝ,Remove all edges equal to the one specified.՝Insert multiple  s into the .֝Insert multiple  s into the .םRemove multiple  s from the .؝Remove multiple  s from the .ٝBuild a  from a list of s.2The list should be in the order such that earlier 1s depend upon later ones (i.e. as produced by Ý (:) []).ڝBuild a quasi-unlabeled .۝Build a graph out of the contexts for which the predicate is satisfied by recursively calling .ܝReturns the subgraph only containing the labelled nodes which satisfy the given predicate.ݝReturns the subgraph only containing the nodes which satisfy the given predicate.ޝReturns the subgraph only containing the nodes whose labels satisfy the given predicate.ߝ3Returns the subgraph induced by the supplied nodes.Find the context for the given . Causes an error if the  is not present in the .Find the label for a .Find the neighbors for a .4Find the labelled links coming into or going from a . Find all "s that have a link from the given . Find all s that link to to the given . Find all !s that are linked from the given  and the label of each link. Find all s that link to the given  and the label of each link.Find all outward-bound s for the given .Find all inward-bound s for the given . The outward-bound degree of the .The inward-bound degree of the .The degree of the .The  in a .The label in a .The  from a .All s linked to or from in a ./All labelled links coming into or going from a .All s linked to in a .All s linked from in a .All s linked from in a , and the label of the links.All s linked from in a , and the label of the links.All outward-directed s in a .All inward-directed s in a .The outward degree of a .The inward degree of a .The degree of a .5Checks if there is a directed edge between two nodes.8Checks if there is an undirected edge between two nodes.5Checks if there is a labelled edge between two nodes.Checks if there is an undirected labelled edge between two nodes.Pretty-print the graph. Note that this loses a lot of information, such as edge inverses, etc.!Pretty-print the graph to stdout.ٝԝҝ؝ӝѝם̝ɝƝΝ۝ĝН֝ϝ՝ޝܝڝǝ͝ݝŝȝߝʝ˝ÝÝĝŝƝǝȝɝʝ̝˝͝ΝϝНѝҝӝԝ՝֝ם؝ٝڝ۝ݝܝޝߝ  "  $ % 8 7  None      + +; ;& 0 0None[NoneX2Edge weights to use when generating a CFG from CMMDefault edge weights  ]None+Y-Simple data type to represent JSON documents.The : is unescaped  ? ?< <xNone"9Subset of UnitInfo: just enough to pretty-print a unit-idInstead of printing the unit-id which may contain a hash, we print: package-version:componentname"Component name"Source package version"Source package name" Identifier"""""""""""""  ^None &'!4Spacing between output items when exact printing. It captures the spacing from the current print position on the page to the position required for the thing about to be printed. This is either on the same line in which case is is simply the number of spaces to emit, or it is some number of lines down, with a given column offset. The exact printing algorithm keeps track of the column offset pertaining to the current anchor position, so the 5 is the additional spaces to add in this case. See  8https://gitlab.haskell.org/ghc/ghc/wikis/api-annotations for details.deltaLine should always be > 0The anchor for an exact print annotation. The Parser inserts the  variant, giving the exact location of the original item in the parsed source. This can be replaced by the  version, to provide a position for the item relative to the end of the previous item in the source. This is useful when editing an AST prior to exact printing the changed one. The EpaDelta also contains the original  for use by tools wanting to manipulate the AST after converting it using ghc-exactprint'  makeDeltaAst.A location as produced by the parser. Consists of two components:The location in the file, adjusted for #line and {-# LINE ... #-} pragmas (RealSrcLoc)The location in the string buffer (BufPos) with monotonicity guarantees (see #17632)We attach SrcSpans to lots of things, so let's have a datatype for it. Source SpanA  identifies either a specific portion of a text file or a human-readable description of a location.StringBuffer Source SpanA  delimits a portion of a text file. It could be represented by a pair of (line,column) coordinates, but in fact we optimise slightly by using more compact representations for single-line and zero-length spans, both of which are quite common.-The end position is defined to be the column after the end of the span. That is, a span of (1,1)-(1,2) is one character long, and a span of (1,1)-(1,1) is zero characters long.Real Source SpanSource Location30-based offset identifying the raw location in the  StringBuffer.The lexer increments the  every time a character (UTF-8 code point) is read from the input buffer. As UTF-8 is a variable-length encoding and  StringBuffer% needs a byte offset for indexing, a  cannot be used for indexing.The parser guarantees that  are monotonic. See #17632. This means that syntactic constructs that appear later in the  StringBuffer" are guaranteed to have a higher . Contrast that with , which does *not* make the analogous guarantee about higher line/column numbers.This is due to #line and {-# LINE ... #-} pragmas that can arbitrarily modify  . Notice how  setSrcLoc and resetAlrLastLoc in GHC.Parser.Lexer update  , modifying  but preserving .Monotonicity makes  useful to determine the order in which syntactic elements appear in the source. Consider this example (haddockA041 in the test suite):haddockA041.hs {-# LANGUAGE CPP #-} -- | Module header documentation module Comments_and_CPP_include where #include "IncludeMe.hs"IncludeMe.hs: -- | Comment on T data T = MkT -- ^ Comment on MkT#After the C preprocessor runs, the  StringBuffer will contain a program that looks like this (unimportant lines at the beginning removed):# 1 "haddockA041.hs" {-# LANGUAGE CPP #-} -- | Module header documentation module Comments_and_CPP_include where # 1 "IncludeMe.hs" 1 -- | Comment on T data T = MkT -- ^ Comment on MkT # 7 "haddockA041.hs" 2The line pragmas inserted by CPP make the error messages more informative. The downside is that we can't use RealSrcLoc to determine the ordering of syntactic elements.With RealSrcLoc, we have the following location information recorded in the AST: * The module name is located at haddockA041.hs:3:8-31 * The Haddock comment "Comment on T" is located at IncludeMe:1:1-17 * The data declaration is located at IncludeMe.hs:2:1-32Is the Haddock comment located between the module name and the data declaration? This is impossible to tell because the locations are not comparable; they even refer to different files.On the other hand, with , we have the following location information: * The module name is located at 846-870 * The Haddock comment "Comment on T" is located at 898-915 * The data declaration is located at 916-928Aside: if you're wondering why the numbers are so high, try running ghc -E haddockA041.hs and see the extra fluff that CPP inserts at the start of the file.For error messages,  is not useful at all. On the other hand, this is exactly what we need to determine the order of syntactic elements: 870 < 898, therefore the Haddock comment appears *after* the module name. 915 < 916, therefore the Haddock comment appears *before* the data declaration.We use  in in GHC.Parser.PostProcess.Haddock to associate Haddock comments with parts of the AST using location information (#17544).Real Source Location'Represents a single point within a file 0.*The span that may be enclosed by the otherThe span it may be enclosed by*The span that may be enclosed by the otherThe span it may be enclosed by>           (      9 2   7#$&'+#      ")+35         yNone""""""""""""""""" wNone"$The operator occurrence type in the PsOperatorWhitespaceMessage diagnostic."The operator symbol in the &PsOperatorWhitespaceExtConflictMessage diagnostic. """"""""" """""""""gNone  , ,-( (9% %5! !  +cNone)1 An unboxed @% type with two unboxed fields in the L case. Useful for defining  and  without overhead.Strict left fold.?Compare not only the values but also the structure of two lists?Compare not only the values but also the structure of two lists 9 94 41 1. .0, ,None&'/o%The jobserver is idle: no thread is currently interacting with the semaphore.1A thread is waiting for a token on the semaphore.&The state of the semaphore job server.A TVar that signals whether we last acquired a token long enough ago that we can now release a token.A TVar that signals whether it has been long enough since we last changed .6The current action being performed by the job server.Resources available for running jobs, i.e. tokens obtained from the parallelism semaphore.Pending jobs waiting on a token, the job will be blocked on the TMVar so putting into the TMVar will allow the job to continue.,How many tokens are not currently being used4How many tokens have been claimed from the semaphoreMinimum delay, in milliseconds, between two consecutive calls of .Minimum delay, in milliseconds, between acquiring a token and releasing a token.A jobserver based off a system .Keeps track of the pending jobs and resources available from the semaphore.The currently pending jobs, and the resources obtained from the semaphore0The semaphore which controls available resourcesAdd one new token.Free one token.Use up one token.Return one owned token.7Add one new job to the end of the list of pending jobs. Retrieve the  that signals if the current thread has finished, if any thread is currently active in the jobserver.Whether we should try to acquire a new token from the semaphore: there is a pending job and no free tokens.Whether we should release a token from the semaphore: there are no pending jobs and we can release a token.%Add one pending job to the jobserver.8Blocks, waiting on the jobserver to supply a free token.Signal to the job server that one job has completed, releasing its corresponding token.Release all tokens owned from the semaphore (to clean up the jobserver at the end).Dispatch the available tokens acquired from the semaphore to the pending jobs in the job server.Update the available resources used from a semaphore, dispatching any newly acquired resources.Invariant: if the number of available resources decreases, there must be no pending jobs.All modifications should go through this function to ensure the contents of the  remains in normal form.Spawn a new thread that waits on the semaphore in order to acquire an additional token.Spawn a thread to release ownership of one resource from the semaphore, provided we have spare resources and no pending jobs.When there are pending jobs but no free tokens, spawn a thread to acquire a new token from the semaphore.See .When there are free tokens and no pending jobs, spawn a thread to release a token from the semaphore.See .6Wait for an active thread to finish. Once it finishes:set the  to ,update the number of capabilities to reflect the number of owned tokens from the semaphore.Try to stop the current thread which is acquiring/releasing resources if that operation is no longer relevant.Main jobserver loop: acquire/release resources as needed for the pending jobs and available semaphore tokens.8Create a new jobserver using the given semaphore handle.2Implement an abstract semaphore using a semaphore  which queries the system semaphore of the given name for resources.the system semaphore to use0the operation to run which requires a semaphore   !eNone09A finite mapping based on equality and association lists.Combines the two lists while keeping their order, placing the first argument first in the result.Uses a set internally to record duplicates. This makes it slightly slower for very small lists but avoids quadratic behaviour for large lists.0Assumes that the arguments contain no duplicates4Calculate the set difference of two lists. This is O((m + n) log n), where we subtract a list of n elements from a list of m elements.3Extremely short cases are handled specially: When m or n is 0, this takes O(1) time. When m is 1, it takes O(n) time.7Lookup key, fail gracefully using Nothing if not found.Remove the duplicates from a list using the provided comparison function. Might change the order of elements.Returns the list without duplicates, and accumulates all the duplicates in the second component of its result.Remove the duplicates from a list using the provided comparison function.fNone combining function initial stateinputsfinal state, outputscombining function initial stateinputsfinal state, outputs((       .7 7$5 5555 5+>NoneM%Class of things that we can obtain a  fromUnique identifier.The type of unique identifiers that are used in many places in GHC for fast ordering and equality tests. You should generate these with the functions from the  UniqSupply moduleThese are sometimes also referred to as "keys" in comments in GHC.>Bitmask that has zeros for the tag bits and ones for the rest.Put the character in the highest bits of the Word64. This may truncate the character to 8. This function is used in mkSplitUniqSupply so that it can precompute and share the tag part of the uniques it generates.The interface file symbol-table encoding assumes that known-key uniques fit in 30-bits; verify this.3See Note [Symbol table representation of names] in GHC.Iface.Binary for details.        NoneONone)A monad for generating unique identifiersGet a new UniqueSupplyGet a new unique identifier.Get an infinite list of new unique identifiers/A monad which just gives the ability to obtain s Unique SupplyA value of type  is unique, and it can supply one distinct . Also, from the supply, one can also manufacture an arbitrary number of further  UniqueSupply values, which will be distinct from the first and from all others.Create a unique supply out of thin air. The "tag" (Char) supplied is mostly cosmetic, making it easier to figure out where a Unique was born. See Note [Uniques and tags].The payload part of the Uniques allocated from this UniqSupply are guaranteed distinct wrt all other supplies, regardless of their "tag". This is achieved by allocating the payload part from a single source of Uniques, namely ", shared across all UniqSupply's. Build two 6 from a single one, each of which can supply its own .Create an infinite list of  from a single one Obtain the  from this particular Obtain an infinite list of : that can be generated by constant splitting of the supply Obtain the  from this particular , and a new supplySmart constructor for 9, as described in Note [The one-shot state monad trick].Run the  action, returning the final Run the  action, discarding the final     !#(KNoneDAn edit on type a, relating an element of a container (like an entry in a map or a line in a file) before and after.&Element was removed from the container"Element was added to the container8Element was changed. Carries the values before and afterA wrapper around  with the sole purpose of informing call sites that the provided 5 and 6 instances are nondeterministic. If you use this please provide a justification why it doesn't introduce nondeterminism. See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM to learn about determinism.A finite map from uniques* of one type to elements in another type.The key is just here to keep us honest. It's always safe to use a single type as key. If two types don't overlap in their uniques it's also safe to index the same map at multiple key types. But this is very much discouraged.Add an element, returns previous lookup result and new map. If old element doesn't exist, add the passed element directly, otherwise compute the element to add using the passed function.Add elements to the map, combining existing values with inserted ones using the given function.1`plusUFM_CD f m1 d1 m2 d2` merges the maps using f! as the combinding function and d1 resp. d2/ as the default value if there is no entry in m1 reps. m2-. The domain is the union of the domains of m1 and m2.IMPORTANT NOTE: This function strictly applies the modification function and forces the result unlike most the other functions in this module.Representative example: plusUFM_CD f {A: 1, B: 2} 23 {B: 3, C: 4} 42 == {A: f 1 42, B: f 2 3, C: f 23 4 } ,`plusUFM_CD2 f m1 m2` merges the maps using f$ as the combining function. Unlike =, a missing value is not defaulted: it is instead passed as K to f. f' can never have both its arguments be K.IMPORTANT NOTE: This function strictly applies the modification function and forces the result.`plusUFM_CD2 f m1 m2` is the same as `plusUFM_CD f (mapUFM Just m1) Nothing (mapUFM Just m2) Nothing`.minusUFC_C f map1 map2 returns map1, except that every mapping key |-> value1 in map1" that shares a key with a mapping key |-> value2 in map2 is altered by f: value1 is replaced by f value1 value2 , where L& means that the new value is used and K$ means that the mapping is deleted. Fold over a .Non-deterministic, unless the folding function is commutative (i.e. a1 f ( a2 f b ) == a2 f ( a1 f b ) for all a1, a2, b).Like , but with the  key as well.Like , but you must ensure the passed-in function does not modify the unique.In essence foldM See Note [Deterministic UniqFM] to learn about nondeterminism. If you use this please provide a justification why it doesn't introduce nondeterminism. Cast the key domain of a UniqFM.As long as the domains don't overlap in their uniques this is safe.Computes the diff of two s in terms of >s. Equal points will not be present in the result map at all.Pretty-print a non-deterministic set. The order of variables is non-deterministic and for pretty-printing that shouldn't be a problem. Having this function helps contain the non-determinism created with nonDetEltsUFM.Pretty-print a non-deterministic set. The order of variables is non-deterministic and for pretty-printing that shouldn't be a problem. Having this function helps contain the non-determinism created with nonDetUFMToList.Determines the pluralisation suffix appropriate for the length of a set in the same way that plural from Outputable does for lists.Inherently nondeterministic. If you use this please provide a justification why it doesn't introduce nondeterminism. See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM to learn about determinism.Inherently nondeterministic. If you use this please provide a justification why it doesn't introduce nondeterminism. See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM to learn about determinism.old -> new -> resultoldnewresult Arguments of combining function of M.insertWith and addToUFM_C are flipped. key,old,new old, result How to adjustoldnewresult How to adjustoldnewresultThe things to be pretty printed3The pretty printing function to use on the elements+ where the things have been pretty printedThe things to be pretty printed3The pretty printing function to use on the elements+ where the things have been pretty printed  3  ' 4 1 -   NonedNoneMaps indexed by  keysAdd an element, returns previous lookup result and new map. If old element doesn't exist, add the passed element directly, otherwise compute the element to add using the passed function.'Intersection with a combining function.** 6   ! QNone  Lift a pure  action into a  such as Transformer version of  to use when threading a deterministic uniq supply over a Monad. Specifically, it is used in the Stream of Cmm decls.:Get a unique from a monad that can access a unique supply.Crucially, because  doesn't allow you to get the  UniqSupply (unlike  MonadUnique), an instance such as  can use a deterministic unique supply to return deterministic uniques without allowing for the  UniqSupply to be shared./A monad which just gives the ability to obtain +s deterministically. There's no splitting.Initialize a deterministic unique supply with the given Tag and initial unique.Set the tag of uniques generated from this deterministic unique supplyGet the tag uniques generated from this deterministic unique supply would haveSet the tag of the running UniqDSMT supply to the given tag and run an action with it. All uniques produced in the given action will use this tag, until the tag is changed again.Like  but for Lift an IO action that depends on, and threads through, a unique supply into UniqDSMT IO.'Change the monad underyling an applied UniqDSMT, i.e. transform a  UniqDSMT m into a  UniqDSMT n given m ~> n.Lift a monadic action m a into an  UniqDSMT m aTag    #   0 + ' - .   !#(_None(Type of unique deterministic finite mapsThe key is just here to keep us honest. It's always safe to use a single type as key. If two types don't overlap in their uniques it's also safe to index the same map at multiple key types. But this is very much discouraged.+A type of values tagged with insertion timeinsertion timeLike 7 but also passes the unique key to the combine functionLike 6 but the combine function also receives the unique keyLike 5, but the merge function also receives the unique keyPerforms a deterministic fold over the UniqDFM. It's O(n log n) while the corresponding function on  is O(n).Like % but the function also receives a keyPerforms a nondeterministic strict fold over the UniqDFM. It's O(n), same as the corresponding function on . If you use this please provide a justification why it doesn't introduce nondeterminism. Converts  to a list, with elements in deterministic order. It's O(n log n) while the corresponding function on  is O(n).>Partition UniqDFM into two UniqDFMs according to the predicate(Delete a list of elements from a UniqDFM7This allows for lossy conversion from UniqDFM to UniqFM(Apply a function to a particular element(Apply a function to a particular elementThe expression (alterUDFM f k map) alters value x at k, or absence thereof. alterUDFM can be used to insert, delete, or update a value in UniqDFM. Use addToUDFM, delFromUDFM or adjustUDFM when possible, they are more efficient.,Map a function over every value in a UniqDFM for a . Cast the key domain of a UniqFM.As long as the domains don't overlap in their uniques this is safe.Deterministic, in O(n log n).Deterministic, in O(n log n).The things to be pretty printed3The pretty printing function to use on the elements+ where the things have been pretty printed44  & 4 #    "*,7aNone%Set of Unique valuesSimilar to 'UniqSet Unique' but with a more compact representation.Set of Uniquable valuesWhat's the point you might ask? We might have changed an object without it's key changing. In which case this lookup makes sense.Like , but you must ensure the passed in function does not change the . converts a  a into a  a0 assuming, without checking, that it maps each  to a value that has that . See Note [UniqSet invariant].99  0  ( %'-!#139NoneBGraph nodes. Represents a thing that can conflict with another thing. For the register allocater the nodes represent registers.>Neighbors that this node would like to be colored the same as.>Colors that this node would prefer to be, in descending order.(Colors that cannot be used by this node.9Neighbors which must be colored differently to this node.The color of this node, if any.The class of this node, determines the set of colors that can be used."A unique identifier for this node.The Interference graph. There used to be more fields, but they were turfed out in a previous revision. maybe we'll want more later..All active nodes in the graph.A fn to check if a node is trivially colorable For graphs who's color classes are disjoint then a node is 'trivially colorable' when it has less neighbors and exclusions than available colors for that node.For graph's who's color classes overlap, ie some colors alias other colors, then this can be a bit more tricky. There is a general way to calculate this, but it's likely be too slow for use in the code. The coloring algorithm takes a canned function which can be optimised by the user to be specific to the specific graph being colored.for details, see "A Generalised Algorithm for Graph-Coloring Register Allocation" Smith, Ramsey, Holloway - PLDI 2004.An empty graph.5Modify the finite map holding the nodes in the graph.An empty node.None6 $A  whose domain is sets of /s, each of which share a common value of type ele. Every such set ("equivalence class") has a distinct representative . Supports merging the entries of multiple such sets in a union-find like fashion.An accurate model is that of [(Set key, Maybe ele)]!: A finite mapping from sets of keys to possibly absent entries ele+, where the sets don't overlap. Example:  m = [({u1,u3}, Just ele1), ({u2}, Just ele2), ({u4,u7}, Nothing)] 9 On this model we support the following main operations: m u3 == Just ele1,  m u4 == Nothing,  m u5 == Nothing.ž m u1 u3 is a no-op, but ž m u1 u2 merges {u1,u3} and {u2} to point to  Just ele2 and returns the old entry of {u1,u3},  Just ele1.Þ m u3 ele4 sets the entry of {u1,u3} to  Just ele4.8As well as a few means for traversal/conversion to list.Either  Indirect x., meaning the value is represented by that of x , or an Entry6 containing containing the actual value it represents.lookupSUDFM env x looks up an entry for x, looking through all s until it finds a shared .$Examples in terms of the model (see ): >>> lookupUSDFM [({u1,u3}, Just ele1), ({u2}, Just ele2)] u3 == Just ele1 >>> lookupUSDFM [({u1,u3}, Just ele1), ({u2}, Just ele2)] u4 == Nothing >>> lookupUSDFM [({u1,u3}, Just ele1), ({u2}, Nothing)] u2 == NothingžequateUSDFM env x y makes x and y+ point to the same entry, thereby merging x's class with y 's. If both x and y$ are in the domain of the map, then y.'s entry will be chosen as the new entry and x's old entry will be returned.$Examples in terms of the model (see ): >>> equateUSDFM [] u1 u2 == (Nothing, [({u1,u2}, Nothing)]) >>> equateUSDFM [({u1,u3}, Just ele1)] u3 u4 == (Nothing, [({u1,u3,u4}, Just ele1)]) >>> equateUSDFM [({u1,u3}, Just ele1)] u4 u3 == (Nothing, [({u1,u3,u4}, Just ele1)]) >>> equateUSDFM [({u1,u3}, Just ele1), ({u2}, Just ele2)] u3 u2 == (Just ele1, [({u2,u1,u3}, Just ele2)])ÞaddToUSDFM env x a sets the entry x is associated with to a1, thereby modifying its whole equivalence class.$Examples in terms of the model (see ): >>> addToUSDFM [] u1 ele1 == [({u1}, Just ele1)] >>> addToUSDFM [({u1,u3}, Just ele1)] u3 ele2 == [({u1,u3}, Just ele2)]ÞžĞžÞĞŞ ƞ bNoneLike  but for 0. Assumes the function we are mapping over the  does not modify uniques, as per Note [UniqSet invariant] in GHC.Types.Unique.Set. 1 66"`NoneA non-deterministic set of FastStrings. See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM for explanation why it's not deterministic and why it matters. Use DFastStringEnv if the set eventually gets converted into a list or folded over in a way where the order changes the generated code. Fold over a .Non-deterministic, unless the folding function is commutative (i.e. a1 f ( a2 f b ) == a2 f ( a1 f b ) for all a1, a2, b)."(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNoneA newtype wrapper around   for JS identifiers.To give a thing a name is to have power over it. This smart constructor serves two purposes: first, it isolates the JS backend from the rest of GHC. The backend should not explicitly use types provided by GHC but instead should wrap them such as we do here. Second it creates a symbol in the JS backend, but it does not yet give that symbols meaning. Giving the symbol meaning only occurs once it is used with a combinator from  GHC.JS.Make.44445555)"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone#rEnvironment for the JSM Monad. We maintain the prefix of each ident in the environment to allow consumers to tag idents with a new prefix. See withTagNewtype to serialise binding names differently to non-binding . See Note [Binary UserData]Encode the argument in its full length. This is different from many default binary instances which make no guarantee about the actual encoding and might do things using variable length encoding.Do not rely on instance sizes for general types, we use variable length encoding for many of them.A  is like a , but contains a relative offset pointer instead of an absolute offset.Like a  but is used to store relative offset pointers. Relative offset pointers store a relative location, but also contain an anchor that allow to obtain the absolute offset.Relative offset to  . The absolute position of the  is relBin_anchor + relBin_offset%Absolute position from where we read .A read-only handle that can be used to deserialise binary data from a buffer.&The buffer is an unboxed binary array.the array (bounds: (0,size-1))size of the array (cached)the current offsetUser data for reading binary inputs. Allows users to overwrite certain 2 instances. This is helpful when a non-canonical / instance is required, such as in the case of .A write-only handle that can be used to serialise binary data into a buffer.&The buffer is an unboxed binary array.the array (bounds: (0,size-1))size of the array (cached)the current offset…User data for writing binary outputs. Allows users to overwrite certain 2 instances. This is helpful when a non-canonical / instance is required, such as in the case of . stores a slice to a .It requires less memory than !, and can be constructed from a  via  and turned back into a  using 8. Additionally, the byte array slice can be put into a  without extra conversions via .total buffer size end offset start offset$ that can be used to resume reading. Write the  slice into the . Freeze a  and a start index into a . stores a slice starting from the 'Bin a' location to the current offset of the . Turn the  into a , setting the  offset to the start of the  and restore the  that was obtained from .Add " as a known binary decoder. If a + for the associated type already exists in , it is overwritten.Add " as a known binary encoder. If a + for the associated type already exists in , it is overwritten.$Get access to the underlying buffer./Read a relative offset location and wrap it in .The resulting ; can be translated into an absolute offset location using ÅFreeze the given  and turn it into an equivalent .The current offset of the  is maintained in the new .Copy the BinBuffer to a new BinBuffer which is exactly the right size. This performs a copy of the underlying buffer. The buffer may be truncated if the offset is not at the end of the written output.UserData is also discarded during the copy You should just use this when translating a Put handle into a Get handle.ąą moves the index pointer to the location pointed to by 'Bin a'. This operation may =, if the pointer location is out of bounds of the buffer of  BinHandle.%SeekBin but without calling expandBinŅ&Takes a size and action writing up to size bytes. After the action has run advance the index to the buffer by size bytes. put_A put_B outputs A after B but allows A to be read before B by using a forward reference.-Read a value stored using a forward reference;The forward reference is expected to be an absolute offset. put_A put_B outputs A after B but allows A to be read before B by using a forward reference.This forward reference is a relative offset that allows us to skip over the result of put_A.Like , but discard the result..Read a value stored using a forward reference.:The forward reference is expected to be a relative offset.Serialize the constructor strictly but lazily serialize a value inside a L.This way we can check for the presence of a value without deserializing the value itself."Deserialize a value serialized by . Find the  for the / instance for the type identified by 'Proxy a'.If no 6 has been configured before, this function will panic. Find the  for the / instance for the type identified by 'Proxy a'.If no 6 has been configured before, this function will panic. Initialise a  , initialising the index to '0'.Serialise the  to disk.Since & stores tree-like structures, such as  IfaceType, serialising an element can add new elements to the mapping. Thus,  first serialises all values, and then checks whether any new elements have been discovered. If so, repeat the loop.Read the elements of a  from disk into a .&Write an element 'Key m' to the given .If the element was seen before, we simply write the index of that element to the ;. If we haven't seen it before, we add the element to the 1, increment the index, and return this new index.Read a value from a .Put a ByteString without its length (can't be read back without knowing the length!)&Get a ByteString whose length is known;This instance doesn't rely on the determinism of the keys' ,! instance, so it works e.g. for s too.how to deserialize show to serialize non-binding show to serialize binding s    ) $       (      5 - &     : . : ) -               - - - ,    +      # # #+*qNone+        1  8None&A Module is a pair of a  and a .A unit identifier identifies a (possibly partially) instantiated library. It is primarily used as part of , which in turn is used in Name=, which is used to give names to entities when typechecking.#There are two possible forms for a :1) It can be a ", in which case we just have a " that uniquely identifies some fully compiled, installed library we have on disk.2) It can be an ". When we are typechecking a library with missing holes, we may need to instantiate a library on the fly (in which case we don't have any on-disk representation.) In that case, you have an ", which explicitly records the instantiation, so that we can substitute over it.6A generic module is a pair of a unit identifier and a .A UnitId identifies a built library in a database and is used to generate unique symbols, etc. It's usually of the form:pkgname-1.2:libname+hash(These UnitId are provided to us via the  -this-unit-id flag.The library in question may be definite or indefinite; if it is indefinite, none of the holes have been filled (we never install partially instantiated libraries as we can cheaply instantiate them on-the-fly, cf VirtUnit). Put another way, an installed unit id is either fully instantiated, or not instantiated at all.""This data type just pairs a value s- with an IsBootInterface flag. In practice, s is usually a Module or  ModuleName'."3A definite unit (i.e. without any free module hole)"A " is an  with the invariant that it only refers to a definite library; i.e., one we have generated code for."The full hashed unit identifier, including the component id and the hash."An instantiated unit.It identifies an indefinite library (with holes) that has been instantiated.This unit may be indefinite or not (i.e. with remaining holes or not). If it is definite, we don't know if it has already been compiled and installed in a database. Nevertheless, we have a mechanism called "improvement" to try to match a fully instantiated unit with existing compiled and installed units: see Note [VirtUnit to RealUnit improvement].?An indefinite unit identifier pretty-prints to something like p[H= H ,A=aimpl:A>] (p is the 5, and the brackets enclose the module substitution)."$A cache of the free module holes of "&. This lets us efficiently tell if a " has been fully instantiated (empty set of free module holes) and whether or not a substitution can have any effect."The sorted (by ) instantiations of this unit.")The (indefinite) unit being instantiated."Cached unique of "."A private, uniquely identifying representation of an InstantiatedUnit. This string is completely private to GHC and is just used to get a unique."Installed definite unit (either a fully instantiated unit or a closed unit)"Virtual unit instantiated on-the-fly. It may be definite if all the holes are instantiated but we don't have code objects for it."Fake hole unit"A unit key in the database"Class for types that are used as unit identifiers (UnitKey, UnitId, Unit)We need this class because we create new unit ids for virtual units (see VirtUnit) and they have to to be made from units with different kinds of identifiers."An " is a " whose unit is identified with an "."A " is like an " but we expect to find it in one of the home units rather than the package database."A " is a # whose unit is identified with an ."Module name (e.g. A.B.C)"Unit the module belongs to"2Compares unit ids lexically, rather than by their s"+Retrieve the set of free module holes of a ."Calculate the free holes of a . If this set is non-empty, this module was defined in an indefinite library that had required signatures.If a module has free holes, that means that substitutions can operate on it; if it has no free holes, substituting over a module has no effect." Create a new "' given an explicit module substitution."*Smart constructor for instantiated GenUnit"Generate a uniquely identifying hash (internal unit-id) for an instantiated unit.This is a one-way function. If the indefinite unit has not been instantiated at all, we return its unit-id.This hash is completely internal to GHC and is not used for symbol names or file paths. It is different from the hash Cabal would produce for the same instantiated unit.ƅ2Generate a hash for a sorted module instantiation."+Create a new simple unit identifier from a  . Internally, this is primarily used to specify wired-in unit identifiers."Map over the unit type of a "4Map over the unit identifier of unit instantiations.#Return the UnitId of the Unit. For on-the-fly instantiated units, return the UnitId of the indefinite unit this unit is an instance of.#=Return the virtual UnitId of an on-the-fly instantiated unit.#A % is definite if it has no free holes.#This is the package Id for the current program. It is the default package Id if you don't specify a package name. We don't add this prefix to symbol names, since there can be only one main package per program.##"####"###""""""""#"""####""####"##"##"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""##""#""##"""################"""""""#0#  # # # *# # # # # # # # $# -# &# (# '# ,# !# %# '# # # # # # # # # 6# .#####!##.####)#+1#3<#># ####!None%%%%%%%%{None) #Module LocationWhere a module lives on the file system: the actual locations of the .hs, .hi, .dyn_hi, .o, .dyn_o and .hie files, if we have them.For a module in another unit, the ml_hs_file_ospath and ml_obj_file_ospath components of ModLocation are undefined.The locations specified by a ModLocation may or may not correspond to actual files yet: for example, even if the object file doesn't exist, the ModLocation still contains the path to where the object file will reside if/when it is created.The paths of anything which can affect recompilation should be placed inside ModLocation.When a ModLocation is created none of the filepaths will have -boot suffixes. This is because in --make mode the ModLocation is put in the finder cache which is indexed by ModuleName, when a ModLocation is retrieved from the FinderCache the boot suffixes are appended. The other case is in -c mode, there the ModLocation immediately gets given the boot suffixes in mkOneShotModLocation.#6Where the .hie file is, whether or not it exists yet.#5Where the .dy file is, whether or not it exists yet.#Where the .o file is, whether or not it exists yet. (might not exist either because the module hasn't been compiled yet, or because it is part of a unit with a .a file)#9Where the .dyn_hi file is, whether or not it exists yet.#Where the .hi file is, whether or not it exists yet. Always of form foo.hi, even if there is an hi-boot file (we add the -boot suffix later)#The source file, if we have one. Package modules probably don't have source files.#Add the -boot suffix to .hs, .hi and .o files# Remove the -boot suffix to .hs, .hi and .o files#Add the -boot suffix if the Bool argument is True#Add the -boot4 suffix to all file paths associated with the module#Add the -boot suffix to all output file paths associated with the module, not including the input file itself# Compute a  from a #.############################################# #|NoneC#A map keyed off of "#A map keyed off of "#A map keyed off of s (actually, their s) Has deterministic folds and can be deterministically converted to a list#A map keyed off of s (actually, their s)# A set of s#A map keyed off of s:#$$##$#$$$##$$######$$#$$$##$$####$$$#####$#$$##$$#$######:#############################$##$$$$$$#$#$$$$$$$$#$$$$$$$$$ $ $ 2$ ?$ $ }None&' $A % is definite if it has no free holes.$!Get a string representation of a  that's unique and stable across recompilations. eg. "$aeson_70dylHtv1FFGeai1IoxcQr$Data.Aeson.Types.Internal"$This gives a stable ordering, as opposed to the Ord instance which gives an ordering based on the Uniques of the components, which may not be stable from run to run of the compiler.$ Test if a  corresponds to a given ", modulo instantiation.$Given a possibly on-the-fly instantiated module, split it into a  that we definitely can find on-disk, as well as an instantiation if we need to instantiate it on the fly. If the instantiation is Nothing" no on-the-fly renaming is needed.$Return the unit-id this unit is an instance of and the module instantiations (if any).$4Remove instantiations of the given instantiated unit$;Remove instantiations of the given module instantiated unit$$Test if a Module is not instantiated$Create a hole Module$$$$$$$$$$#$$##$#$$$##$$######$$#$$$##$$####$$$#####$#$$##$$#$##########"####"###""""""""#"""####""####"##"##$$$$####################""""""""""""""""""""""""""""""""""""$$$$$$$$$$$$$$None=Internal breakpoint identifier!See Note [Breakpoint identifiers]Breakpoint info indexBreakpoint info moduleBreakpoint tick indexBreakpoint tick moduleBreakpoint identifier.!See Note [Breakpoint identifiers]Breakpoint tick indexBreakpoint tick module  None$Information about the home unit (i.e., the until that will contain the modules we are compiling)The unit identifier of the instantiating units is left open to allow switching from UnitKey (what is provided by the user) to UnitId (internal unit identifier) with $.TODO: this isn't implemented yet. UnitKeys are still converted too early into UnitIds in GHC.Unit.State.readUnitDataBase$.Definite home unit (i.e. that we can compile).Nothing: not an instantiated unit Just (i,insts): made definite by instantiating "i" with "insts"$6Indefinite home unit (i.e. that we can only typecheck)All the holes are instantiated with fake modules from the Hole unit. See Note [Representation of module/name variables] in GHC.Unit$Return home unit id$Return home unit instantiations$Return the unit id of the unit that is instantiated by the home unit.-E.g. if home unit = q[A=p:B,...] we return q.If the home unit is not an instance of another unit, we return its own unit id (it is an instance of itself if you will).$Return the unit id of the unit that is instantiated by the home unit.4E.g. if home unit = q[A=p:B,...] we return (Just q).If the home unit is not an instance of another unit, we return Nothing.$&Return the home unit as a normal unit.We infer from the home unit itself the kind of unit we create: 1. If the home unit is definite, we must be compiling so we return a real unit. The definite home unit may be the result of a unit instantiation, say `p = q[A=r:X]`. In this case we could have returned a virtual unit `q[A=r:X]` but it's not what the clients of this function expect, especially because p is lost when we do this. The unit id of a virtual unit is made up internally so `unitId(q[A=r:X])` is not equal to p. If the home unit is indefinite we can only create a virtual unit from it. It's ok because we must be only typechecking the home unit so we won't produce any code object that rely on the unit id of this virtual unit.$4Map over the unit identifier for instantiating units$/Test if we are type-checking an indefinite unit7(if it is not, we should never use on-the-fly renaming)$(Test if we are compiling a definite unit3(if it is, we should never use on-the-fly renaming)$9Test if we are compiling by instantiating a definite unit$!Test if the unit is the home unit$'Test if the unit-id is the home unit-id$+Test if the unit-id is not the home unit-id$9Test if the home unit is an instance of the given unit-id$+Test if the module comes from the home unit$+Test if the module comes from the home unit$6Test if a module doesn't come from the given home unit$6Test if a module doesn't come from the given home unit%6Test if a module doesn't come from the given home unit%6Test if a module doesn't come from the given home unit%Make a module in home unit%Make a module in home unit%Return the module that is used to instantiate the given home module name. If the ModuleName doesn't refer to a signature, return the actual home module."E.g., the instantiating module of A in  p[A=q[]:B] is q[]:B%. the instantiating module of A in p is p:A.%Return the module that is used to instantiate the given home module.If the given module isn't a module hole, return the actual home module."E.g., the instantiating module of p:A in  p[A=q[]:B] is q[]:B%. the instantiating module of r:A in  p[A=q[]:B] is r:A%. the instantiating module of p:A in p is p:A%. the instantiating module of r:A in p is r:A.%%$$$$$$$$$$$$$$%%$$%%$$$$$$$$$$$$$$$$$$$$$$$$%%$$%%%%None   !%,jNone&')Z A String Literal in the source, including its original raw format for use by source to source manipulation tools.Fractional LiteralUsed (instead of Rational) to represent exactly the floating point literal that we encountered in the user's source program. This allows us to pretty-print exactly what the user wrote, which is important e.g. for floating point numbers that can't represented as Doubles (we used to via Double for pretty-printing). See also #2245. Note [FractionalLit representation] in GHC.HsToCore.Match.Literal The actual value then is: sign * fl_signi * (fl_exp_base^fl_exp) where sign = if fl_neg then (-1) else 1For example FL { fl_neg = True, fl_signi = 5.3, fl_exp = 4, fl_exp_base = Base10 } denotes -5300'How the value was written in the sourceIntegral LiteralUsed (instead of Integer) to represent negative zegative zero which is required for NegativeLiterals extension to correctly parse `-0::Double` as negative zero. See also #13211.For when code is generated, e.g. TH, deriving. The pretty printer will then make its own representation of the item./Special combinator for showing string literals.7The integer should already be negated if it's negative.=The arguments should already be negated if they are negative.DžCompare fractional lits with small exponents for value equality but large values for syntactic equality.Be wary of using this instance to compare for equal *values* when exponents are large. The same value expressed in different syntactic form won't compare as equal when any of the exponents is >= 100.Be wary of using this instance to compare for equal *values* when exponents are large. The same value expressed in different syntactic form won't compare as equal when any of the exponents is >= 100.!!        "   " #'  NoneE% Package-qualifier after renamingRenaming detects if "this" or the unit-id of the home-unit was used as a package qualifier.%No package qualifier%Import from home-unit%Import from another unit%"Package-qualifier as it was parsed%No package qualifier%Raw package qualifier string.%%%%%%%%%%%%%%% %# #% %%% NoneU%.hs file%.hs-boot or .hsig file% .hs-boot file% .hsig file% Tests if an %9 is a boot file, primarily for constructing elements of  BuildModule. We conflate signatures and modules because they are bound in the same namespace; only boot interfaces can be disambiguated with `import {-# SOURCE #-}`. %%%%%%%%%%%%%%%%%%%%%%%%%%%%% %==%==%==%66%66%66NoneA newtype wrapper around < to ensure we never generate a < that becomes a NaN&, see instances for details on sanity." "    Ÿ"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone  #+/ßJS Unary OperatorsğVanilla Assignment: =şAddition Assignment: +=ƟSubtraction Assignment: -=ǟJS Unary Operatorsȟ Logical Not: !ɟ Bitwise Not: ~ʟ Negation: -˟ Unary Plus: +x̟new x͟typeof xΟdelete xϟyield xПvoid xџPrefix Increment: ++xҟPostfix Increment: x++ӟPrefix Decrement: --xԟPostfix Decrement: x--՟JS Binary Operators. We do not deeply embed the comma operator and the assignment operators֟Equality: ןStrict Equality: ===؟InEquality: !=ٟStrict InEquality !==ڟGreater Than: Y۟Greater Than or Equal: ܟLess Than: <ݟLess Than or Equal: <=ޟAddition: +ߟSubtraction: -Multiplication *Division: /Remainder: %Left Shift: <<Right Shift: >>Unsigned RightShift: >>>Bitwise And: &Bitwise Or: |Bitwise XOr: ^Logical And: &&Logical Or: ||  instanceof inJavaScript valuesA variable reference,A JavaScript list, or what JS calls an ArrayA DoubleA BigIntA StringA Regex A BooleanA JS HashMap:  {"foo": 0} A functionJavaScript Expressions$All values are trivially expressionsSelection: Obj.foo, see Indexing: Obj[foo], see Infix Expressions, see  pattern synonymsUnary Expressions If-expression ApplicationA Label used for , specifically ,  and of course JavaScript statements, see the  https://tc39.es/ecma262/#sec-ecmascript-language-statements-and-declarationsECMA262 Reference for details$Variable declarations: var foo [= e]ReturnIfWhile, bool is "do" when TrueFor For-in, bool is "each' when TrueSwitchTryBlocks ApplicationUnary operatorsBinding form:  foo  op bar/Statement Labels, makes me nostalgic for qbasicBreakContinuean explicit function definition4pattern synonym to create a local variable reference'pattern synonym to create string values(pattern synonym to create integer values pattern synonym for logical And &&pattern synonym for logical Or || pattern synonym for Bitwise Not ~ pattern synonym for Bitwise XOr ^ pattern synonym for Bitwise And &pattern synonym for Bitwise Or |pattern synonym for remainder %pattern synonym for division *#pattern synonym for multiplication * pattern synonym for subtraction -pattern synonym for addition +#pattern synonym for unary negation - pattern synonym for logical not !&pattern synonym for postfix decrement --x%pattern synonym for prefix decrement --x&pattern synonym for postfix increment x++%pattern synonym for prefix increment ++x(pattern synonym for a unary operator newȅ)Append a statement to another statement. ȅ only returns a  that is not a  when either mx or @my is an empty . That is: > (BlockStat [] , y ) = y > (x , BlockStat []) = x!construct a JS variable referenceThe JS literal trueThe JS literal falseßşğƟ՟ޟ֟۟ڟݟܟ؟ןٟߟǟɟΟʟ̟ȟ˟ԟҟӟџ͟Пϟ՟ޟ֟۟ڟݟܟ؟ןٟߟǟɟΟʟ̟ȟ˟ԟҟӟџ͟ПϟßşğƟ          "&(/  "&(/  à Ġ"&Š(/"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone#+/y ƠJsRender controls the differences in whitespace between HLine and SDoc. Generally, this involves the indentation and newlines in the human-readable SDoc implementation being replaced in the HLine version by the minimal whitespace required for valid JavaScript syntax.Ǡ)Concatenate with an optional single spaceȠ$Concatenate with an optional newlineɠConcatenate these doc3s, either vertically (SDoc) or horizontally (HLine)ʠOptionally indent the followingˠ0Append semi-colon (and line-break in HLine mode)ԠRender a syntax tree as a pretty-printable document (simply showing the resultant doc produces a nice, well formatted String).נRender a syntax tree as a pretty-printable document, using a given prefix to all generated names. Use this with distinct prefixes to ensure distinct generated names between independent calls to render(Prefix)Js.ɅRemove one Block layering if we know we already have braces around the statement۠?The structure `{body}`, optionally indented over multiple linesܠThe structure `hdr {body}`, optionally indented over multiple lines۠ՠܠڠ֠٠ԠנؠƠȠǠˠɠʠ̠͠ΠϠҠРӠѠԠנؠ̠͠ՠΠϠҠРӠѠƠȠǠˠɠʠ֠٠ڠ۠ܠ ݠ ޠ ߠ        "(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry  experimentalNone#)-Render JS with code size minimization enabledʅRender as an hexadecimal number in reversed order (because it's faster and we don't care about the actual value)."(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith experimental This module contains a simple expression optimizer that performs constant folding and some boolean expression optimizations.None)"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone#˅A trivial assignment is an assignment of a variable to itself: x = x̅&Does the expression have side effects?This only returns False if the expression definitely does not have side effects, i.e. it can be removed without changing the semantics if the result is not used.Note: We have some assumptions here about Haskell RTS related values, which may not be true for all JavaScript code. We should really replace these with explicit nodes or annotations in the AST.     !     "(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone# ͅA BlockOpt is a function that alters the stream, and a continuation that represents the rest of the stream. The first  BlockTrans represents restarting the optimizer after a change has happened. The second  BlockTrans1 represents the rest of the continuation stream.΅A block transformation is a function from a stream of syntax to another streamυ recur over a JExpr and optimize the JValsЅ?drive optimizations to anonymous functions and over expressionsх loop until a fixpoint is reached҅5Perform all the optimizations on the tail of a block.ӅCatch modify and assign operators: case 1: i = i + 1; ==> ++i; case 2: i = i - 1; ==> --i; case 3: i = i + n; ==> i += n; case 4: i = i - n; ==> i -= n;ԅ&Catch 'var i; i = q;' ==> 'var i = q;'ՅEliminate all code after a return statement. This is a special case optimization that doesn't need to loop. See Note [Unsafe JavaScript optimizations]օremove nested blocksׅstack adjustmentsTo merge two BlockOpt we first run the left-hand side optimization and capture the right-hand side in the continuation  "(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone +/JS Unary OperatorsVanilla Assignment: =Addition Assignment: +=Subtraction Assignment: -=JS Unary Operators Logical Not: ! Bitwise Not: ~ Negation: - Unary Plus: +xnew xtypeof xdelete xyield xvoid xPrefix Increment: ++xPostfix Increment: x++Prefix Decrement: --xPostfix Decrement: x--JS Binary Operators. We do not deeply embed the comma operator and the assignment operatorsEquality: Strict Equality: ===InEquality: !=Strict InEquality !==Greater Than: YGreater Than or Equal: Less Than: <Less Than or Equal: <=Addition: +Subtraction: -Multiplication *Division: /Remainder: %Left Shift: <<Right Shift: >>Unsigned RightShift: >>>Bitwise And: &Bitwise Or: |Bitwise XOr: ^Logical And: &&Logical Or: ||  instanceof inJavaScript valuesA variable reference/A JavaScript list, or what JS calls an ArrayA DoubleA BigIntA StringA Regex A BooleanA JS HashMap:  {"foo": 0} A functionJavaScript Expressions$All values are trivially expressionsSelection: Obj.foo, see Indexing: Obj[foo], see Infix Expressions, see  pattern synonymsUnary Expressions If-expression ApplicationA Label used for , specifically ơ, ǡ and of course šJavaScript statements, see the  https://tc39.es/ecma262/#sec-ecmascript-language-statements-and-declarationsECMA262 Reference for details$Variable declarations: var foo [= e]ReturnIfWhile, bool is "do" when TrueFor For-in, bool is "each' when TrueSwitchTryBlocks¡ ApplicationáUnary operatorsġBinding form:  foo = barš/Statement Labels, makes me nostalgic for qbasicơBreakǡContinueȡan explicit function definitionɡ/pattern synonym to create an anonymous functionʡ4pattern synonym to create a local variable referenceˡ'pattern synonym to create string values̡(pattern synonym to create integer values͡ pattern synonym for logical And &&Ρpattern synonym for logical Or ||ϡ pattern synonym for Bitwise Not ~С pattern synonym for Bitwise XOr ^ѡ pattern synonym for Bitwise And &ҡpattern synonym for Bitwise Or |ӡpattern synonym for remainder %ԡpattern synonym for division *ա#pattern synonym for multiplication *֡ pattern synonym for subtraction -סpattern synonym for addition +ء#pattern synonym for unary negation -١ pattern synonym for logical not !ڡ&pattern synonym for postfix decrement --xۡ%pattern synonym for prefix decrement --xܡ&pattern synonym for postfix increment x++ݡ%pattern synonym for prefix increment ++xޡ(pattern synonym for a unary operator new؅)Append a statement to another statement. ؅ only returns a  that is not a  when either mx or @my is an empty . That is: > (BlockStat [] , y ) = y > (x , BlockStat []) = xߡ Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone#+3Type class that finds the form of arguments required for a JS syntax object. This class gives us a single interface to generate variables for functions that have different arities. Thus with it, we can have only one  jFunction1 which is polymorphic over its arity, instead of  jFunction2,  jFunction3 and so on. Type class that generates fresh a's for the JS backend. You should almost never need to use this directly. Instead use  JSArgument:, for examples of how to employ these classes please see jVar,  jFunction and call sites in the Rts.The  class handles injection of of things into the EDSL as a JS statement. This ends up being polymorphic sugar for JS blocks, see helper function 1. Instantiate for any necessary data structures.Things that can be marshalled into javascript values. Instantiate for any necessary data structures.مConvert A JS expression to a JS statement where applicable. This only affects applications; , If-expressions; , and Unary expression; .1Create a new anonymous function. The result is a  expression. Usage: jLam $ \x -> jVar x + one_ jLam $ \f -> (jLam $ \x -> (f `app` (x `app` x))) `app` (jLam $ \x -> (f `app` (x `app` x)))Special case of jLam; where the anonymous function requires no fresh arguments.Introduce only one new variable into scope for the duration of the enclosed expression. The result is a block statement. Usage:+'jVar $ x -> mconcat [jVar x ||= one_, ...'Introduce one or many new variables into scope for the duration of the enclosed expression. This function reifies the number of arguments based on the container of the input function. We intentionally avoid lists and instead opt for tuples because lists are not sized in general. The result is a block statement. Usage: 9jVars $ (x,y) -> mconcat [ x |= one_, y |= two_, x + y]Construct a top-level function subject to JS hoisting. This combinator is polymorphic over function arity so you can you use to define a JS syntax object in Haskell, which is a function in JS that takes 2 or 4 or whatever arguments. For a singleton function use the Solo constructor MkSolo . Usage:an example from the Rts that defines a 1-arity JS function > jFunction (global "h$getReg") ((MkSolo n) -> return $ SwitchStat n getRegCases mempty)an example of a two argument function from the Rts > jFunction (global "h$bh_lne") ((x, frameSize) -> bhLneStats s x frameSize)Construct a top-level function subject to JS hoisting. Special case where the arity cannot be deduced from the 2 parameter (atleast not without dependent types).Construct a top-level function subject to JS hoisting. Special case where the function binds no parameters$Create a 'for in' statement. Usage: .jForIn {expression} $ x -> {block involving x}8As with "jForIn" but creating a "for each in" statement. Create a for statement given a function for initialization, a predicate to step to, a step and a body Usage:  jFor (|= zero_) (.<. Int 65536) preIncrS (j -> ...something with the counter j...)8As with "jForIn" but creating a "for each in" statement.+Convert a FastString to a Javascript String4construct a js declaration with the given identifierThe empty JS HashMapA singleton JS HashMap)insert a key-value pair into a JS HashMap5Construct a JS HashMap from a list of key-value pairsThe empty JS statementJS infix Equality operatorsJS infix Equality operatorsJS infix Equality operatorsJS infix Equality operatorsJS infix Ord operatorsJS infix Ord operatorsJS infix Ord operatorsJS infix Ord operatorsJS infix bit operatorsJS infix bit operatorsJS infix bit operatorsJS infix bit shift operatorsJS infix bit shift operatorsJS infix bit shift operatorsGiven a , return the its type.JS if-expression if_ e1 e2 e3 ==> e1 ? e2 : e34If-expression which returns statements, see related  'if e s1 s2 ==> if(e) { s1 } else { s2 }Version of a JS if-expression which admits monadic actions in its branches(A when-statement as syntactic sugar via  2jwhenS cond block ==> if(cond) { block } else { }"If-expression which returns blocks -ifBlockS e s1 s2 ==> if(e) { s1 } else { s2 }*if-expression that returns 1 if condition  = true, 0 otherwise if10 e ==> e ? 1 : 0*if-expression that returns 0 if condition  = true, 1 otherwise if01 e ==> e ? 0 : 1'an application expression, see related  app f xs ==> f(xs)1A statement application, see the expression form  Return a ("for" loop with increment at end of body("for" loop with increment at end of bodyPrefix-increment a Postfix-increment a Prefix-decrement a Postfix-decrement a 'Byte indexing of o with a 64-bit offset'Byte indexing of o with a 32-bit offset¢'Byte indexing of o with a 16-bit offsetâ&Byte indexing of o with a 8-bit offsetĢ'a bit mask to retrieve the lower 8-bitsŢ(a bit mask to retrieve the lower 16-bitsƢ Sign-extend/narrow a 8-bit valueǢ!Sign-extend/narrow a 16-bit valueȢSelect a property prop, from and object obj obj .^ prop ==> obj.propɢ"Assign a variable to an expression foo |= expr ==> var foo = expr;ʢDeclare a variable and then Assign the variable to an expression $foo |= expr ==> var foo; foo = expr;ˢ#return the expression at idx of obj obj .! idx ==> obj[idx]ТThe JS literal ѢThe JS literal 0ҢThe JS literal 1ӢThe JS literal 2ԢThe JS literal 3բThe JS literal k֢The JS literal trueעThe JS literal false global name:function body, input is locally unique generated variables global nameArity:function body, input is locally unique generated variables global name:function body, input is locally unique generated variablesinitialization function predicate step functionbodyˢȢ̢͢΢ϢעŢĢޢߢۢݢ٢ڢܢТ¢âҢآǢƢԢ֢ӢբѢɢʢIUTʢɢˢâ¢ĢŢƢǢآ̢͢΢ϢȢТբע֢ѢҢӢԢ٢ڢۢܢݢޢߢIUTU   Ȣɢʢˢ%      > 1       / 5     "        / - + ) ' % # !  9None#J Return registersExtra results from foreign calls can be stored here (while first result is directly returned)Stack registersGeneral purpose "registers"1The JS backend arbitrarily supports 128 registers#List of registers, starting from R1#List of registers, starting from R2/List of registers, starting from R1 as JStgExpr,List of registers, starting from R2 as JExprGiven a register, return the JS syntax object representing that registerGiven a register, return the JS syntax object representing that register§çħŧƧǧȧɧʧ˧̧ͧΧϧЧѧҧӧԧէ֧קا٧ڧۧܧݧާߧ§çħŧƧǧȧɧʧ˧̧ͧΧϧЧѧҧӧԧէ֧קا٧ڧۧܧݧާߧ     ")+- = ======= ="=)=+=-vNone] "Safe Haskell information for ModIface Simply a wrapper around SafeHaskellMode to separate iface and flags"The various Safe Haskell modes"inferred unsafe"declared and checked"declared and checked"declared and checked"inferred as safe"-fno-safe-haskell state"Is an import a safe import? """""""""""" """""""""""""* *$"" "" " #"  ~None$ A C type, used in CAPI FFI calls$,How to call a particular function in C-land.$Might invoke Haskell GC, or do a call back, or switch threads, etc. So make sure things are tidy before the call. Additionally, in the threaded RTS we arrange for the external call to be executed by a separate OS thread, i.e., _concurrently_ to the execution of other Haskell threads.$Like PlaySafe, but additionally the worker thread running this foreign call may be unceremoniously killed, so it must be scheduled on an unbound thread.$None of the above can happen; the call will return without interacting with the runtime system at all. Specifically:No GC No call backs No blockingNo precise exceptions $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $ $ $ $ $ $ $ $1 1 $ $  $ $ $ $ $$$$$ $* *$ $ $$ $$$$$$"lNonej Flag to indicate whether the FieldSelectors extension is enabled..Selector functions are available (the default)$Selector functions are not availableFlag to indicate whether the DuplicateRecordFields extension is enabled.+Fields may be duplicated in a single module3Fields must be unique within a module (the default):Fields in an algebraic record type; see Note [FieldLabel].The  of the selector function, which uniquely identifies the field label.Was FieldSelectors enabled in the defining module for this datatype? See Note [NoFieldSelectors] in GHC.Rename.EnvWas DuplicateRecordFields- on in the defining module for this datatype?2A map from labels to all the auxiliary informationUser-visible label of a field. We need the  Binary Name> constraint here even though there is an instance defined in GHC.Types.Name, because the we have a SOURCE import, so the instance is not in scope. And the instance cannot be added to Name.hs-boot because GHC.Utils.Binary itself depends on GHC.Types.Name. $ % & * &  #  *     oNone 9An index into a given cost centre module,name,flavour set2Per-module state for tracking cost centre indices.See documentation of  for more details.Initialize cost centre state.-Get a new index for a given cost centre name. "rNone ReadingWriting  ? ?! !kNone#A contiguous chunk of documentation'|' is the decorator is the decorator'$ string' is the decorator%The decorator is the given number of msHaskell Documentation StringRich structure to support exact printing The location around each chunk doesn't include the decorators#The first chunk is preceded by "--  decorator" and each following chunk is preceded by "--" Example: -- | This is a docstring for foo$. It is the line with the decorator '|' and is always included -- This continues that docstring and is the second element in the NonEmpty list foo :: a -> a The docstring is preceded by "{- decorator" and followed by "-}" The chunk contains balanced pairs of '{-' and '-}'A docstring generated either internally or via TH Pretty printed with the '-- |' decorator This is because it may contain unbalanced pairs of '{-' and '-}' and not form a valid Annotate a pretty printed thing with its doc The docstring comes after if is  Otherwise it comes before. Note - we convert MultiLineDocString HsDocStringPrevious to HsDocStringNext because we can't control if something else will be pretty printed on the same line Create a  from a UTF8-encoded τ.:Pretty print with decorators, exactly as the user wrote it:Pretty print with decorators, exactly as the user wrote it.Just get the docstring, without any decoratorsڅ&Don't add a newline to a single stringJust get the docstring, without any decorators Separates docstrings using "nn", which is how haddock likes to render them % % ) % !  ? ? = ===== $  mNone  , , ! !  $ "nNone  pNoneRepresents the  as a bit set.+Assumes that all elements are non-negative.This is only efficient for values that are sufficiently small, for example in the lower hundreds.2 2  &uNone1A group of warning flags that can be enabled or disabled collectively, e.g. using -Wcompat to enable all warnings in the  group.-Enumerates the simple on-or-off dynamic flags.Append dump output to files instead of stdout. Use foo.ways. dumpFlag instead of foo. dumpFlag8Enable floating out of let-bindings in the simplifierEnable floating out of let-bindings at the top level in the simplifier N.B. See Note [RHS Floating]deprecated, no effect and behaviour is now default. Allowed switching of a special demand transformer for dictionary selectors)Use the cfg based block layout algorithm.+Layout based on last instruction per block.;Do W/W split for unlifting even if we won't unbox anything.Keep auto-generated rules even if they seem to have become uselessrender JavaScript pretty-printed instead of minified (compacted)don't link C sources (compiled to JS) with Haskell code (compiled to JS)Ignore manual SCC annotations -fPIC -fPIE -pie Use regular thunks even when we could use std ap thunks in order to get entry counts -fcompact-unwind Dump diagnostics as JSON Suppress timestamps in dumps -Suppress per binding Core size stats in dumps Debugging flags!#Dump the cfg used for block layout.!Initial STG (CoreToStg output)!STG after unarise!STG (after stg2stg)!!Result of tag inference analysis.!Final STG (before cmm gen)!The default Language is used if one is not specified explicitly, by both GHC and GHCi.!Always returns !6 even when the flag is only conditionally deprecated.ۅIs this extension known by any other names? For example -XGeneralizedNewtypeDeriving is accepted!-All the names by which an extension is known.!)Helper function to query whether a given   is enabled or not.!Is the flag implicitly enabled when the verbosity is high enough?!The set of flags which affect optimisation for the purposes of recompilation avoidance. Specifically, these include flags which affect code generation but not the semantics of the program.See Note [Ignoring some flag changes] in GHC.Iface.Recomp.Flags)!The set of flags which affect code generation and can change a program's runtime behavior (other than performance). These include flags which affect:?user visible debugging information (e.g. info table provenance);the ability to catch runtime errors (e.g. -fignore-asserts)6the runtime result of the program (e.g. -fomit-yields)5which code or interface file declarations are emittedWe also considered placing flags which affect asympototic space behavior (e.g. -ffull-laziness) however this would mean that changing optimisation levels would trigger recompilation even with -fignore-optim-changes, regressing #13604.Also, arguably Opt_IgnoreAsserts should be here as well; however, we place it instead in ! since it is implied by -O[12]( and therefore would also break #13604. See #23369.!!Return the names of a WarningFlagOne flag may have several names because of US/UK spelling. The first one is the "preferred one" that will be displayed in warning messages.!Does this warning group contain (all) extended warning categories? See Note [Warning categories] in GHC.Unit.Module.Warnings.The * group contains extended warnings but no 5s, but extended warnings are also treated as part of + and every warning group that includes it.!Warning groups.As all warnings are in the Weverything set, it is ignored when displaying to the user which group a warning is in.!Warning group hierarchies, where there is an explicit inclusion relation.Each inner list is a hierarchy of warning groups, ordered from smallest to largest, where each group is a superset of the one before it.Separating this from ! allows for multiple hierarchies with no inherent relation to be defined.3The special-case Weverything group is not included.!Find the smallest group in every hierarchy which a warning belongs to, excluding Weverything.!The smallest group in every hierarchy to which a custom warning category belongs is currently always -Wextended-warnings$. See Note [Warning categories] in GHC.Unit.Module.Warnings.!+Warnings enabled unless specified otherwise!Things you get with -W"Things you get with -Wall"Things you get with -Weverything, i.e. *all* known warnings flags"Things you get with -Wcompat.This is intended to group together warnings that will be enabled by default at some point in the future, so that library authors eager to make their code future compatible to fix issues before they even generate warnings.""Things you get with -Wunused-binds!Getter for verbosity setting(Getter for the set of enabled dump flags!!!!!!!!!!!!!"""!!!!!!"!!!!!!!!!! !!!!!!!!!!! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                                   !!!!!! !!!!!!!!!!! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                                   !!!!!!!!!!!!!!!!!!""""!!!!!!!!!!!!!!!!!!!!" " " " "  "  """"!"#*""""""" "9;"="??"??"??"??%None29Pretty print a graph in a somewhat human readable format.Pretty print a graph in graphviz .dot format. Conflicts get solid edges. Coalescences get dashed edges.܅Nodes in the graph are doubly linked, but we only want one edge for each conflict if the graphviz graph. Traverse over the graph, but make sure to only print the edges for each node once.What graphviz color to use for each node color It's usually safe to return X11 style colors here, ie "red", "green" etc or a hex triplet #aaff55 etcNoneLookup a node from the graph.>Get a node from the graph, throwing an error if it's not there-Add a node to the graph, linking up its edges/Delete a node and all its edges from the graph.Modify a node in the graph. returns Nothing if the node isn't present.Get the size of the graph, O(n)Union two graphs together.Add a conflict between nodes to the graph, creating the nodes required. Conflicts are virtual regs which need to be colored differently.Delete a conflict edge. k1 -> k2 returns Nothing if the node isn't in the graphAdd some conflicts to the graph, creating nodes if required. All the nodes in the set are taken to conflict with each other.Add an exclusion to the graph, creating nodes if required. These are extra colors that the node cannot use.Add a coalescence edge to the graph, creating nodes if required. It is considered advantageous to assign the same color to nodes in a coalescence.4Delete a coalescence edge (k1 -> k2) from the graph.Add a color preference to the graph, creating nodes if required. The most recently added preference is the most preferred. The algorithm tries to assign a node it's preferred color if possible.Do aggressive coalescing on this graph. returns the new graph and the list of pairs of nodes that got coalesced together. for each pair, the resulting node will have the least key and be second in the pair.Coalesce this pair of nodes unconditionally / aggressively. The resulting node is the one with the least key.returns: Just the pair of keys if the nodes were coalesced the second element of the pair being the least one3Nothing if either of the nodes weren't in the graphFreeze a node This is for the iterative coalescer. By freezing a node we give up on ever coalescing it. Move all its coalesce edges into the frozen set - and update back edges from other nodes.Freeze one node in the graph This if for the iterative coalescer. Look for a move related node of low degree and freeze it.We probably don't need to scan the whole graph looking for the node of absolute lowest degree. Just sample the first few and choose the one with the lowest degree out of those. Also, we don't make any distinction between conflicts of different classes.. this is just a heuristic, after all.IDEA: freezing a node might free it up for Simplify.. would be good to check for triv right here, and add it to a worklist if known triv/non-move nodes.Freeze all the nodes in the graph for debugging the iterative allocator.7Find all the nodes in the graph that meet some criteriavalidate the internal structure of a graph all its edges should point to valid nodes If they don't then throw an error݅If this node is colored, check that all the nodes which conflict with it have different colors.Slurp out a map of how many nodes had a certain number of conflict neighboursSet the color of a certain nodeIf True, coalesce nodes even if this might make the graph less colorable (aggressive coalescing)If True, coalesce nodes even if this might make the graph less colorable (aggressive coalescing)!keys of the nodes to be coalescedkey of the node to freeze the graphgraph with that node frozen(extra debugging info to display on error-whether this graph is supposed to be colored.graph to validatevalidated graph݅True if this node is ok9(conflict neighbours, num nodes with that many conflicts)None) *Edge direction based on DFS Classification7Loop back towards the root node. Eg backjumps in loopsv -> v&Representation for nodes of the Graph.The payload1 is user data, just carried around in this moduleThe key is the node identifier. Key has an Ord instance for performance reasons.The [key] are the dependencies of the node; it's ok to have extra keys in the dependencies that are not the key of any Node in the graph#Dependencies/successors of the nodeUser defined node id User dataFind a reasonably short cycle a->b->c->a, in a graph The graph might not necessarily be strongly connected.1Given a list of roots return all reachable nodes.Efficiently construct a map which maps each key to it's set of transitive dependencies. Only works on acyclic input.Efficiently construct a map which maps each key to it's set of transitive dependencies. Less efficient than  allReachable$, but works on cyclic input as well.Given a start vertex, a way to get successors from a node and a list of (directed) edges classify the types of edges.&'  3 ? 4 #%&)*-.8NoneTry to color a graph with this set of colors. Uses Chaitin's algorithm to color the graph. The graph is scanned for nodes which are deamed 'trivially colorable'. These nodes are pushed onto a stack and removed from the graph. Once this process is complete the graph can be colored by removing nodes from the stack (ie in reverse order) and assigning them colors different to their neighbors.ޅScan through the conflict graph separating out trivially colorable and potentially uncolorable (problem) nodes.Checking whether a node is trivially colorable or not is a reasonably expensive operation, so after a triv node is found and removed from the graph it's no good to return to the start of the graph and recheck a bunch of nodes that will probably still be non-trivially colorable.To ward against this, during each pass through the graph we collect up a list of triv nodes that were found, and only remove them once we've finished the pass. The more nodes we can delete at once the more likely it is that nodes we've already checked will become trivially colorable for the next pass.TODO: add work lists to finding triv nodes is easier. If we've just scanned the graph, and removed triv nodes, then the only nodes that we need to rescan are the ones we've removed edges from.߅)Try to assign a color to all these nodes.Select a color for a certain node taking into account preferences, neighbors and exclusions. returns Nothing if no color can be assigned to this node."whether to do iterative coalescing6how many times we've tried to color this graph so far.>map of (node class -> set of colors available for this class).3fn to decide whether a node is trivially colorable.fn to choose a node to potentially leave uncolored if nothing is trivially colorable.the graph to color.ޅ"whether to do iterative coalescing2fn to decide whether a node is trivially colorablefn to choose a node to potentially leave uncolored if nothing is trivially colorable.the graph to scan߅>map of (node class -> set of colors available for this class). the graphnodes to assign a color to.+sNone 66       ; 1"$+-5"$*,5None` A "supernode" stands for a collection of one or more nodes (basic blocks) that have been coalesced by the Hecht-Ullman algorithm. A collection in a supernode constitutes a  reducible subgraph of a control-flow graph. (When an entire control-flow graph is collapsed to a single supernode, the flow graph is reducible.)The idea of node splitting is to collapse a control-flow graph down to a single supernode, then materialize (`inflate'<) the reducible equivalent graph from that supernode. The  class defines only the methods needed to collapse; rematerialization is the responsibility of the client.During the Hecht-Ullman algorithm, every supernode has a unique entry point, which is given by . But this invariant is not guaranteed by the class methods and is not a law of the class. The  function rewrites all labels that appear in a supernode (both definitions and uses). The * function replaces every appearance of a defined label with a fresh label. (Appearances include both definitions and uses.)Laws:  superLabel (n <> n') == superLabel n blocks (n <> n') == blocks n  blocks n' mapLabels f (n <> n') = mapLabels f n <> mapLabels f n' mapLabels id == id mapLabels (f . g) == mapLabels f . mapLabels g  (We expect  to distribute over , but because of the fresh names involved, formulating a precise law is a bit challenging.)The identity monad as a >. Use this monad when you want efficiency in graph collapse.Module : GHC.Data.Graph.Collapse Description : Implement the "collapsing" algorithm Hecht and UllmanA control-flow graph is reducible if and only if it is collapsible according to the definition of Hecht and Ullman (1972). This module implements the collapsing algorithm of Hecht and Ullman, and if it encounters a graph that is not collapsible, it splits nodes until the graph is fully collapsed. It then reports what nodes (if any) had to be split in order to collapse the graph. The information is used upstream to node-split Cmm graphs.The module uses the inductive graph representation cloned from the Functional Graph Library (Hackage package fgl , modules .)If you want to visualize the graph-collapsing algorithm, create an instance of monad . Each step in the algorithm is announced to the monad as a side effect. If you don't care about visualization, you would use the . monad, in which these operations are no-ops. Tell if a  has a single predecessor.1Use this function to extract information about a  that you know is in a  . It's like  from , but it must succeed."Rewrite the label of a given node.&Test if a graph has but a single node.Merge two nodes, return new graph plus list of nodes that newly have a single predecessor. This function implements transformation $T_2$ from the Hecht and Ullman paper (merge the node into its unique predecessor). It then also removes self-edges (transformation $T_1$ from the Hecht and Ullman paper). There is no need for a separate implementation of $T_1$.`consumeBy v u g` returns the graph that results when node v is consumed by node u in graph g. Both v and u are replaced with a new node u' with these properties:LABELS(u') = LABELS(u) " LABELS(v) SUCC(u') = SUCC(u)  SUCC(v) - { u } every node that previously points to u now points to u'It also returns a list of nodes in the result graph that are *newly* single-predecessor nodes.Split a given node. The node is replaced with a collection of replicas, one for each predecessor. After the split, every predecessor points to a unique replica.;Does a list have more than one element? (in constant time).Find a candidate for splitting by finding a node that has multiple predecessors.Using the algorithm of Hecht and Ullman (1972), collapse a graph into a single node, splitting nodes as needed. Record visualization events in monad m. & *£ ã!ģ#(ţ*8None +3ƣGraph' is abstracted over the block type, so that we can build graphs of annotated blocks for example (Compiler.Hoopl.Dataflow needs this).ʣA control-flow graph, which may take any of four shapes (O/O, OC, CO, C/C). A graph open at the entry has a single, distinguished, anonymous entry point; if a graph is closed at the entry, its entry point(s) are supplied by a context.ˣGives access to the anchor points for nonlocal edges as well as the edges themselvesBody abstracted over blockΣ5A (possibly empty) collection of closed/closed blocksӣMaps over all nodes in a graph.ԣ Function ԣ enables a change of representation of blocks, nodes, or both. It lifts a polymorphic block transform into a polymorphic graph transform. When the block representation stabilizes, a similar function should be provided for blocks.֣Returns a list of blocks reachable from the provided Labels in the reverse postorder.This is the most important traversal over this data structure. It drops unreachable code and puts blocks in an order that is good for solving forward dataflow problems quickly. The reverse order is good for solving backward dataflow problems quickly. The forward order is also reasonably good for emitting instructions, except that it will not usually exploit Forrest Baskett's trick of eliminating the unconditional branch from a loop. For that you would need a more serious analysis, probably based on dominators, to identify loop headers.For forward analyses we want reverse postorder visitation, consider: - A -> [B,C] B -> D C -> D  Postorder: [D, C, B, A] (or [D, B, C, A]) Reverse postorder: [A, B, C, D] (or [A, C, B, D]) This matters for, e.g., forward analysis, because we want to analyze *both* B and C before we analyze D.̣"The label of a first node or blockͣGives control-flow successorsңУѣϣգӣԣ֣Σʣƣɣǣȣˣ̣ͣΣʣƣɣǣȣˣ̣ͣңУѣϣգӣԣ֣ף) )*3NoneV Whether an ' argument may appear in source Haskell.the argument may not appear in source Haskell, it is only inferred.?the argument may appear in source Haskell, but isn't required. ForAllTyFlag3Is something required to appear in source Haskell (), permitted by request () (visible type application), or prohibited entirely from appearing in source Haskell ()? See Note [VarBndrs, ForAllTyBinders, TyConBinders, and visibility] in GHC.Core.TyCo.Rep Does this 1 classify an argument that is written in Haskell? Does this 5 classify an argument that is not written in Haskell?,The ForAllTyFlag on a (Lam a e) term, where a is a type variable. If you want other ForAllTyFlag, use a cast. See Note [Required foralls in Core] in GHC.Core.TyCo.Rep  % %%%%%zNone"0 0"- -"! !" " !None %Specify whether to default kind variables, and type variables of kind  RuntimeRep% Multiplicity.%Default kind variables:default kind variables of kind Type to Type,default  RuntimeRep% Multiplicity kind variables to  LiftedRep%Many, respectively.When this strategy is used, it means that we have determined that the variables we are considering defaulting are all kind variables.;Usually, we pass this option when -XNoPolyKinds is enabled.%=Default (or don't default) non-standard variables, of kinds  RuntimeRep, % and  Multiplicity.%2Specify whether to default type variables of kind  RuntimeRep% Multiplicity.%*Default type variables of the given kinds:default  RuntimeRep variables to  LiftedRepdefault % variables to %default  Multiplicity variables to Many%/Try not to default type variables of the kinds  RuntimeRep% Multiplicity.Note that these might get defaulted anyway, if they are kind variables and `-XNoPolyKinds` is enabled.%Whether something is a type or a data declaration, e.g. a type family or a data family.%Paints a picture of what a  represents, in broad strokes. This is used towards more informative error messages.% e.g., the (->) .%Flag to see whether we're type-checking terms or kind-checking types%An integer or infinity%Inline Specification%Rule Match Information% Phase Number%Default Method Specification& Inside Lambda&Occurs inside a non-linear lambda Substituting a redex for this occurrence is dangerous because it might duplicate work.&Interesting Context&Function: is applied Data value: scrutinised by a case with at least one non-DEFAULT branch&!identifier Occurrence Information&2There are many occurrences, or unknown occurrences&Marks unused variables. Sometimes useful for lambda and case-bound variables.&3Occurs exactly once (per branch), not inside a rule&This identifier breaks a loop of mutually recursive functions. The field marks whether it is only a loop breaker due to a reference in a rule&Embedding Projection pair&7Are we dealing with an unboxed tuple or an unboxed sum?!Used when validity checking, see check_ubx_tuple_or_sum.&2A general-purpose pretty-printing precedence type.&'This instance must not overlap another &- instance. However, it may be overlapped by & instances, and it may overlap & instances.&Silently ignore this instance if you find a more specific one that matches the constraint you are trying to resolveExample: constraint (Foo [Int]) instance Foo [Int] instance {-# OVERLAPPABLE #-} Foo [a]Since the second instance has the Overlappable flag, the first instance will be chosen (otherwise its ambiguous which to choose)&Silently ignore any more general instances that may be used to solve the constraint.Example: constraint (Foo [Int]) instance {-# OVERLAPPING #-} Foo [Int] instance Foo [a]Since the first instance has the Overlapping flag, the second---more general---instance will be ignored (otherwise it is ambiguous which to choose)&Equivalent to having both & and & flags.&Behave like Overlappable and Overlapping, and in addition pick an arbitrary one if there are multiple matching candidates, and don't worry about later instantiationExample: constraint (Foo [b]) instance {-# INCOHERENT -} Foo [Int] instance Foo [a] Without the Incoherent flag, we'd complain that instantiating b would change which instance was chosen. See also Note [Incoherent instances] in GHC.Core.InstEnv&Behave like Incoherent, but the instance choice is observable by the program behaviour. See Note [Coherence and specialisation: overview].We don't have surface syntax for the distinction between Incoherent and NonCanonical instances; instead, the flag `-f{no-}specialise-incoherents` (on by default) controls whether  INCOHERENT7 instances are regarded as Incoherent or NonCanonical.&The semantics allowed for overlapping instances for a particular instance. See Note [Safe Haskell isSafeOverlap] in GHC.Core.InstEnv for a explanation of the & field.&6Whether to run pattern-match checks in generated code.5See Note [Generated code and pattern-match checking].&This metadata stores the information as to why was the piece of code generated It is useful for generating the right error context See Part 3 in Note [Expanding HsDo with XXExprGhcRn] in &Was this piece of code user-written or generated by the compiler?5See Note [Generated code and pattern-match checking].&Recursivity Flag&4Should an argument be passed evaluated *and* tagged.&If the Id is a lambda-bound variable then it may have lambda-bound variable info. Sometimes we know whether the lambda binding this variable is a "one-shot" lambda; that is, whether it is applied at most once.This information may be useful in optimisation, as computations may safely be floated inside such a lambda without risk of duplicating work.+See also Note [OneShotInfo overview] above.&No information&#The lambda is applied at most once.&A power-of-two alignment& A *zero-indexed* constructor tag&FullArgCount is the number of type or value arguments in an application, or the number of type or value binders in a lambda. Note: it includes both type and value arguments!&The number of arguments that a join point takes. Unlike the arity of a function, this is a purely syntactic property and is fixed when the join point is created (or converted from a value). Both type and value arguments are counted.&Representation ArityThe number of represented arguments that can be applied to a value before it does "real work". So: fib 100 has representation arity 0 x -> fib x has representation arity 1 (# x, y #) -> fib (x + y) has representation arity 2&Syntactic (visibility) arity, i.e. the number of visible arguments. See Note [Visibility and arity]&The number of value arguments that can be applied to a value before it does "real work". So: fib 100 has arity 0 x -> fib x has arity 1 See also Note [Definition of arity] in GHC.Core.Opt.Arity&Tags are allocated from here for real constructors or for superclass selectors&$It is always safe to assume that an Id) has no lambda-bound variable information& Does this & require us to run pattern-match checking, or should we skip these checks?5See Note [Generated code and pattern-match checking].&=Pretty print an alternative in an unboxed sum e.g. "| a | |".'0Outputs string for pragma name for any of INLINE INLINABLENOINLINE. This differs from the Outputable instance for the InlineSpec type where the pragma name string as well as the accompanying SourceText (if any) is printed.'3Pretty-print without displaying the user-specified %.'*Pretty-print including the user-specified %.'A representation of infinityAdd two %s Multiply two %s' Subtract an  from an %'Turn a positive number into an %, where 0 represents infinity'Inject any integer into an %'Get the enclosing class TyCon (if there is one) for the given TyConFlavour'If there is any  interesting identifier occurrence, then the aggregated occurrence info of that identifier is considered interesting.'If any occurrence of an identifier is inside a lambda, then the occurrence info of that identifier marks it as occurring inside a lambda&#The pretty printing function to useThe things to be pretty printedAlternative (one-based)Arity where the alternative havs been pretty printed and finally packed into a paragraph.''''&''&'&&&''''&&&'&&&&&&&'''''''''''''''''&'&''''&''&&&'&'&''''&&'''&&''&'''&&'&&&&&&''&&'''&&&''''&'&'&&'&&'&'' %%%%%%%&&&&&&&%%%%&%%%%%%&&&&&&&&&&&&&&%%%%%%%%%%%%%&&&%&&&&&&&%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&%&&&&&&%%%&%%%&&&%%%&&&&&&&%%%%%%%%%%%%%%%%%%%%%&&&%%%%%& %%%&&&& &&&&&&&&&&&%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'''''''&''&&&&&&&&%%%'''&&&&%%%&&&&&&&&%%%%%'''%%%%%%''''''''%%%''%%%%%%'%%%%%%%''''''''''''''''''''''%%%%%''''%%%'''%'''''%%%''%%%''%%%%%%%%%%%%%%%%%%'%%%%%%'' ' ' ' "' '  ' #' '  ' ' ' #' !' ' ' ' ' ' ' ' '  ' '  ' ' ' &' ' '' ' "' !' ' %' ' ' "' ' ' ' "' ' ' ' !' $'  ' ' ' ' ' ' ' ' /' &' 2' '' ''' (( ((( (((( ( (  (  ( (  (  (  ( " &( ( ,( (  ( ( ( ( ( ( ( ((()+(-0(26((( ((((((("(( (( (((( ( (((( $(&)Nonec+Test if the given Integer is representable with a platform Int+?Test if the given Integer is representable with a platform Word+For some architectures the C calling convention is that any integer shorter than 64 bits is replaced by its 64 bits representation using sign or zero extension.+&Does this platform have an RTS linker?+Try to locate "DerivedConstants.h" file in the given dirs and to parse the PlatformConstants from it.See Note [Platform constants]+++++++++++++++++++++++****+++++++++++++++++++++++++++++++++efg*******************************++++++++++++++++++++++++++++++++++++++++++********************+++++++++++++++++*******+++****+++efg+****++++++++++++++++++++++++++++++++++++ + + ++++++++!+ +NoneŨGenerate a section type (e.g.  @progbits). See #13937.ŨTarget platform section typepretty assembler fragmentŨŨNoneISettings for what GHC this is.IPaths to various files and directories used by GHC, including those that provide more settings.I)Settings for other executables GHC calls.Probably should further split down by phase, or split between platform-specific and platform-agnostic.I iserv optionsILLVM: llc static compilerILLVM: llvm optimiserIcached Fingerprint of sOpt_CmmP See Note [Repeated -optP hashing]Icached Fingerprint of sOpt_JSP See Note [Repeated -optP hashing]I?cached Fingerprint of sOpt_P See Note [Repeated -optP hashing]ILLVM: assemblerILLVM: llc static compilerILLVM: opt llvm optimiserIN.B. On Windows we don't have a linker which supports object merging, hence the @ . See Note [Object merging] in GHC.Driver.Pipeline.Execute for details.I>The C preprocessor (distinct from the Haskell C preprocessor!)I?The C-- C Preprocessor and default options (not added by -optP)IThe JavaScript C preprocessor and default options (not added by -optP)IThe Haskell C preprocessor and default options (not added by -optP)IDynamic library suffixIIIIIJIIIIIJIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJIII+++++++++++++++++++++IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII+++++++++++++++++++++IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJNone Just like ", but it is not exposed from base.ɨ TopDir path&Settings filepath (for error messages)Raw settings file contentsɨƨȨǨƨȨǨɨNonevFA way4Don't change the constructor order as it is used by F to create a unique tag (e.g. thr_debug_p) which is expected by other tools (e.g. Cabal).F,for GHC API clients building custom variantsF'(RTS only) Multithreaded runtime systemF1Debugging, enable trace messages and extra checksF:Profiling, enable cost-centre stacks and profiling reportsFDynamic linkingFTest if a way is enabledFTest if a way is not enabledF Add a wayF Remove a wayF)Check if a combination of ways is allowedF'Unique tag associated to a list of waysF-Unique build-tag associated to a list of waysRTS only ways are filtered out because they have no impact on the build.F$Unique build-tag associated to a wayFReturn true for ways that only impact the RTS, not the generated codeF.Filter ways that have an impact on compilationFFilter RTS-only ways (ways that don't have an impact on compilation)F*Turn these flags on when enabling this wayF+Turn these flags off when enabling this wayF;Pass these options to the C compiler when enabling this wayF3Pass these options to linker when enabling this wayF=Pass these options to the preprocessor when enabling this wayFConsult the RTS to find whether it has been built with profiling enabled.FConsult the RTS to find whether GHC itself has been built with dynamic linking. This can't be statically known at compile-time, because we build both the static and dynamic versions together with -dynamic-too.F/Consult the RTS to find whether it is threaded.F/Consult the RTS to find whether it is debugged.F.Consult the RTS to find whether it is tracing.F Host ways.FHost "full" ways (i.e. ways that have an impact on the compilation, not RTS only ways).These ways must be used when compiling codes targeting the internal interpreter. FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF FFF None&' JInformation about an installed unit (units are identified by their internal UnitId)JInformation about an installed unit (units are identified by their database UnitKey)J#Information about an installed unitWe parameterize on the unit identifier: * UnitKey: identifier used in the database (cf J5) * UnitId: identifier used to generate code (cf J)These two identifiers are different for wired-in packages. See Note [About units] in GHC.UnitJ9Convert a DbUnitInfo (read from a package database) into JJMap over the unit parameterJMake a  from a J If the unit is definite, make a " from  field."If the unit is indefinite, make a " from  and 8 fields. Note that in this case we don't keep track of . It can be retrieved later with "improvement", i.e. matching on `unitInstanceOf/unitInstantiations` fields (see Note [About units] in GHC.Unit).J$Create a UnitPprInfo from a UnitInfoJ3Find all the include directories in the given unitsJ2Find all the C-compiler options in the given unitsJFind all the library directories in the given units for the given waysJ*Find all the frameworks in the given unitsJFind all the package framework paths in these and the preload packages Either the  or  as appropriate for the way.:JJJJJJJJJJJJJJJJJJJJJ"":JJ""JJJJJJJJJJJJJJJJJJJJ J J J JJ9;NonejFA platform profile fully describes the kind of objects that are generated for a platform.+ doesn't fully describe the ABI of an object. Compiler ways (profiling, debug, dynamic) also modify the ABI.FWaysFPlatformFGet platform constantsFIs profiling enabledFWord size in bytesF Unique build tag for the profileFFFFFFFFFFFFFFFFF FFF None ̨Lambda lift even when this turns a known call into an unknown call.ͨMaximum number of arguments after lambda lifting non-recursive function.ΨMaximum number of arguments after lambda lifting a recursive function.ʨ˨̨ͨΨϨʨ˨̨ͨΨϨШ ѨҨӨ Nonea8An ArgDescr describes the argument pattern of a functionaWe represent liveness bitmaps as a Bitmap (whose internal representation really is a bitmap). These are pinned onto case return vectors to indicate the state of the stack for the garbage collector.In the compiled program, liveness bitmaps that fit inside a single word (StgWord) are stored as a single word, while larger bitmaps are stored as a pointer to an array of words.aTrue <=> This is a static closure. Affects how we garbage-collect it. Static closure have an extra static link field at the end. Constructors do not have a static variant; see Note [static constructors]aA description of the layout of a closure. Corresponds directly to the closure types in includes/rts/storage/ClosureTypes.h.aWord offset, or word countaByte offset, or byte countaRound up the given byte count to the next byte count that's a multiple of the machine's word size.a Round up base to a multiple of size.a7Convert the given number of words to a number of bytes.This function morally has type WordOff -> ByteOff , but uses Num a to allow for overloading.aFirst round the given byte count up to a multiple of the machine's word size and then convert the result to words.aHalf word size in bytesaSize of a closure header (StgHeader in includes/rts/storage/Closures.h)aSize of the profiling part of a closure header (StgProfHeader in includes/rts/storage/Closures.h)The garbage collector requires that every closure is at least as big as this.a(The total size of the closure, in words.aThe byte offset into the card table of the card for a given elementa>Convert a number of elements to a number of cards, rounding upa"The size of a card table, in bytesa"The size of a card table, in wordsa%Derives the RTS closure type from an aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa a  a a $a a aa aa aaaaNoneUԨ*Compute the output file name of a program.StaticLink boolean is used to indicate if the program is actually a static library (e.g., on iOS).Use the provided filename (if any), otherwise use "main.exe" (Windows), "a.out (otherwise without StaticLink set), "liba.a". In every case, add the extension if it is missing.ԨԨNoneAJUntyped Phase descriptionJ -EJ -CJ -SJ -cJWhen we are given files (modified by -x arguments) we need to determine if they are Haskellish or not to figure out how we should try to compile it. The rules are: If no -x flag was specified, we check to see if the file looks like a module name, has no extension, or has a Haskell source extension.If an -x flag was specified, we just make sure the specified suffix is a Haskell one.JForeign language of the phase if the phase deals with a foreign code1JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ1JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ J JNoneը&A bitmap represented by a sequence of a s on the target architecture. These are used for bitmaps in info tables and other generated code which need to be emitted as sequences of StgWords.֨%Make a bitmap from a sequence of bitsר0Make a bitmap where the slots specified are the zeros in the bitmap. eg. [0,1,3], size 4 ==> 0x4 (we leave any bits outside the size as zero, just to make the bitmap easier to read). The list of Ints must& be already sorted and duplicate-free.بMagic number, must agree with BITMAP_BITS_SHIFT in InfoTables.h. Some kinds of bitmap pack a size/bitmap into a single word if possible, or fall back to an external pointer when the bitmap is too large. This value represents the largest size of bitmap that can be packed into a single word.ר size in bits*sorted indices of zeros free of duplicatesרب֨ըը֨רبNoneE Rule optionsEEnable rules for bignumsECut down precision of Rational values to that of Float/Double if disabledE-Enable more advanced numeric constant foldingETarget platformEEEEEEEEEEEENone ٨!Read in assembly file and process4These are the rewrites that the mangler will performRewrite a line of assembly source with the given rewrites, taking the first rewrite that applies.This rewrites .type$ annotations of function symbols to %object+. This is done as the linker can relocate  %functions through the Procedure Linking Table (PLT). This is bad since we expect that the info table will appear directly before the symbol's location. In the case that the PLT is used, this will be not an info table but instead some random PLT garbage.This rewrites aligned AVX instructions to their unaligned counterparts on x86-64. This is necessary because the stack is not adequately aligned for aligned AVX spills, so LLVM would emit code that adjusts the stack pointer and disable tail call optimization. Both would be catastrophic here so GHC tells LLVM that the stack is 32-byte aligned (even though it isn't) and then rewrites the instructions in the mangler.This rewrites (tail) calls to avoid creating PLT entries for functions on riscv64. The replacement will load the address from the GOT, which is resolved to point to the real address of the function.This rewrites bl and b jump inst to avoid creating PLT entries for functions on loongarch64, because there is no separate call instruction for function calls in loongarch64. Also, this replacement will load the function address from the GOT, which is resolved to point to the real address of the function.replaceOnce match replace bs1 replaces the first occurrence of the substring match in bs with replace.This function splits a line of assembly code into the label and the rest of the code.٨٨None] =Supported LLVM configurations. see Note [LLVM configuration]target triple passed to LLVM&True ==> warn unsupported Llvm versionversion of Llvm we're using(x86) BMI instructionsSplit sections+Fill undefined literals with garbage values Context for LLVM code generationTarget platformڨۨܨݨިߨڨۨܨݨިߨNone3Cache LLVM configuration read from files in top_dir5See Note [LLVM configuration] in GHC.CmmToLlvm.ConfigCurrently implemented with unsafe lazy IO. But it could be implemented with an IORef as the exposed interface is in IO.None Eis -falignment-sanitisation enabled?EA weaker notion of equality of Es than E, used (only) in Cmm Lint.Why "weaker"? Because:we don't distinguish GcPtr vs NonGcPtr, because the the RTS files are not yet well-typed wrt pointers,for vectors, we only compare the widths, because in practice things like X86 xmm registers support different types of data (e.g. 4xf32, 2xf64, 2xu64 etc).E.The width of the current platform's word size.E3The width of the current platform's half-word size.E7A bit-mask for the lower half-word of current platform.EA width in bits.EA width in bytes. %widthFromBytes (widthInBytes w) === wE*Partial* A width from the number of bytes.E:log_2 of the width in bytes, useful for generating shifts.ENarrow a signed or unsigned value to the given width. The result will reside in  [0, +2^width). narrowU W8 256 == 256narrowU W8 255 == 255narrowU W8 128 == 128narrowU W8 127 == 127narrowU W8 0 == 0narrowU W8 (-127) == 129narrowU W8 (-128) == 128narrowU W8 (-129) == 127narrowU W8 (-255) == 1narrowU W8 (-256) == 0ENarrow a signed value to the given width. The result will reside in [-2^(width-1), +2^(width-1)). narrowS W8 256 == 0narrowS W8 255 == -1narrowS W8 128 == -128narrowS W8 127 == 127narrowS W8 0 == 0narrowS W8 (-127) == -127narrowS W8 (-128) == -128narrowS W8 (-129) == 127narrowS W8 (-255) == 1narrowS W8 (-256) == 0EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE E E E E  E E9 9EEE EFNone#Native code generator configuration+Whether to enable the dead-code eliminationCompute block unwinding tablesEnable shortcutting (don't jump to blocks only containing a jump)%Enable static control-flow prediction$Enable GHC-specific source note DIEs0Expose symbol table entries for internal symbols0Strip out block information from generated DwarfEnable unwindingsEnable Dwarf generation+Layout based on last instruction per block.$Use CFG based block layout algorithmCFG edge weights(x86) BMI instructions(x86) SSE instructionsPerform CMM constant foldingPerform ASM linting passSplit sections Ditto for memset If inlining memcpy produces less than this threshold (in pseudo-instruction unit), do it Enable Position-Independent Code/Generate code to link against dynamic librariesMandatory proc alignment1The name of the module we are currently compilingContext for ASM code generationTarget platformReturn Word size=Size in bytes of the pre-allocated spill space on the C stackReturn Word size&&None F+Global registers used for argument passing.0See Note [realArgRegsCover] in GHC.Cmm.CallConv.F5General-purpose (integer) argument-passing registers.F=Scalar (integer & floating-point) argument-passing registers.F16 byte vector argument-passing registers, together with integer & floating-point argument-passing scalar registers.F32 byte vector argument-passing registers, together with integer & floating-point argument-passing scalar registers.F64 byte vector argument-passing registers, together with integer & floating-point argument-passing scalar registers.F0An abstract global register for the STG machine. See also F, which denotes a usage of a register at a particular type (e.g. using a 32-bit wide register to store an 8-bit wide value), as per Note [GlobalReg vs GlobalRegUse].F2Stack ptr; points to last occupied stack location.F Stack limitF0Heap ptr; points to last occupied heap location.FHeap limit registerFCurrent cost-centre stackFpointer to current thread's TSOFpointer to allocation areaF'allocation count for heap check failureF#address of stg_EAGER_BLACKHOLE_infoFaddress of stg_gc_enter_1Faddress of stg_gc_funFBase offset for the register table, used for accessing registers which do not have real registers assigned to them. This register will only appear after we have expanded GlobalReg into memory accesses (where necessary) in the native code generator.FThe register used by the platform for the C stack pointer. This is a break in the STG abstraction used exclusively to setup stack unwinding information.FA dummy register used to indicate to the stack unwinder where a routine would return to.F?Base Register for PIC (position-independent code) calculations.Only used inside the native code generator. Its exact meaning differs from platform to platform (see module PositionIndependentCode).F'Parameters: 1. Identifier 2. TypeF0A use of a global register at a particular type.While a F5 identifies a global register in the STG machine, a F also contains information about the type we are storing in the register.:See Note [GlobalReg vs GlobalRegUse] for more information.FThe E at which we are using the F.-Its width must be less than the width of the F: ;typeWidth ty <= typeWidth (globalRegSpillType platform reg)FThe underlying F8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF F F F F #F F F F !F FFFFFFF F FFF None F$The operation to perform atomically.GC11 memory ordering semantics.Grelaxed orderingGacquire orderingGrelease orderingGsequentially consistentG(Atomic read-modify-write. Arguments are  [dest, n].GAtomic read. Arguments are [addr].GAtomic write. Arguments are  [addr, value].G'Atomic compare-and-swap. Arguments are [dest, expected, new]. Sequentially consistent. Possible future refactoring: should this be anG variant?GAtomic swap. Arguments are  [dest, new]G8Where are the signs in a fused multiply-add instruction?x*y + z vs x*y - z vs -x*y+z vs -x*y-z.Warning: the signs aren't consistent across architectures (X86, PowerPC, AArch64). The user-facing implementation uses the X86 convention, while the relevant backends use their corresponding conventions.GFused multiply-add x*y + z.G!Fused multiply-subtract. On X86: x*y - z.GFused multiply-add. On X86: -x*y + z.G!Fused multiply-subtract. On X86: -x*y - z.GMachine-level primops; ones which we can reasonably delegate to the native code generators to handle.)Most operations are parameterised by the E that they operate on. Some operations have separate signed and unsigned versions, and float and integer versions.Note that there are variety of places in the native code generator where we assume that the code produced for a MachOp does not introduce new blocks.HFused multiply-add, see G.HAn atomic read with no memory ordering. Address msut be naturally aligned.HReturns M if the MachOp has commutable arguments. This is used in the platform-independent Cmm optimisations.If in doubt, return J. This generates worse code on the native routes, but is otherwise harmless.HReturns M$ if the MachOp is associative (i.e. (x+y)+z == x+(y+z)=) This is used in the platform-independent Cmm optimisations.If in doubt, return J. This generates worse code on the native routes, but is otherwise harmless.HReturns M if the MachOp is a comparison.If in doubt, return False. This generates worse code on the native routes, but is otherwise harmless.HReturns Just w6 if the operation is an integer comparison with width w, or Nothing otherwise.H.Returns the MachRep of the result of a MachOp.HThis function is used for debugging only: we can check whether an application of a MachOp is "type-correct" by checking that the MachReps of its arguments are the same as the MachOp expects. This is used when linting a CmmExpr.H!Return (results_hints,args_hints)HThe alignment of a memcpy-ish operation.HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHGHHHHHHHHHHHHHHHHHGGHHHHHHHHHGGGGHHGHHHHHGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHGGGGGGGHHGHHHHHHHHHHHHHHHHHGGHHHHHHHHHGGGGHHGHHHHHGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHGGGGGFFGGGGGGGGGGH H HHHH HII II INone  None> $Should we optimize constant divisorsDoes this platform support mul2#Should Cmm split proc points or not1Should the Cmm pass replace Stg switch statements/Generate code to link against dynamic libraries5Generate stack unwinding instructions (for debugging).Instrument memory accesses for ThreadSanitizer&Perform sink after stack layout or notEliminate common blocks or not"Do Cmm Linting Optimization or not Optimize Cmm Control Flow or notTarget Profile retrieve the target Cmm platformNone4EForeign export stubsEWe don't have any stubsE!There are some stubs. Parameters:?1) Header file prototypes for "foreign exported" functions2) C stubs to use when calling "foreign exported" functionsE Finalizers to be run at shutdownEInitializers to be run at startup See Note [Initializers and finalizers in Cmm] in GHC.Cmm.InitFini.E!initializerCStub fn_nm decls body is a E: containing C initializer function (e.g. an entry of the  .init_array section) named fn_nm7 with the given body and the given set of declarations.EfinalizerCStub fn_nm decls body is a E8 containing C finalizer function (e.g. an entry of the  .fini_array section) named fn_nm7 with the given body and the given set of declarations.EEEEEEEEEEEEEEEEEEEEEEEEEEEEE& &E# #E E None(Get the  associated with a known-key .)This function is an inverse of ()This function is an inverse of mkTupleTyDataUnique1 that also matches the worker and promoted tycon.%)(()())))(()(()())((((((((((((((())()%((()(())(()((((((((((()))))))(((((())7None#.Other names in the compiler add additional information to an OccName. This class provides a consistent way to access the underlying OccName. Occurrence NameIn this context that means: "classified (i.e. as a type name, value name, etc) but not qualified and not yet resolved")A map keyed on . See Note [OccEnv].9Variable name space (including "real" data constructors).,Record field namespace for the given record.Source data constructor namespace.Type variable namespace.%Type constructor and class namespace.,The textual name of the parent of the field.For a field of a datatype, this is the name of the first constructor of the datatype (regardless of whether this constructor has this field).For a field of a pattern synonym, this is the name of the pattern synonym.)0Is this a term variable or field name namespace?).Mangle field names to avoid duplicate symbols.See Note [Mangling OccNames].) The empty ).) A singleton ).)Add a single element to an ).) Extend an ) by a list.(s later on in the list override earlier s.)Look an element up in an ).)Lookup an element in an ) , ignoring ) s entirely.)Lookup an element in an )8, looking in the record field namespace for a variable.)8Look up all the record fields that match with the given   in an ).) Create an ) from a list.(s later on in the list override earlier s.) Create an )8 from a list, combining different values with the same  using the combining function.)4Compute whether there is a value keyed by the given .) Fold over an ). Non-deterministic, unless the folding function is commutative (i.e. a1 f ( a2 f b ) == a2 f ( a1 f b ) for all a1, a2, b).)Obtain the elements of an ).)The resulting order is non-deterministic.) Union of two )s, right-biased.) Union of two )s with a combining function.) Map over an ) (* instance).*mapMaybe for b ).*Add a single element to an )*, using a different function whether the  already exists or not.*Delete one element from an ).*!Delete multiple elements from an ).*Filter out all elements in an ) using a predicate.* Alter an )1, adding or removing an element at the given key.*Remove elements of the first ) that appear in the second ).*9Alters (replaces or removes) those elements of the first )# that are mentioned in the second ). Same idea as .* Map over an ) strictly.* Force an ) with the provided function.*Value OccNamess are those that are either in the variable, field name or data constructor namespaces* Test if the 8 is a data constructor that starts with a symbol (e.g. :, or [])* Test if the  is that for any operator (whether it is a data constructor or variable or whatever)*Wrap parens around an operator*Haskell 98 encourages compilers to suppress warnings about unused names in a pattern if they start with _: this implements that test Build an  derived from another .4Note that the pieces of the name are passed in as a  [FastString]: so that the whole name can be constructed with a single  3, minimizing unnecessary intermediate allocations.*Test for definitions internally generated by GHC. This predicate is used to suppress printing of internal definitions in some debug prints*Is an  one of a Typeable TyCon or Module binding? This is needed as these bindings are renamed differently. See Note [Grand plan for Typeable] in GHC.Tc.Instance.Typeable.* new -> result*add to existing new elementoldnewA prefix which distinguishes one sort of derived name from anotherThe name we are deriving from in pieces which will be concatenated.*Index of superclass, e.g. 3 Class, e.g. OrdDerived Occname, e.g. $p3Ord*Unique to combine with the Local name, e.g. satNice unique version, e.g. $L23sat*Family name, e.g. Mapavoid these Occs R:Map*3Typically the class and type glommed together e.g. OrdMaybe-. Only used in debug mode, for extra clarity Is this a hs-boot instance DFun?avoid these OccsE.g.  $f3OrdMaybe**))***)))*)**))***)*****)*****)**)*))***)*)*))))**)******))*****))***************))))*))*****))*)))*)))**))*)))*)))*)**))**)**)*)))))))))))))))))))))))))))))))))))**)))))********************************)*)************))))))))))))**))))))))))))***********)***********)******* * * * * *  * * * * * * * '* /* * ?None &'*A class allowing convenient access to the  of various datatypesA unique, unambiguous name for something, containing information about where that thing originated.+!BuiltInSyntax is for things like (:), [] and tuples, which have special syntactic forms. They aren't in scope as such.Definition siteNOTE: we make the n_loc field strict to eliminate some potential (and real!) space leaks, due to the fact that we don't look at the SrcLoc in a Name all that often. Its unique.Its occurrence name.NOTE: kept lazy to allow known names to be known constructor applications and to inline better. See Note [Fast comparison for built-in Names]What sort of name it is+This matches a datacon as well as its worker and promoted tycon.+ Will the ( come from a dynamically linked package?+Returns True if the name is (a) Internal (b) External but from the specified module (c) External but from the  interactive packageThe key idea is that False means: the entity is defined in some other module you can find the details (type, fixity, instances) in some interface file those details will be stored in the EPT or HPTTrue means: the entity is defined in this module or earlier in the GHCi session you can find details (type, fixity, instances) in the TcGblEnv or TcLclEnvThe isInteractiveModule part is because successive interactions of a GHCi session each give rise to a fresh module (Ghci1, Ghci2, etc), but they all come from the magic  interactive package; and all the details are kept in the TcLclEnv, TcGblEnv, NOT in the HPT or EPT. See Note [The interactive package] in GHC.Runtime.Context+1Returns True if the name is external or from the  interactive package See documentation of + function+Returns True if the Name comes from some other package: neither this package nor the interactive package.+Create a name which is (for now at least) local to the current module and hence does not need a  to disambiguate it from other s+=Create a name which definitely originates in the given module,>Create a name which is actually defined by the compiler itself,0Create a name brought into being by the compiler,Make a name for a foreign call, Make the ? into an internal name, regardless of what it was to begin with,Compare Names lexicographically This only works for Names that originate in the source code or have been tidied.,Print fully qualified name (with unit-id and module, but no unique),Print a ticky ticky styled nameModule argument is the module to use for internal and system names. When printing the name in a ticky profile, the module name is included even for local things. However, ticky uses the format "x (M)" rather than "M.x". Hence, this function provides a separation from normal styling.,0Print the string of Name unqualifiedly directly.,!Get a string representation of a  that's unique and stable across recompilations. Used for deterministic generation of binds for derived instances. eg. "$aeson_70dylHtv1FFGeai1IoxcQr$Data.Aeson.Types.Internal$String",Assumes that the  is a non-binding one. See  and  for serializing binding s. See UserData) for the rationale for this distinction.,Caution#: This instance is implemented via , which means that the ordering is not stable across deserialization or rebuilds.See  for further information, and #15240 for a bug caused by improper use of this instance.,The same comments as for 's , instance apply.,,,,++++++++++++++++,+++,+,,,,,+++++++++++,,,,,,,,,,,,+**))***)))*)**))***)*****)*****)**)*))***)*)*))))**)******))*****))***************))))*))*****))*)))*)))**))*)))*)))*)**))**)**)*))+++))))))+++,,+++,,,+,+++,,+,++,,,,++++++++++++++++++++++,,,,,,,,,,, , , , , , , , , , , , , 0, None ,Ids which have no CAF references. This is a result of analysis of C--. It is always safe to use an empty ,. TODO Refer to Note., A number of ,s in dependency order: earlier , scope over later , In a single (def, use) pair, the defs also scope over the uses,(Just ds, us) => The use of any member of the ds, implies that all the us+ are used too. Also, us may mention ds. Nothing => Nothing is defined in this group, but nevertheless all the uses are essential. Used for instance declarations, for example,&A set of names that are used somewhere,)A set of names that are defined somewhere,,True if there is a non-empty intersection. s1 , s2 doesn't compute s2 if s1 is empty,Get the elements of a NameSet with some stable ordering. This only works for Names that originate in the source code or have been tidied. See Note [Deterministic UniqFM] to learn about nondeterminism, Just like ,, but , are not eliminated from the , returned, Collect all ,>, regardless of whether the group is itself used, but remove , on the way, Given some , and some ,, find all the uses, transitively. The result is a superset of the input ,,; and includes things defined in the input , (but only if they are used)/,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,/,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,None,Deterministic Name Environment#See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM' for explanation why we need DNameEnv.,Name Environment0,,,,,,,,,,-,,--,,,,,,,,-,,,,,,,,,,,,--,,,,,,,,,,0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,------,@NoneG/*Type variable that might be a metavariableType or Coercion Variable IdentifierType or kind VariableVariableEssentially a typed ?, that may also contain some additional information about the  and its use sites.The non-dependent version of . See Note [FunTyFlag] Appears here partly so that it's together with its friends ForAllTyFlag and ForallVisFlag, but also because it is used in IfaceType, rather early in the compilation chain-- is like -, but there can only be  in the - field.-A - represents an argument to a function. PiTyBinders can be dependent (-) or nondependent (-;). They may also be visible or not. See Note [PiTyBinders]-Variable BinderA - is the binder of a ForAllTy It's convenient to define this synonym here rather its natural home in GHC.Core.TyCo.Rep/, because it's used in GHC.Core.DataCon.hs-bootA - is a binder with only TyVar-,Not exported: may be discarded as dead code.-Exported: kept aliveIdentifier Scope-The type or kind of the  in questionKey for fast comparison Identical to the Unique in the name, cached here for speed-Equality Variable-Implicit parameter Identifier-Dictionary Identifier-Dictionary Function Identifier-Evidence Variable-Evidence Identifier- Kind Variable- Type Variable-Type or Kind Variable-Coercion Variable-Compare Vars by their Uniques. This is what Ord Var does, provided here to make it explicit at the call-site that it can introduce non-determinism. See Note [Unique Determinism]- Update a s type. Does not update the  multiplicity stored in an , if any. Because of the possibility for abuse, ASSERTs that there is no multiplicity to update.- Update a (s type monadically. Does not update the  multiplicity stored in an , if any. Because of the possibility for abuse, ASSERTs that there is no multiplicity to update.-Make a named binder-Make a named binder var should be a type variable-Make many named binders- . v == not (. v)..Is this a term variable ( ) that is not! a coercion variable? Satisfies . v ==> . v == not (. v)... returns True% for type variables as well as local s These are the variables that we need to pay attention to when finding free variables, or doing dependency analysis... returns True of s and s that must have a binding in this module. The converse is not quite right: there are some global s that must have bindings, such as record selectors. But that doesn't matter, because it's only used for assertions.isExportedIdVar means "don't throw this away"---------------..-..---...-..-..------------------.-----.---------------------------%%%---------------------------------------------------------------------------------.---............----------------%%%---------------------------------------------------. . . . . . . . . . 7. <. >. ?. . . ... ..None.+Deterministic Type or Coercion Variable Set.#Deterministic Coercion Variable Set.Deterministic Type Variable Set.Deterministic Identifier Set.Deterministic Variable Set.Type or Coercion Variable Set.Coercion Variable Set.Type Variable Set.Identifier Set. A non-deterministic Variable SetA non-deterministic set of variables. See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM for explanation why it's not deterministic and why it matters. Use DVarSet if the set eventually gets converted into a list or folded over in a way where the order changes the generated code, for example when abstracting variables..5map the function over the list, and union the results.Determines the pluralisation suffix appropriate for the length of a set in the same way that plural from Outputable does for lists..Pretty-print a non-deterministic set. The order of variables is non-deterministic and for pretty-printing that shouldn't be a problem. Having this function helps contain the non-determinism created with nonDetEltsUFM. Passing a list to the pretty-printing function allows the caller to decide on the order of Vars (eg. toposort them) without them having to use nonDetEltsUFM at the call site. This prevents from let-binding non-deterministically ordered lists and reusing them where determinism matters..5Map the function over the list, and union the results.True if empty intersection.True if non-empty intersection.2Partition DVarSet according to the predicate given.'Delete a list of variables from DVarSet."Add a list of variables to DVarSet/Convert a DVarSet to a VarSet by forgetting the order of insertion/transCloVarSet for DVarSet.The things to be pretty printed4The pretty printing function to use on the elements+ where the things have been pretty printed......./................................................./......................................................................................./.../Noneq/.Predicate on possible free variables: returns True! iff the variable is interestingRun a free variable computation, returning a list of distinct free variables in deterministic order and a non-deterministic set containing those variables./Run a free variable computation, returning a list of distinct free variables in deterministic order./Run a free variable computation, returning a deterministic set of free variables. Note that this is just a wrapper around the version that returns a deterministic list. If you need a list you should use /./Run a free variable computation, returning a non-deterministic set of free variables. Don't use if the set will be later converted to a list and the order of that list will impact the generated code./Add a variable - when free, to the returned free variables. Ignores duplicates and respects the filtering function./Return no free variables./%Union two free variable computations./5Mark the variable as not free by putting it in scope./%Mark many free variables as not free./#Filter a free variable computation./Map a free variable computation over a list and union the results./&Union many free variable computations./Add multiple variables - when free, to the returned free variables. Ignores duplicates and respects the filtering function.//////////////////////////////None0An entry to be inserted into a module's static pointer table. See Note [Grand plan for static forms] in GHC.Iface.Tidy.StaticPtrTable.00000 Nonecomplete bipartite graphcomplete graph Resolves all 0, by pushing them in, and simplifies `D D @ = @`Shallow empty check./////////////////////////////////////////// / /11Noned"/'Deterministic Type Variable Environment/Deterministic Identifier Environment Sadly not always indexed by Id, but it is in the common case./"Deterministic Variable Environment/Coercion Variable Environment/%Type or Coercion Variable Environment/Type Variable Environment/Identifier Environment/Variable Environment/Tidy EnvironmentWhen tidying up print names, we keep a mapping of in-scope occ-names (the )+) and a Var-to-Var of the current renamings/Rename Environment 2When we are comparing (or matching) types or terms, we are faced with "going under" corresponding binders. E.g. when comparing: \x. e1 ~ \y. e2Basically we want to rename [x -> y] or [y -> x], but there are lots of things we must be careful of. In particular, x might be free in e2 , or y in e1. So the idea is that we come up with a fresh binder that is free in neither, and rename x and y, respectively. That means we must maintain: 'A renaming for the left-hand expression)A renaming for the right-hand expressionsAn in-scope setFurthermore, when matching, we want to be able to have an 'occurs check', to prevent: \x. f ~ \y. ymatching with [f -> y]. So for each expression we want to know that set of locally-bound variables. That is precisely the domain of the mappings 1. and 2., but we must ensure that we always extend the mappings as we go in.-All of this information is bundled up in the //3A set of variables that are in scope at some point.Note that this is a superset of the variables that are currently in scope. See Note [The InScopeSet invariant]."Secrets of the Glasgow Haskell Compiler inliner" Section 3.2 provides the motivation for this abstraction./Look up a variable the /. This lets you map from the variable's identity (unique) to its full value./uniqAway in_scope v finds a unique that is not used in the in-scope set, and gives that to v. See Note [Local uniques] and Note [The InScopeSet invariant]./unsafeGetFreshUnique in_scope3 finds a unique that is not in-scope in the given /. This must be used very carefully since one can very easily introduce non-unique %s this way. See Note [Local uniques]./Retrieve the left mapping/Retrieve the right mapping/Applies / to several variables: the two variable lists must be of equal length/rnBndr2 env bL bR goes under a binder bL5 in the Left term, and binder bR, in the Right term. It finds a new binder, new_b&, and returns an environment mapping  bL -> new_b and  bR -> new_b/ Similar to / but returns the new variable as well as the new environment. Postcondition: the type of the returned Var is that of bR/ Similar to /7 but used when there's a binder on the left side only./ Similar to /8 but used when there's a binder on the right side only./ Similar to /5 but used for eta expansion See Note [Eta expansion]/ Similar to /5 but used for eta expansion See Note [Eta expansion]/?Look up the renaming of an occurrence in the left or right term/?Look up the renaming of an occurrence in the left or right term/?Look up the renaming of an occurrence in the left or right term/?Look up the renaming of an occurrence in the left or right term/)Tells whether a variable is locally bound/)Tells whether a variable is locally bound/`anyInRnEnvR env set` == `any (inRnEnvR rn_env) (toList set)` but lazy in the second argument if the right side of the env is empty./$Wipe the left or right side renaming/$Wipe the left or right side renaming/"swap the meaning of left and right0+Only keep variables contained in the VarSet0/0//0////00/////0///0///000////////0/0///0/0/////0/0/0/0//////00000//0000/////0//////////////////0//0/0//////////////////////////////////////0///000///0000///00000000000000000000000//////////////////////////////////////////////////0 None +3c0Information to be exposed in interface files which is produced by the stg2stg passes. 00000000000 000000000000. .0( (0 0= =$0; ;0 0& &None 3The constructors which have this field label. Always non-empty.NB: these constructors will always share a single parent, as the field label disambiguates between parents in the presence of duplicate record fields.3The  of a %. Name is an ExternalName However LocalDefs can have an InternalName. This happens only when type-checking a [d| ... |] Template Haskell quotation; see this note in GHC.Rename.Names Note [Top-level Names in Template Haskell decl quotes]INVARIANT 3: If the GlobalRdrEnv maps [occ -> gre], then greOccName gre = occ40Local Reader Environment See Note [LocalRdrEnv]4 Reader NameDo not use the data constructors of RdrName directly: prefer the family of functions that creates them, such as 4Note: A Located RdrName will only have API Annotations if it is a compound one, e.g.  `bar` ( ~ )4Unqualified name1Used for ordinary, unqualified occurrences, e.g. x, y or Foo. Create such a 4 with 44Qualified name)A qualified name written by the user in source code. The module isn't necessarily the module where the thing is defined; just the one from which it is imported. Examples are Bar.x, Bar.y or Bar.Foo. Create such a 4 with 44 Original name$An original name; the module is the defining module. This is used when GHC generates code that will be fed into the renamer (e.g. from deriving clauses), but where we want to say "Use Prelude.map dammit". One of these can be created with 44 Exact nameWe know exactly the . This is used: ,When the parser parses built-in syntax like [] and (,), but wants a 4 from it8By Template Haskell, when TH has generated a unique nameSuch a 4 can be created by using 4 on a 4Look up relevant GREs, taking into account the interaction between the variable and field )s as determined by the FieldsOrSelector argument.4"Look up as many possibly relevant 4s as possible.4Make a qualified 4& in the given namespace and where the  and the  are taken from the first and second elements of the tuple respectively4Create a local 4 for a .4.The SrcSpan of the name pointed to by the GRE.4>The module in which the name pointed to by the GRE is defined.4Takes a list of distinct GREs and folds them into AvailInfos. This is more efficient than mapping each individual GRE to an AvailInfo and then folding using 3', but needs the uniqueness assumption.4 Drop all 3 fields in a 4 in order to avoid space leaks. See Note [Forcing GREInfo] in GHC.Types.GREInfo.4 Hydrate a previously dehydrated 4, by (lazily!) looking up the 3 using the provided function.0See Note [Forcing GREInfo] in GHC.Types.GREInfo.4*After looking up something with the given ), is the resulting 4- we have obtained relevant, according to the 3 specification of which )s are relevant?2Scoring priority function for looking up children 4. We score by 4 and ), with higher priorities having lower numbers. Which lexicographic order we use (4 or ) first) is determined by the first argument; see Note [childGREPriority].43Look something up in the Global Reader Environment.The 3 argument specifies what to look up, and in particular whether there should there be any lee-way if the )s don't exactly match. Collect the 4s with the highest priority according to the given function (lower value  = higher priority)..This allows us to first look in e.g. the data )(, and then fall back to the type/class ).4Look for precisely this  in the environment, in the same ) as the .This tests whether it is in scope, ignoring anything else that might be in scope which doesn't have the same .4?Look for a particular record field selector in the environment.4Is this 4 defined locally?4Is this 4 imported?Not just the negation of 4, because it might be an Exact or Orig name reference. See Note [GlobalRdrElt provenance].4Is this a record field GRE?Important: does not consult the GreInfo field.4:Is this a record field defined with DuplicateRecordFields?4Is this a record field defined with NoFieldSelectors? (See Note [NoFieldSelectors] in GHC.Rename.Env)4Is this a record field defined with FieldSelectors? (See Note [NoFieldSelectors] in GHC.Rename.Env)42Returns the field label of this GRE, if it has one4>Test if an unqualified version of this thing would be in scope42Takes a list of GREs which have the right OccName x: Pick those GREs that are in scope * Qualified, as 4 if want_qual is Qual M _ * Unqualified, as x if want_unqual is Unqual _Return each such GRE, with its ImportSpecs filtered, to reflect how it is in scope qualified or unqualified respectively. See Note [GRE filtering]4Pick GREs that are in scope *both* qualified *and* unqualified Return each GRE that is, as a pair (qual_gre, unqual_gre) These two GREs are the original GRE with imports filtered to express how it is in scope qualified an unqualified respectively9Used only for the 'module M' item in export list; see isBuiltInSyntax filter out names for built-in syntax They just clutter up the environment (esp tuples), and the parser will generate Exact RdrNames for them, so the cluttered envt is no use. Really, it's only useful for GHC.Base and GHC.Tuple.4>Apply a transformation function to the GREs for these OccNames4greClashesWith new_gre old_gre computes whether new_gre clashes with old_gre. (assuming they both have the same underlying )). Is the given 4 shadowed, as specified by the ShadowedNameSpaces?Internal function: is a 4 with the ) with given  shadowed by the specified ?What are all the 4 s that are shadowed by this new 4?5Is in scope unqualified?5,Is in scope qualified with the given module?5Print out one place where the name was define/imported (With -dppr-debug, print them all)5.Indicate if the given name is the "@" operator4the  to look up!information about other relevant )s4the 4 to look up!information about other relevant )s4the  to look upinformation to decide which 4&s are valid children after looking up4specification of which 4s to consider relevantthe ) of the thing we are looking upthe 40 we have looked up, in a potentially different ) than we wanted?what kind of child do we want, e.g. what should its parent be?what ) are we originally looking in?6the result of looking up; it might be in a different ), which is used to determine the score (in the first component)priority function lower value  = higher priority40discard names that are only available qualified?34445444444444444444444444444444444444455444445444444444444444444444444444444444444445444445454444444533333333333333444444444444444443333333333333333343333334444444444444443434333344444444444444444444444444444444444444444444444444444444434444444344333334443333344444444444444444444444444444444444444445554444444444333333333333333444444444443333333333333333355555 5 5 5  5 5 5  5 5 5 %5 5 %5 "5  5 5 5 5 5 <5 )5 .555#5 5555 5555 Nonen;"whether this is a qualified import;(all the things the module could provide.4NB. BangPattern here: otherwise this leaks. (#15111);"whether this is an "hiding" import;whether this is a safe import;#the source span of the whole import;$The name the module is imported with;If a module was "imported" by the user, we associate it with more detailed usage information ;; a module imported by the system only gets used for usage information.;Records the modules directly imported by a module for extracting e.g. usage information, and also to give better error message ;;;;;;;;;;;;; ;;;;;;;;;;;;;NonefDA collection of annotationsDThe kind of annotation target found in the middle end of the compilerDAn annotation targetDWe are annotating something with a name: a type or identifierD%We are annotating a particular moduleDRepresents an annotation after it has been sufficiently desugared from it's initial form of DThe target of the annotationD An empty annotation environment.DConstruct a new annotation environment that contains the list of annotations provided.D,Add the given annotation to the environment.D"Union two annotation environments.D5Find the annotations attached to the given target as  values of your choice. If no deserializer is specified, only transient annotations will be returned.D5Find the annotations attached to the given target as  values of your choice. If no deserializer is specified, only transient annotations will be returned.Find payloads for the given D in an D.DDeserialize all annotations of a given type. This happens lazily, that is no deserialization will take place until the [a] is actually demanded and the [a] can also be empty (the UniqFM is not filtered).DThe "payload" of an annotation allows recovery of its value at a given type, and can be persisted to an interface fileDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD= =0D9 98D D4 4None3 A0conveniently calculate locations for things without locations attached0equivalent of , but does not need Semigroup0Used to track interleaving of class methods, class signatures, associated types and associate type defaults in  ClassDecl and  ClsInstDecl.0Used to track of interleaving of binds and signatures for ValBind0,Captures the sort order of sub elements for ValBinds,  ClassDecl,  ClsInstDecl0exact print annotation used for capturing the locations of annotations in pragmas.0A 0 can capture the locations of surrounding adornments, such as parens or backquotes. This data type identifies what particular pair are being used.0exact print annotations for a RdrName. There are many kinds of adornment that can be attached to a given RdrName. This type captures them, as detailed on the individual constructors.0&Used for a name with an adornment, so `foo`, (bar)0 Used for (,,,), or (,,,)0 Used for  (# | | #)0 Used for (), (##), []0 Used for ->, as an identifier0 Used for an item with a leading '1. The annotation for unquoted item is stored in 0.0Used when adding a 1 to an existing 1 which has no Api Annotation.0Exact print annotation for the Context data type.0!zero or more closing parentheses.0!zero or more opening parentheses.0location of the '=>' , if present.0exact print annotation for an item having surrounding "brackets", such as tuples or lists0'(', ')'0 '(#', '#)'0'[', ']'0Annotation for the "container" of a list. This captures surrounding items such as braces if present, and introductory keywords such as 'where'.0)items appearing after the list, such as '=>' for a context1#start point of a list having layout1Annotation for items appearing in a list. They can have one or more trailing punctuations items, such as commas or semicolons.1Captures the location of punctuation occurring between items, normally in a list. It is captured as a trailing annotation.1 Trailing ';'1 Trailing ','1 Trailing '|'1 Trailing '=>' / C1General representation of a 0 type carrying a parameterised annotation type.1When we are parsing we add comments that belong to a particular AST element, and print them together with the element, interleaving them into the output stream. But when editing the AST to move fragments around it is useful to be able to first separate the comments into those occurring before the AST element and those following it. The 1 constructor is used to do this. The GHC parser will only insert the 1 form.1The exact print annotations (EPAs) are kept in the HsSyn AST for the GhcPs phase. They are usually inserted into the AST by the parser, and in case of generated code (e.g. by TemplateHaskell) they are usually initialized using 0 type class.A goal of the annotations is that an AST can be edited, including moving subtrees from one place to another, duplicating them, and so on. This means that each fragment must be self-contained. To this end, each annotated fragment keeps track of the anchor position it was originally captured at, being simply the start span of the topmost element of the ast fragment. This gives us a way to later re-calculate all Located items in this layer of the AST, as well as any annotations captured. The comments associated with the AST fragment are also captured here.The ann type parameter allows this general structure to be specialised to the specific set of locations of original exact print annotation elements. For example &type SrcSpannAnnA = EpAnn AnnListItem 3is a commonly used type alias that specializes the ann type parameter to 1.The spacing between the items under the scope of a given EpAnn is normally derived from the original Anchor. But if a sub-element is not in its original position, the required spacing can be captured using an appropriate  value for the 1 Anchor. This allows us to freely move elements around, and stitch together new AST fragments out of old ones, and have them still printed out in a precise way.16Comments enclosed in the SrcSpan of the element this 1 is attached to1Annotations added by the Parser1Base location for the start of the syntactic element holding the annotations.1Tokens embedded in the AST have an EpaLocation, unless they come from generated code (e.g. by TH).1;a docstring that can be pretty printed using pprHsDocString1(doc options (prune, ignore-exports, etc)1comment starting by "--"1comment in {- -}1?The location of the prior token, used in exact printing. The 1 appears as an 1 containing its location. The difference between the end of the prior token and the start of this location is used for the spacing when exact printing the comment.1$Layout information for declarations.1$Explicit braces written by the user. 'class C a where { foo :: a; bar :: a } 10Virtual braces inserted by the layout algorithm. &class C a where foo :: a bar :: a 1Empty or compiler-generated blocks do not have layout information associated with them.1With  UnicodeSyntax, there might be multiple ways to write the same token. For example an arrow could be either -> or C. This choice must be recorded in order to exactprint such tokens, so instead of  EpToken "->" we introduce EpUniToken "->" "C".1A token stored in the syntax tree. For example, when parsing a let-expression, we store  EpToken "let" and  EpToken "in". The locations of those tokens can be used to faithfully reproduce (exactprint) the original program text.1 HsExpr (GhcPass p) -> blah f e = case ghcPass @p of GhcPs -> ... in this RHS we have HsExpr GhcPs... GhcRn -> ... in this RHS we have HsExpr GhcRn... GhcTc -> ... in this RHS we have HsExpr GhcTc... which is very useful, for example, when pretty-printing. See Note [IsPass].5Used as a data type index for the hsSyn AST; also serves as a singleton type for PassMarks that a field uses the GhcRn variant even when the pass parameter is GhcTc. Useful for storing HsTypes in GHC.Hs.Exprs, say, because HsType GhcTc should never occur. See Note [NoGhcTc]5555555555555555555555555555555555555555 5 &5 5 (5 5 5 5 5 5None 54Maps of docs that were added via Template Haskell's putDoc.56The documentation added to class and family instances.5.The documentation added to function arguments.5(The documentation added to declarations.54The added module header documentation, if it exists.57The full set of language extensions used in the module.5The !! used in the module, for example !.5Haddock options from OPTIONS_HADDOCK or from  -haddock-opts.5Map from chunk name to content.This map will be empty unless we have an explicit export list from which we can reference the chunks.5>Docs for arguments. E.g. function arguments, method arguments.5Docs for declarations: functions, data types, instances, methods etc. A list because sometimes subsequent haddock comments can be combined into one5 Docs attached to module exports.5Module header.5A simplified version of .5Annotate a value with the probable identifiers found in it These will be used by haddock to generate links.The identifiers are bundled along with their location in the source file. This is useful for tooling to know exactly where they originate.This type is currently used in two places - for regular documentation comments, with a set to <, and for adding identifier information to warnings, where a is  StringLiteral58A docstring with the (probable) identifiers found in it.5Extract a mapping from the lexed identifiers to the names they may correspond to.5Pretty print a thing with its doc The docstring will include the comment decorators '-- |', '{-|' etc and will come either before or after depending on how it was written i.e it will come after the thing if it is a '-- ^' or '{-^' and before otherwise.5See  pprWithHsDoc56Print a doc with its identifiers, useful for debugging5For compatibility with the existing @-ddump-parsed' output, we only show the docstring.Use pprHsDoc to show 5 's internals.5We might re-export avails from multiple modules with a single export declaration. E.g. when we have 7module M (module X) where import R0 as X import R1 as XInvariant: This list of ModuleNames must be sorted to guarantee interface file determinism.Invariant: This list of Avails must be sorted to guarantee interface file determinism.=55555555555555555555555555555555555#55555555555555555555555555555555555 5 ;5 5 5 !5 %5 !5 5 5 55None 31%Is a TyCon a promoted data constructor or just a normal type constructor?5Field OccurrenceRepresents an *occurrence* of a field. This may or may not be a binding occurrence (e.g. this type is used in 6 and RecordPatSynField' which bind their fields, but also in  HsRecField5 for record construction and patterns, which do not).We store both the RdrName the user originally wrote, and after the renamer we use the extension field to store the selector function.There is a wrinkle in that update field occurances are sometimes ambiguous during the rename stage. See note [Ambiguous FieldOcc in record updates] to see how we currently handle this.5Located Field Occurrence5/Arguments in an expression/type after splitting6Describes the arguments to a data constructor. This is a common representation for several constructor-related concepts, including:The arguments in a Haskell98-style constructor declaration (see HsConDeclH98Details in  GHC.Hs.Decls).)The arguments in constructor patterns in case/function definitions (see HsConPatDetails in  GHC.Hs.Pat).The left-hand side arguments in a pattern synonym binding (see HsPatSynDetails in  GHC.Hs.Binds).One notable exception is the arguments in a GADT constructor, which uses a separate data type entirely (see HsConDeclGADTDetails in  GHC.Hs.Decls). This is because GADT constructors cannot be declared with infix syntax, unlike the concepts above (#18844).6Constructor Declaration Field6See Note [ConDeclField pass]6%Located Constructor Declaration Field6Haskell Tuple Sort6This is used in the syntax. In constructor declaration. It must keep the arrow representation.62Denotes the type of arrows in the surface language6a -> b or a C b6a %1 -> b or a %1 C b, or a E b6a %m -> b or a %m C b (very much including `a %Many -> b`! This is how the programmer wrote it). It is stored as an 69 so as to preserve the syntax as written in the program.6Haskell Type Literal6 Haskell Type6  (?x :: ty)6  (ty :: kind)6>Haskell Type Variable Binder See Note [Type variable binders]6These names are used early on to store the names of implicit parameters. They completely disappear after type-checking.6 A type signature that obeys the forall&-or-nothing rule. In other words, an 7 that uses an 6 to represent its outermost type variable quantification. See #Note [Representing type signatures].6Main payload (the type itself)6After renamer:  HsTyPatRn6'Located Haskell Signature Wildcard Type6Located Haskell Wildcard Type6Located Haskell Signature Type6Types that can appear in pattern signatures, as well as the signatures for term-level binders in RULES. See ,Note [Pattern signature binders and scoping].This is very similar to  HsSigWcType., but with slightly different semantics: see Note [HsType binders] . See also #Note [The wildcard story for types].6Main payload (the type itself)6After renamer: HsPSRn6Haskell Wildcard Binders6.Used for type-family instance equations, e.g., 'type instance forall a. F [a] = Tree a The notion of specificity is irrelevant in type family equations, so we use () for the 6 flag.6Used for signatures, e.g., f :: forall a {b}. blah We use  for the 6 flag to allow distinguishing between specified and inferred type variables.66The outermost type variables in a type that obeys the forall-or-nothing rule. See Note [forall-or-nothing rule].6Implicit forall, e.g., f :: a -> b -> b6Explicit forall, e.g., f :: forall a b. a -> b -> b7)Located Haskell Quantified Type Variables7$Located Haskell Type Variable Binder7 The type variable binders in an 6 . See also 1Note [Variable Specificity and Forall Visibility] in GHC.Tc.Gen.HsType.7 A visible forall (e.g., forall a -> {...}). These do not have any notion of specificity, so we use () as a placeholder value.7 An invisible forall (e.g., forall a {b} c. {...}), where each binder has a .7Located Haskell Kind7 Haskell Kind7Located Haskell Type7Haskell Context7Located Haskell Context7 Bang TypeIn the parser, strictness and packedness annotations bind more tightly than docstrings. This means that when consuming a 7 (and looking for 68) we must be ready to peer behind a potential layer of 6 . See #15206 for motivation and  getBangType for an example.7Located Bang Type7 Does this 6' come with an explicit kind annotation?7An empty list that can be used to indicate that there are no type arguments allowed in cases where HsConDetails is applied to Void.77777777%77 7666666655555566566666666666666666666666777777777667666666666666666666666666666666666666666666666666666666666666666666666666666676577777776667756%%%5666666665655666666776666666666666666666666666666666666666667776666666666666666666667777777777666666677777766666666666666666666666666666666666667766666667566565555577 %%%%666666666666755555577777 77 77777  None )3.37!Haskell Pattern Synonym Direction7Record Pattern Synonym Field7=Filled in by renamer, the name used internally by the pattern7'Field label visible in rest of the file7Haskell Pattern Synonym Details7Fixity Signature7Located Fixity Signature7Signatures and pragmas7An ordinary type signature f :: Num a => a -> aAfter renaming, this list of Names contains the named wildcards brought into scope by this signature. For a signature _ -> _a -> Bool., the renamer will leave the unnamed wildcard _$ untouched, and the named wildcard _a is then replaced with fresh meta vars in the type. Their names are stored in the type signature that brought them into scope, in this third field to be more specific.7 A pattern synonym type signature ,pattern Single :: () => (Show a) => a -> [a]7A signature for a class method False: ordinary class-method signature True: generic-default class method signature e.g. class C a where op :: a -> a -- Ordinary default op :: Eq a => a -> a -- Generic default No wildcards allowed here7An ordinary fixity declaration  infixl 8 ***7An inline pragma {#- INLINE f #-}7A specialisation pragma "{-# SPECIALISE f :: Int -> Int #-}76A specialisation pragma for instance declarations only ${-# SPECIALISE instance Eq [Int] #-}(Class tys); should be a specialisation of the current instance declaration7$A minimal complete definition pragma ${-# MINIMAL a | (b, c | (d | e)) #-}7+A "set cost centre" pragma for declarations {-# SCC funName #-}or &{-# SCC funName "cost_centre_name" #-}7A complete match pragma {-# COMPLETE C, D [:: T] #-}Used to inform the pattern match checker about additional complete matchings which, for example, arise from pattern synonym definitions.7Located Signature7Implicit parameter bindings.7"Located Implicit Parameter Binding7#Haskell Implicit Parameter Bindings7Multiplicity annotations, on binders, are always resolved (to a unification variable if there is no annotation) during type-checking. The resolved multiplicity is stored in the extension fields.7Pattern Synonym binding7Directionality7Right-hand side7Formal parameter names7Name of the pattern synonym71Haskell Binding with separate Left and Right id's7Function-like Binding'FunBind is used for both functions f x = e) and variables  f = x -> e) and strict variables  !x = x + 1/Reason 1: Special case for type inference: see .Reason 2: Instance decls can only have FunBinds, which is convenient. If you change this, you'll need to change e.g. rnMethodBinds'But note that the form f :: a->a = ... parses as a pattern binding, just like (f :: a -> a) = ... 6Strict bindings have their strictness recorded in the  SrcStrictness of their  MatchContext. See Note [FunBind vs PatBind] for details about the relationship between FunBind and PatBind.7Pattern BindingThe pattern is never a simple variable; That case is done by FunBind. See Note [FunBind vs PatBind] for details about the relationship between FunBind and PatBind.7Variable BindingDictionary binding and suchlike. All VarBinds are introduced by the type checker7Patterns Synonym Binding7 The payload7$See Note [Multiplicity annotations].7Located only for consistency7Located Haskell Binding with separate Left and Right identifier types7Located Haskell Bindings with separate Left and Right identifier types7Haskell Binding7Located Haskell Bindings7Located Haskell Binding7Haskell Value bindings with separate Left and Right identifier types (not implicit parameters) Used for both top level and nested bindings May contain pattern synonym bindings7Value Bindings InBefore renaming RHS; idR is always RdrName Not dependency analysed Recursive by default7Value Bindings OutAfter renaming RHS; idR can be Name or Id Dependency analysed, later bindings in the list may depend on earlier ones.7Haskell Value Bindings7Haskell Local Bindings with separate Left and Right identifier typesBindings in a 'let' expression or a 'where' clause7Haskell Value Bindings7#Haskell Implicit Parameter Bindings7Empty Local Bindings7Located Haskell local bindings7Haskell Local Bindings8778787777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777888777777777None $Indicates whether a module name is referring to a boot interface (hs-boot file) or regular module (hs file). We need to treat boot modules specially when building compilation graphs, since they break cycles. Regular source files and signature files are treated equivalently.8$Located name with possible adornment8A name in an import or export specification which may have adornments. Used primarily for accurate pretty printing of ParsedSource, and API Annotation placement.8unadorned name, e.g myFun8 default X ()=, see Note [Named default declarations] in GHC.Tc.Gen.Default8  pattern Xexactprint: the location of pattern keyword is captured via 8  type (:+:)exactprint: the location of type keyword is captured via 82Wildcard in an import or export sublist, like the .. in import Mod ( T(Mk1, Mk2, ..) ).8no wildcard in this list86wildcard after the given # of items in this list The Int< is in the range [0..n], where n is the length of the list.8Imported or exported entity.8Imported or exported variable (module Mod ( test ) import Mod ( test ) 87Imported or exported Thing with absent subordinate list&The thing is a Class/Type (can't tell) (module Mod ( Test ) import Mod ( Test ) 8Imported or exported thing with wildcard subordinate list (e.g. (..))The thing is a Class/Type and the All refers to methods/constructors 0module Mod ( Test(..) ) import Mod ( Test(..) ) 8:Imported or exported thing with explicit subordinate list.The thing is a Class/Type (can't tell) and the imported or exported things are its children. 4module Mod ( Test(f, g) ) import Mod ( Test(f, g) ) 87Export of entire module. Can only occur in export list. module Mod ( module Mod2 ) 8$A Haddock section in an export list. 0module Mod ( -- * Section heading ... ) 8A bit of unnamed documentation. .module Mod ( -- | Documentation ... ) 8+A reference to a named documentation chunk. )module Mod ( -- $chunkName ... ) 8,A docstring attached to an export list item.8Located Import or Export8>Whether the import list is exactly what to import, or whether hiding was used, and therefore everything but what was listed should be imported8Import DeclarationA single Haskell import declaration.85Explicit import list (EverythingBut => hiding, names)8 as Module8If/how the import is qualified.8True => safe import8 IsBoot <=> {-# SOURCE #-} import8Package qualifier.8 Module name.8Locations of keywords like import,  qualified, etc. are captured here.8If/how an import is  qualified.8 qualified! appears in prepositive position.8 qualified" appears in postpositive position.8Not qualified.8Located Import Declaration8When in a list this may have,88888888888888888888888888888888888888888,88888888888888888888888888888888888888888 80 0 8 )8 8888..8..8..8.."8' '8''None 38$Names that are deprecated as exports8Deprecated declarations8!Warning information from a module8Whole module deprecated8 Warning Text6reason/explanation from a WARNING or DEPRECATED pragma8/A finite or infinite set of warning categories.Unlike  WarningFlag, there are (in principle) infinitely many warning categories, so we cannot necessarily enumerate all of them. However the set is constructed by adding or removing categories one at a time, so we can represent it as either a finite set of categories, or a cofinite set (where we store the complement).6The set of warning categories is the given finite set.The set of warning categories is infinite, so the constructor stores its (finite) complement.8The  deprecations category is used for all DEPRECATED pragmas and for WARNING pragmas that do not specify a category.8Is this warning category allowed to appear in user-defined WARNING pragmas? It must either be the known category  deprecations,, or be a custom category that begins with x- and contains only valid characters (letters, numbers, apostrophes and dashes).8$The empty set of warning categories.86The set consisting of all possible warning categories.8Is this set empty?8-Does this warning category belong to the set?8.Insert an element into a warning category set.8.Delete an element from a warning category set.8To which warning category does this WARNING or DEPRECATED pragma belong? See Note [Warning categories].87The message that the WarningTxt was specified to output8=True if the 2 WarningTxts have the same category and messages8Constructs the cache for the mi_decl_warn_fn field of a ModIface8Constructs the cache for the mi_export_warn_fn field of a ModIface8Names deprecated (may be empty)!Exports deprecated (may be empty)8Warning category attached to this WARNING pragma, if any; see Note [Warning categories]8Existing warningsNew declaration deprecationsUpdated warnings8Existing warningsNew export deprecationsUpdated warnings%8888888888888888888888888888888888888%88888888888888888888888888888888888888 &8 &8 88888!+8-183<8>8688:8'None )3#,8Role Annotation Declaration8#Located Role Annotation Declaration8Annotation Provenance8Annotation Declaration8Located Annotation Declaration8Warning pragma Declaration8"Located Warning pragma Declaration8Warning pragma Declarations9Located Warning Declarations9!Documentation comment Declaration9)Located Documentation comment Declaration9 Rule Binder9Located Rule Binder9Rule Declaration9Forall'd term vars, before typechecking; after typechecking this includes all forall'd vars9Forall'd type vars9Note [Pragma source text] in GHC.Types.SourceText9-After renamer, free-vars from the LHS and RHS9Located Rule Declaration9Rule Declarations9Located Rule Declarations9Foreign Declaration9Located Foreign Declaration9Default Declaration9Located Default Declaration9Which technique the user explicitly requested when deriving an instance.9GHC's "standard" strategy, which is to implement a custom instance for the data type. This only works for certain types that GHC knows about (e.g., %, 1, * when -XDeriveFunctor is enabled, etc.)9 -XDeriveAnyClass9 -XGeneralizedNewtypeDeriving9  -XDerivingVia9A Located 9.9+Stand-alone 'deriving instance' declaration9The instance type to derive. It uses an 69 because the context is allowed to be a single wildcard: !deriving instance _ => Eq (Foo a)4Which signifies that the context should be inferred.93Located stand-alone 'deriving instance' declaration9Instance Declaration9Located Instance Declaration9Class Instance Declaration9"Located Class Instance Declaration9Family EquationOne equation in a type family instance declaration, data family instance declaration, or type family default. See Note [Type family instance declarations in HsSyn] See Note [Family instance declaration binders]9Fixity used in the declaration9Optional quantified type vars9 Data Family Instance Declaration9(Located Data Family Instance Declaration9 Type Family Instance Declaration9(Located Type Family Instance Declaration9)Located type family default declarations.9 MkT a b MkT :: forall b a. Eq a => MkT a b data T b where MkT1 :: Int -> T Int data T = Int MkT, Int | MkT2 data T a where Int MkT Int :: T Int data Constructor Declaration:A possible Haddock comment.: Result type:Arguments; never infix:User-written context (if any):The outermost type variable binders, be they explicit or implicit. The   is used to anchor exact print annotations, AnnForall and AnnDot.:Arguments; can be infix:Existentials only:True  = explicit user-written forall e.g. data T a = forall b. MkT b (b->a) con_ex_tvs = {b} False => con_ex_tvs is empty:$Located data Constructor Declaration:#Whether a data-type declaration is data or newtype, and its constructors.:5When we only care whether a data-type declaration is `data` or  `newtype`", but not what constructors it has: newtype Blah ...:  data Blah ...:!Located Standalone Kind Signature: The types mentioned in a single deriving& clause. This can come in two forms, : or :, depending on whether the types are surrounded by enclosing parentheses or not. These parentheses are semantically different than 6. For example,  deriving () means "derive zero classes" rather than "derive an instance of the 0-tuple".: use 6 because deriving clauses can mention type variables that aren't bound by the datatype, e.g. data T b = ... deriving (C [a])&should produce a derived instance for  C [a] (T b).:A deriving clause with a single type. Moreover, that type can only be a type constructor without any arguments. Example:  deriving Eq:A deriving clause with a comma-separated list of types, surrounded by enclosing parentheses. Example: deriving (Eq, C a): A single deriving clause of a data declaration.:The types to derive.:;The user-specified strategy (if any) to use when deriving :.:Haskell Deriving clause:Haskell Data type Definition::Declares a data type or newtype, giving its constructors  data/newtype T a =  constrs! data/newtype instance T [a] =  constrs : Optional  'deriving' clause:Data constructorsFor data T a = T1 | T2 a the : s all have :. For data T a where { T1 :: T a } the  LConDecls all have :.:Optional kind signature.(Just k) for a GADT-style data, or  data instance decl, with explicit kind sigAlways Nothing for H98-syntax decls:Context:K if we're in an hs-boot file and the user said "type family Foo x where ..":If the user supplied an injectivity annotation it is represented using InjectivityAnn. At the moment this is a single injectivity condition - see Note [Injectivity annotation]. `Located name` stores the LHS of injectivity condition. `[Located name]` stores the RHS of injectivity condition. Example:.type family Foo a b c = r | r -> a c where ...,This will be represented as "InjectivityAnn r [a, c]":Located Injectivity Annotation:type Family Declaration:Located type Family Declaration:type Family Result Signature:$Located type Family Result Signature:Type or Class Group:A type or class declaration.: type/data family T :: *->*:type declaration:data declaration:RHS of type declaration:Fixity used in the declaration:Type variables; for an associated type these include outer binders:Type constructor:Post renamer, FVs:Post renamer, CUSK flag, FVs: Haddock docs:Associated type defaults:Associated types;:Default methods:Methods' signatures:Functional deps: Context...:Post renamer, FVs:&Located Declaration of a Type or Class:A splice can appear with various decorations wrapped around it. This data type captures explicitly how it was originally written, for use in the pretty printer.:$splice: bare splice:Splice Declaration:Located Splice Declaration: Haskell GroupA ; is categorised into a :" before being fed to the renamer.;A Haskell Declaration;Type or Class Declaration;Instance declaration;Deriving declaration;Value declaration;Signature declaration;Standalone kind signature; 'default' declaration;Foreign declaration;Warning declaration;Annotation declaration;Rule declaration;+Splice declaration (Includes quasi-quotes);"Documentation comment declaration;Role annotation declaration;True  = argument is a data/newtype declaration.;!type or type instance declaration; type class;type/data family declaration;type family declaration;open type family info;closed type family info;data family declaration;Are the constructors within a  type data declaration? See Note [Type data declarations] in GHC.Rename.Module.;)Retrieve the first data constructor in a : (if one exists).: The optional deriving clauses of a data declaration. Clauses is plural because one can specify multiple deriving clauses using the -XDerivingStrategies language extension. The list of :s corresponds to exactly what the user requested to derive, in order. If no deriving clauses were specified, the list is empty.;When in a list this may have; Just cls  =* this is an associated family of class cls;;;;;;;;;;;;;;;;;;;;;8888888999999999999999::::::::::::::::::999999999::::99999999999999999999999999::::::::::::::::::::9999999999999999:::99999:::::::::;;;;;;;;;;;;;;;;:::::::9:::::::;:::;;;::::9999999999989:99:999::9;:::98999:::99989:::8889999999999999999999::::::::::::::::::::::::::::::::::::::::999999988888898999;;;;;;;;;;;;;;;;;::::::::::::::::::::::::::::::::;;;::::::::::::::::::::::::::::::::::::;;;;;;;;;;;;;::::::::::::999999999999::::;99999999999999999999999999999999999999999999999999999999999999999999999;9999999:::::::9999999999999999999999::::::::::::::::99999999999999;888888898988888888;8888:::::::::::::::::;:::;;;:; ; ;;; ;");+6;;; ;;;  None 3_ DThe location of the as keywordD-The location of the package name (when using -XPackageImports)DThe location of the  qualified keywordDThe location of the safe keywordDThe locations of  {-# SOURCE and #-} respectivelyDThe location of the import keywordDGHC generates an 8 to represent the invisible `import Prelude` that appears in any file that omits `import Prelude`, setting this field to indicate that the import doesn't appear in the original source. True => implicit import (of Prelude)DGiven two possible located  qualified tokens, compute a style (in a conforming Haskell program only one of the two can be not K). This is called from  GHC.Parser.DConvenience function to answer the question if an import decl. is qualified.EEEDDEEDDEEEEDDDDDDDDDDDDDDD88888888888888888888888888888888888888888EEEDDEEDDEEEEDDDDDDDDDDDDDDDE E E E ;E E .EEE+E+E+E-E-E-None DDDDDDDDDDD DDDDDDDDDDDD$ $D  D !D #None+3J1Always unary: just one TypeEqn argument Returns Nothing when it doesn't like the supplied argument. When this happens in a coercion that means that the coercion is ill-formed, and Core Lint checks for that.J-A more explicit representation for `t1 ~ t2`.JCoAxiomRule describes a built-in axiom, one that we assume to be true See Note [CoAxiomRule]JA branch of a coercion axiom, which provides the evidence for unwrapping a newtype or a type-family reduction step using a single equation.JThe previous incompatible branches See Note [Storing compatibility]JRight-hand side of the equality See Note [CoAxioms are homogeneous]JType patterns to match againstJSee Note [CoAxBranch roles]JBound coercion variables Always empty, for now. See Note [Constraints in patterns] in GHC.Tc.TyClJEta-reduced tyvars cab_tvs and cab_lhs may be eta-reduced; see Note [Eta reduction for data families]JBound type variables; not necessarily fresh See Note [CoAxBranch type variables]J?Location of the defining equation See Note [CoAxiom locations]JA J: is a "coercion constructor", i.e. a named equality axiom.KThe  [CoAxBranch] passed into the mapping function is a list of all previous branches, reversedKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ KJJKJJJKKKKKJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKK KJJJJJJJJJJJJJJJJJJJKKKKJJJJK K K K K !K /K !K  K K  K K K NoneKInformation about a type family equation, used for validity checking of closed type family equations and associated type family default equations.This type exists to delay validity-checking after typechecking type declaration groups, to avoid cyclic evaluation inside the typechecking knot.See (Note [Type-checking default assoc decls] in  GHC.Tc.TyCl.KUsed for equations which don't need any validity checking, for example equations imported from another module.KInformation necessary for validity checking of a type family equation.KRHS of the equationNB: for associated type family default declarations, this is the RHS *before* applying the substitution from Note [Type-checking default assoc decls] in GHC.Tc.TyCl.K LHS patternsK=non-user-written type variables (for error message reporting)(Example: with -XPolyKinds, typechecking type instance forall a. F = () introduces the kind variable k for the kind of a . See #23734.KLHS quantified type variablesK4Default associated type (if any) from this template.As per Note [Associated type defaults], the Type has been renamed to use the class tyvars, while the K0 uses the original user-written type variables.(KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK(KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK K K K K NoneM-The register architecture of a given machine.Floating-point and vector registers are unified (e.g. X86, AArch64).?Floating-point and vector registers are separate (e.g. RISC-V).No vector registers.The class of a register. Used in the register allocator. We treat all registers in a class as being interchangeable.>>=C@B><@>C@@C?C>B>D>D>C?C><>>>@@?BBAB><@A=AA=A@AB@@C@=@=CBCAC=A=A@BC?A@?BC>AA=A=@?=@?<@?=@B>B>B>DAC>C>B@@BBBA=C@C@@?C?C?C?<CB>AAACB>==@>=B><@@D?=C?C@CC??C?C@C>=A@A@@><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<@?@?B?BC>B@@?AAA@@?AAA@@?AAA@@?AAAB@@D>D>D?D?D?DD>>D?D>D>C>D>D>D?BBBD?D>D>D>D?D>D>D>D>D?D?D>D?C?C?D>C>C>C>C>D>C>@D?@?DDB?@A?@@C?=@@;;@?>>B@B=A=AB?B?B?B?A?B?B?B?@@@@@@=C<=B>B=C=<@C>C>=B>B>B>C@=@>@>@@@@@>AAA@@C@D>D>D>D>D>D>D>D>D>D>BBD>D>D>D>D>D>D>D>D>D>D>D>D>C?C?D>@D>C>C@BBB>B>CCA?BC=B>DBC@>B=B=B=@=C>@<==A==C=A@<=<<=B>C?=A=ACAA@=>>=C@=<=B>B=C=@?@>C?BC?@?======AAA?A?B>B>B>B>A=B@BAA@@@ADC?C?C?AB@B@A@A@=@<>C?C>A<=C@C?<=BBBBBBC?ABB?CB?B?B?BB?B?A?B?BBBBBBBBBC?C?A?ABBC?B@?=A===A===A===A===A===A=A===A=====CBAAC>C>C>C>C>C>AC?C?A?==B??A?CA=@=BABABCCA=@B=@?AA?AAAAA?AAAAA@AAABAA?AAABAAAAC?ABBB@;;==>>>=C@B><@>C@@C?C>B>D>D>C?C><>>>@@?BBAB><@A=AA=A@AB@@C@=@=CBCAC=A=A@BC?A@?BC>AA=A=@?=@?<@?=@B>B>B>DAC>C>B@@BBBA=C@C@@?C?C?C?<CB>AAACB>==@>=B><@@D?=C?C@CC??C?C@C>=A@A@@><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<@?@?B?BC>B@@?AAA@@?AAA@@?AAA@@?AAAB@@D>D>D?D?D?DD>>D?D>D>C>D>D>D?BBBD?D>D>D>D?D>D>D>D>D?D?D>D?C?C?D>C>C>C>C>D>C>@D?@?DDB?@A?@@C?=@@;;@?>>B@B=A=AB?B?B?B?A?B?B?B?@@@@@@=C<=B>B=C=<@C>C>=B>B>B>C@=@>@>@@@@@>AAA@@C@D>D>D>D>D>D>D>D>D>D>BBD>D>D>D>D>D>D>D>D>D>D>D>D>C?C?D>@D>C>C@BBB>B>CCA?BC=B>DBC@>B=B=B=@=C>@<==A==C=A@<=<<=B>C?=A=ACAA@=>>=C@=<=B>B=C=@?@>C?BC?@?======AAA?A?B>B>B>B>A=B@BAA@@@ADC?C?C?AB@B@A@A@=@<>C?C>A<=C@C?<=BBBBBBC?ABB?CB?B?B?BB?B?A?B?BBBBBBBBBC?C?A?ABBC?B@?=A===A===A===A===A===A=A===A=====CBAAC>C>C>C>C>C>AC?C?A?==B??A?CA=@=BABABCCA=@B=@?AA?AAAAA?AAAAA@AAABAA?AAABAAAAC?ACNone^ǯTyCons represent type constructors. Type constructors are introduced by things such as:1) Data declarations: data Foo = ... creates the Foo type constructor of kind Type2) Type synonyms: type Foo = ... creates the Foo type constructor 3) Newtypes: newtype Foo a = MkFoo ... creates the Foo type constructor of kind  Type -> Type4) Class declarations: class Foo where creates the Foo type constructor of kind  ConstraintThis data type also encodes a number of primitive, built in type constructors such as those for function and tuple types.If you edit this type, you may need to update the GHC formalism See Note [GHC Formalism] in GHC.Core.LintMake a  for the Typeable* representation of the given wired-in type Is this the  for an unboxed tuple? Does this  represent a tuple?NB: when compiling  Data.Tuple, the tycons won't reply True to , because they are built as  AlgTyCons. However they get spat into the interface file as tuple tycons, so I don't think it matters.Is this  that for a newtypeLA L is an abstraction of a non-void type. (Use PrimRepOrVoidRep if you want void types too.) It contains information that the code generator needs in order to pass arguments, return results, and store values of this type. See also Note [RuntimeRep and PrimRep] in GHC.Types.RepType and Note [VoidRep] in GHC.Types.RepType.LBoxed, heap valueLSigned, 8-bit valueLSigned, 16-bit valueLSigned, 32-bit valueLSigned, 64 bit valueLSigned, word-sized valueLUnsigned, 8 bit valueLUnsigned, 16 bit valueLUnsigned, 32 bit valueLUnsigned, 64 bit valueLUnsigned, word-sized valueLA pointer, but not to a Haskell value (use L)LA vectorL;Information pertaining to the expansion of a type synonym (type)LRepresents an open type family without a fixed right hand side. Additional instances can appear at any time.7These are introduced by either a top level declaration: data family T a :: TypeOr an associated data type declaration, within a class declaration: $class C a b where data T b :: TypeL"An open type synonym family e.g. !type family F x y :: Type -> TypeL$A closed type synonym family e.g. &type family F x where { F Int = Bool }LA closed type synonym family declared in an hs-boot file with type family F a where ..L0Built-in type family used by the TypeNats solverLDescribes the flavour of an algebraic type constructor. For classes and data families, this flavour includes a reference to the parent .LAn ordinary algebraic type constructor. This includes unlifted and representation-polymorphic datatypes and newtypes and unboxed tuples, but NOT unboxed sums; see UnboxedSumTyCon.LAn unboxed sum type constructor. This is distinct from VanillaAlgTyCon because we currently don't allow unboxed sums to be Typeable since there are too many of them. See #13276.LType constructors representing a class dictionary. See Note [ATyCon for classes] in GHC.Core.TyCo.RepLType constructors representing an *instance* of a *data* family. Parameters:1) The type family in question*2) Instance types; free variables are the L of the current  (not the family one). INVARIANT: the number of types matches the arity of the family 3) A CoTyCon identifying the representation type with the type instance familyLSome promoted datacons signify extra info relevant to GHC. For example, the L constructor of L corresponds to the L constructor of L. This data structure allows us to store this information right in the 6. The other approach would be to look up things like L's L by known-key every time. See also Note [Getting from RuntimeRep to PrimRep] in GHC.Types.RepTypeLan ordinary promoted data conLA constructor of L. The argument to the function should be the list of arguments to the promoted datacon.LA constructor of LLA constructor of LLA constructor of %LRepresents right-hand-sides of s for algebraic typesLSays that we know nothing about this data type, except that it's represented by a pointer. Used when we export a data type abstractly into an .hi file.LInformation about those s derived from a data declaration. This includes data types with no constructors at all.LAn unboxed sum type.LInformation about those s derived from a newtype declarationLM if the data type constructor has a known, fixed levity when fully applied to its arguments, False otherwise.This can only be J with UnliftedDatatypes, e.g. 5data A :: TYPE (BoxedRep l) where { MkA :: Int -> A }This boolean is cached to make it cheaper to check for levity and representation-polymorphism in tcHasFixedRuntimeRep.LCached value: is this an enumeration type? See Note [Enumeration types]LCached value: length data_consLThe data type constructors; can be empty if the user declares the type to have no constructors'INVARIANT: Kept in order of increasing (/ tag (see the tag assignment in mkTyConTagMap)L.Is this a boxed, unboxed or constraint tuple?LThe unique constructor for the newtype. It has no existentialsLM if the newtype has a known, fixed representation when fully applied to its arguments, J# otherwise. This can only ever be J with UnliftedNewtypes.Example: newtype N (a :: TYPE r) = MkN a=Invariant: nt_fixed_rep nt = tcHasFixedRuntimeRep (nt_rhs nt)This boolean is cached to make it cheaper to check if a variable binding is representation-polymorphic in tcHasFixedRuntimeRep.L Same as the L0, but this time eta-reduced. Hence the list of ?s in this field may be shorter than the declared arity of the .LCached value: the argument type of the constructor, which is just the representation type of the  (remember that newtypes do not exist at runtime so need a different representation type). The free s of this type are the L from the corresponding "Algebraic data types, from - data declarations - newtype declarations - data instance declarations - type instance declarations - the TyCon generated by a class declaration - boxed tuples - unboxed tuples - constraint tuples - unboxed sums Datanewtypetype families are handled by . See L for more information.Represents type synonymsRepresents families (both type and data) Argument roles are all NominalPrimitive types; cannot be defined in Haskell. This includes the usual suspects (such as Int#0) as well as foreign-imported types and kinds (*, #, and ?)Represents promoted data constructor. The kind of a promoted data constructor is the *wrapper* type of the original data constructor. This type must not have constraints (as checked in GHC.Tc.Gen.HsType.tcTyVar).These exist only during type-checking. See Note [TcTyCon, MonoTcTyCon, and PolyTcTyCon] in  GHC.Tc.TyClThe flavour of this algebraic tycon. Gives the class or family declaration  for derived 8s representing class or family instances, respectively.L,Maps a label to information about the fieldContains information about the data constructors of the algebraic typeThe "stupid theta" for the data type (always empty for GADTs). A "stupid theta" is the context to the left of an algebraic type declaration, e.g. Eq a in the declaration data Eq a => T a .... See Note [The stupid context] in GHC.Core.DataCon.Was the data type declared with GADT syntax? If so, that doesn't mean it's a true GADT; only that the "where" form was used. This field is used only to guide pretty-printingThe C type that should be used for this type when using the FFI and CAPI8Contains information about the expansion of the synonymis this a type family injective in its type variables? Nothing if no injectivity annotation was givenFor *associated* type/data families The class tycon in which the family is declared See Note [Associated families and their parent class]Type family flavour: open, closed, abstract, built-in. See comments for FamTyConFlavName of result type variable, used for pretty-printing with --show-iface and for reifying TyCon in Template Haskell†The Typeable' representation. A cached version of  (L tc).ÆSee comments with LĆCorresponding data constructorņ What sort of  this represents.ƆIs this TcTyCon already generalized? Used only to make zonking more efficientdžScoped tyvars over the tycon's body The range is always a skolem or TcTyVar, be MonoTcTyCon only: see Note [Scoped tyvars in a TcTyCon]LThe role for each type variable This list has length = tyConArity See also Note [TyCon Role signatures]LA pre-allocated TyConApp tycon []LArityLKind of this TyConL TyVar bindersL Result kindL Full bindersLName of the constructorLA Unique of this TyCon. Invariant: identical to Unique of Name stored in tyConName field.L1A named, forall-bound variable (invisible or not)L"an ordinary, visible type argumentLMake a Required TyConBinder. It chooses between NamedTCB and AnonTCB based on whether the tv is mentioned in the dependent setL(mkTyConTy tc) returns (TyConApp tc []) but arranges to share that TyConApp among all calls See Note [Sharing nullary TyConApps] So it's just an alias for tyConNullaryTy!L Create an L from the data constructors, for a potentially levity-polymorphic datatype (with UnliftedDatatypes).L Create an L from the data constructors.Use mkLevPolyDataConRhs if the datatype can be levity-polymorphic or if it comes from a "data type" declarationLExtract those (s that we are able to learn about. Note that visibility in this sense does not correspond to visibility in the context of any particular user program!ȆChecks the invariants of a L/ given the appropriate type class name, if anyLThe name (and defining module) for the Typeable representation (TyCon) of a type constructor.&See Note [Grand plan for Typeable] in GHC.Tc.Instance.Typeable.LThe size of a L in bytes.This applies also when used in a constructor, where we allow packing the fields. For instance, in data Foo = Foo Float# Float# the two fields will take only 8 bytes, which for 64-bit arch will be equal to 1 word. See also mkVirtHeapOffsetsWithPadding for details of how data fields are laid out.L>Like primRepSizeB but assumes pointers/words are 8 words wide.This can be useful to compute the size of a rep as if we were compiling for a 64bit platform.LLike primElemRepSizeB but assumes pointers/words are 8 words wide.This can be useful to compute the size of a rep as if we were compiling for a 64bit platform.LReturn if Rep stands for floating type, returns Nothing for vector types.L-The labels for the fields of this particular Ɇ-The labels for the fields of this particular L(Look up a field label belonging to this ʆMake a map from strings to FieldLabels from all the data constructors of this algebraic tyconL#This is the making of an algebraic .LSimpler specialization of L for classesLMakes a tycon suitable for use during type-checking. It stores a variety of details about the definition of the TyCon, but no right-hand side. It lives only during the type-checking of a mutually-recursive group of tycons; it is then zonked to a proper TyCon in zonkTcTyCon. See Note [TcTyCon, MonoTcTyCon, and PolyTcTyCon] in  GHC.Tc.TyClL5No scoped type variables (to be used with mkTcTyCon).LCreate an primitive  , such as Int#, Type or  RealWorld Primitive TyCons are marshalable iff not lifted. If you'd like to change this, modify marshalablePrimTyCon.LCreate a type synonym LCreate a type family M#Create a promoted data constructor  Somewhat dodgily, we give it the same Name as the data constructor itself; when we pretty-print the TyCon we add a quote; see the Outputable TyCon instanceM Test if the 8 is algebraic but abstract (invisible data constructors)M Does this 7 represent something that cannot be defined in Haskell?MReturns True if the supplied  resulted from either a data or newtype declarationMReturns True9 for vanilla AlgTyCons -- that is, those created with a data or newtype declaration.MReturns True% if a boxed type headed by the given TyCon satisfies condition DTT2 of Note [DataToTag overview] in GHC.Tc.Instance.ClassMReturns True for data types that are  definitely represented by heap-allocated constructors. These are scrutinised by Core-level case: expressions, and they get info tables allocated for them.-Generally, the function will be true for all data types and false for newtype1s, unboxed tuples, unboxed sums and type family &s. But it is not guaranteed to return True in all cases that it could.%NB: for a data type family, only the instance 2s get an info table. The family declaration  does notM Was this  declared as "type data"? See Note [Type data declarations] in GHC.Rename.Module.MM is true of s for which this property holds (where r is the role passed in): If (T a1 b1 c1) ~r (T a2 b2 c2), then (a1 ~r1 a2), (b1 ~r2 b2), and (c1 ~r3 c2) (where r1, r2, and r3, are the roles given by tyConRolesX tc r) See also Note [Decomposing TyConApp equalities] in GHC.Tc.Solver.EqualityMM is true of s for which this property holds (where r is the role passed in): If (T tys ~r t), then (t's head ~r T). See also Note [Decomposing TyConApp equalities] in GHC.Tc.Solver.EqualityNB: at Nominal role, isGenerativeTyCon is simple: isGenerativeTyCon tc Nominal = not (isTypeFamilyTyCon tc || isSynonymTyCon tc)M Is this an L of a  that is generative and injective with respect to representational equality?MTake a  apart into the s it scopes over, the  it expands into, and (possibly) a coercion from the representation type to the newtype . Returns Nothing if this is not possible.M Is this a * representing a regular H98 type synonym (type)?MIs this tycon neither a type family nor a synonym that expands to a type family?MIs this a forgetful type synonym? If this is a type synonym whose RHS does not mention one (or more) of its bound variables, returns True. Thus, False means that all bound variables appear on the RHS; True may not mean anything, as the test to set this flag is conservative."See Note [Forgetful type synonyms]MTrue iff we can decompose (T a b c) into ((T a b) c) I.e. is it injective and generative w.r.t nominal equality? That is, if (T a b) ~N d e f, is it always the case that (T ~N d), (a ~N e) and (b ~N f)? Specifically NOT true of synonyms (open and otherwise)It'd be unusual to call tyConMustBeSaturated on a regular H98 type synonym, because you should probably have expanded it first But regardless, it's not decomposableMIs this an algebraic  declared with the GADT syntax?MIs this an algebraic ( which is just an enumeration of values?M Is this a ., synonym or otherwise, that defines a family?M Is this a >, synonym or otherwise, that defines a family with instances?MIs this a type family  (whether open or closed)?MIs this a data family ?M"Is this an open type family TyCon?M0Is this a non-empty closed type family? Returns K( for abstract or empty closed families.MExtract type variable naming the result of injective type familyMM tc returns L is if tc is an injective tycon (where is states for which L tc is injective), or L otherwise.M%Is this TyCon for an associated type?MGet the enclosing class TyCon (if there is one) for the given TyCon.M Is this the  for a boxed tuple?M Is this the  for an unboxed sum?M T a .... See Note [The stupid context] in GHC.Core.DataCon.M Extract the s bound by a vanilla type synonym and the corresponding (unsubstituted) right hand side.MExtract the information pertaining to the right hand side of a type synonym (type) declaration.MExtract the flavour of a type family (with all the extra information that it carries)MIs this  that for a class instance?MIf this  is that for a class instance, return the class it is for. Otherwise returns NothingM#Return the associated types of the , if anyMIs this ! that for a data family instance?MIf this  is that of a data family instance, return the family in question and the instance types. Otherwise, return NothingMIf this - is that of a data family instance, return a  which represents a coercion identifying the representation type with the type instance family. Otherwise, return NothingM Extract any RuntimeRepInfo from this TyCon͆Can this flavour of  appear unsaturated?MIs this flavour of & an open type family or a data family?MReturns whether or not this  is definite, or a hole that may be filled in at some later point. See Note [Skolem abstract data] L whether the ( has a fixed levityTrue if this is a "type data" declaration See Note [Type data declarations] in GHC.Rename.ModuleLBinders of the  Result kindThe roles for each TyVar>The C type this type corresponds to when using the CAPI FFIStupid theta: see #Information about data constructors0What flavour is it? (e.g. vanilla, type family)Was the  declared with GADT syntax?LResult kind of the %Whether the tuple is boxed or unboxedLKind of the resulting Lresult kind onlyScoped type variables;$Is this TcTyCon generalised already? What sort of  this representsLresult kind Must answer M to isFixedRuntimeRepKind (i.e., no representation polymorphism). (If you need a representation-polymorphic PrimTyCon, change tcHasFixedRuntimeRep, marshalablePrimTyCon, reifyTyCon for PrimTyCons.)Lresult kindLresult kindM Arguments to  Returns a  substitution, the body type of the synonym (not yet substituted) and any arguments remaining from the application ^ Expand a type synonym application Return Nothing if the TyCon is not a synonym, or if not enough arguments are suppliedMMMMMMMMMMMMMMMMMMMLMMMMLLMMMMMLLMMMMMMMMMMMMMMMMLLLLLLLLLLLLLMLLLLLLMLMMMMMMLMLLLLLLLLLLMMMMMMMMMLLMMMMMMMMMLMMLMMLMMMMMMLMML'LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL%%%%%%%%%%%%%%% LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLLLLLL%%%%%%%%%%%%LLLLLLLLLLLLLLLLLLLLLLLLLLLMLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM'MMMMMMMLMLLLLMMMMMMMMMLLLLMMMMMMMMMMMMMMMMMMLMLLLMMLMLLLMMMMLMLLLLLLLLLLLLLLLLLLLLLLLLLLLL%%%LLLLLLLLLLLLLLM M M !M M !M M M M M M M M M M !M M  M  M ! %M M  M  M ! %M  M  M  M " &M ( ,M None,True if there is a non-empty intersection. s1  s2 doesn't compute s2 if s1 is emptyNoneYDeterministic TyCon Environment#See Note [Deterministic UniqFM] in GHC.Types.Unique.DFM( for explanation why we need DTyConEnv.YTyCon Environment&YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY&YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYNoneY Initialise a Y with Y.Y8The default upper bound (100) for the number of times a Y is allowed to encounter each .Y1Change the upper bound for the number of times a Y is allowed to encounter each .YYYYYYYYYYY !GNonel"A collection of s0The key type representing kinds in the compiler./Type synonym used for types of kind RuntimeRep.A type of the form p of constraint kind represents a value whose type is the Haskell predicate p/, where a predicate is what occurs before the => in a Haskell type.We use  as documentation to mark those types that we guarantee to have this kind.0It can be expanded into its representation, but:(The type checker must treat it as opaque1The rest of the compiler treats it as transparentConsider these examples: f :: (Eq a) => a -> Int g :: (?x :: Int -> Int) => a -> Int h :: (r\l) => {r} => {l::Int | r} Here the Eq a and ?x :: Int -> Int and rl are all called "predicates"Mult is a type alias for Type.Mult must contain Type because multiplicity variables are mere type variables (of kind Multiplicity) in Haskell. So the simplest implementation is to make Mult be Type.Multiplicities can be formed with: - One: GHC.Types.One (= oneDataCon) - Many: GHC.Types.Many (= manyDataCon) - Multiplication: GHC.Types.MultMul (= multMulTyCon)So that Mult feels a bit more structured, we provide pattern synonyms and smart constructors for these.&A shorthand for data with an attached  element (the multiplicity).A semantically more meaningful type to represent what may or may not be a useful .For simplicity, we have just one UnivCo that represents a coercion from some type to some other type, with (in general) no restrictions on the type. The UnivCoProvenance specifies more exactly what the coercion really is and why a program should (or shouldn't!) trust the coercion. It is reasonable to consider each constructor of  as a totally independent coercion form; their only commonality is that they don't tell you what types they coercion between. (That info is in the N constructor of .A  is concrete evidence of the equality/convertibility of two types. creates a nullary N$. In general you should rather use F, which picks the shared nullary TyConApp from inside the TyCon (via tyConNullaryTy. But we have to build the TyConApp tc [] in that TyCon field; that's what  is for.Like mkTyCoForAllTy, but does not check the occurrence of the binder See Note [Unused coercion variable in ForAllTy]M.The returned env is used in the extended scopeM>What to do with coercion holes. See Note [Coercion holes] in GHC.Core.TyCo.Rep.MA coercion to be filled in by the type-checker. See Note [Coercion holes]N>See Note [Phantom coercions]. Only in Phantom roled coercionsNFrom the fact that any two coercions are considered equivalent. See Note [ProofIrrelProv]. Can be used in Nominal or Representational coercionsNFrom a plugin, which asserts that this coercion is sound. The string and the variable set are for the use by the plugin.N;See Note [Coercion holes] Only present during typecheckingNA type labeled N might have knot-tied tycons in it. See Note [Type checking recursive type and class declarations] in  GHC.Tc.TyClN;Vanilla type or kind variable (*never* a coercion variable)N+Type application to something other than a  . Parameters:1) Function: must not be a N or N, must be another N, or N See Note [Respecting definitional equality] (EQ1) about the no N requirement2) Argument typeNApplication of a , including newtypes and1 synonyms. Invariant: saturated applications of FunTyCon must use N and saturated synonyms must use their own constructors. However,  unsaturated FunTyCons do appear as Ns. Parameters:%1) Type constructor being applied to.2) Type arguments. Might not have enough type arguments here to saturate the constructor. Even type synonyms are not necessarily saturated; for example unsaturated type synonyms can appear as the right hand side of a type synonym.NA  type. See Note [Why ForAllTy can quantify over a coercion variable] INVARIANT: If the binder is a coercion variable, it must be mentioned in the Type. See Note [Unused coercion variable in ForAllTy]NFUN m t1 t2 Very common, so an important special case See Note [Function types]N/Type literals are similar to type constructors.NA kind cast. The coercion is always nominal. INVARIANT: The cast is never reflexive (EQ2) INVARIANT: The Type is not a CastTy (use TransCo instead) (EQ3) INVARIANT: The Type is not a ForAllTy over a tyvar (EQ4) See Note [Respecting definitional equality]NInjection of a Coercion into a type This should only ever be used in the RHS of an AppTy, in the list of a TyConApp, when applying a promoted GADT data constructorN+Type synonym used for types of kind Levity.N3The key representation of types within the compilerNMake nested arrow types | Special, common, case: Arrow type with mult ManyN/Wraps foralls over the type using the provided s from left to rightN/Wraps foralls over the type using the provided s from left to rightN+A view function that looks through nothing.NApply a function to both the Mult and the Type in a 'Scaled Type'NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN&NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNMMMMMMMMNNNNNNNNNNNNNNNNNN----NNNNNNNNNNNNNNNNNNN----NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN&MMMMMMMNNNNNMNNNNNN N N N N N !N !N %N N !N N N N N 1N N N N N N  N  N NNN OOO ONone Zonk binders, bringing them into scope in the inner computation./Can be thought of as a state monad transformer StateT ZonkEnv m a-, but written in continuation-passing style.2See Note [Continuation-passing style for zonking].A reader monad over 3, for zonking computations which don't modify the ! (e.g. don't bind any variables).Use  when you need to modify the  (e.g. to bind a variable).How should we handle unfilled unification variables in the zonker?+See Note [Un-unified unification variables],Default unbound unification variables to AnySkolemise unbound unification variables See Note [Zonking the LHS of a RULE]Used in the GHCi debuggerPanic on unfilled meta-variables See Note [Error on unconstrained meta-variables] in GHC.Tc.Utils.TcMTypeSee Note [The ZonkEnv]ǩ+Zonk some binders and run the continuation.Example: zonk (ForAllTy (Bndr tv vis) body_ty) = runZonkBndrT (zonkTyBndrX tv) $ \ tv' -> do { body_ty' <- zonkTcTypeToTypeX body_ty ; return (ForAllTy (Bndr tv' vis) body_ty') }2See Note [Continuation-passing style for zonking].ȩ,Embed a computation that doesn't modify the  into .ɩ+Run a nested computation that modifies the +, without affecting the outer environment.̩!Extend the knot-tied environment.ɩΩ̩ϩͩ˩ʩȩǩЩũé©ĩƩũé©ĩ˩ʩƩƩǩȩɩЩͩΩ̩ϩ ѩ ҩ *ө ԩ (թ $֩ 0ש (ة ٩!ک#(۩*1ܩ3;NoneԯǰȰۭܱ֯ڱְɱĮðӭڮ֭ذŰүӰձۮ֮ݯϭЭɮʮůʯװέ˭ͭˮٰկڰܰ۰ԭӯűگӱʰɰܮޮݮƱ׭ٱѯЯŮޱȮױƯϱͱ˱ΰϰͰհޯǭĭݰư°ҭ߭ޭ٭԰ʭݭ׮ϯۯֱбDZٮحׯدٯ̭ұα̱ʱӮҮ̮ͮѮԮծήϮЮխݱñ±ɭƭ߯ȭͯ˯̯ί߰ѱڭ߮į¯˰̰ܭǮްƮԱ۱ȱ­íŭаîïخȯǯɯر®ܯѭҰѰ߱İı­íĭŭƭǭȭɭʭ˭̭ͭέϭЭѭҭӭԭխ֭׭ح٭ڭۭܭݭޭ߭®îĮŮƮǮȮɮʮˮ̮ͮήϮЮѮҮӮԮծ֮׮خٮڮۮܮݮޮ߮¯ïįůƯǯȯɯʯ˯̯ͯίϯЯѯүӯԯկ֯ׯدٯگۯܯݯޯ߯°ðİŰưǰȰɰʰ˰̰ͰΰϰаѰҰӰ԰հְװذٰڰ۰ܰݰް߰±ñıűƱDZȱɱʱ˱̱ͱαϱбѱұӱԱձֱױرٱڱ۱ܱݱޱ߱NoneΆCreate a primitive  with the given , arguments of kind Type with the given  -s, and the given result kind representation.Only use this in GHC.Builtin.Types.Prim.φCreate a primitive nullary  with the given ! and result kind representation.Only use this in GHC.Builtin.Types.Prim.ІCreate a primitive  like Ά, except the last argument is levity-polymorphic, where the levity argument is implicit and comes before other argumentsOnly use this in GHC.Builtin.Types.Prim.O Primitive s that are defined in GHC.Prim but not "exposed". See Note [Unexposed TyCons]O Primitive 3s that are defined in, and exported from, GHC.Prim.OThe FUN type constructor. FUN :: forall (m :: Multiplicity) -> forall {rep1 :: RuntimeRep} {rep2 :: RuntimeRep}. TYPE rep1 -> TYPE rep2 -> Type The runtime representations quantification is left inferred. This means they cannot be specified with -XTypeApplications.This is a deliberate choice to allow future extensions to the function arrow.PGiven a Role, what TyCon is the type of equality predicates at that role?Іroles of the arguments (must be non-empty), not including the implicit argument of kind %, which always has   role(representation of the fully-applied typeOOOOOOOOOOOOOOPPPOOOPPOOOOOOOOPPOOOOOOOOPPPPPPPPPPOOOOOOPPPPPPOOOOOOOPPPPPPOOOPPPPPPOOOPPPPPPOOOPPPPPPOOOPOOOOOOOOOOOOOPPPPPPPPPPPPPOPOOOOOOOOOPOOPPPOOOOOOOOOOPPPPPOOOOOOOOOPPPPPPOPOOOOOPPOPOOOPPPPPPOOOPPPPPPOOOPPPPPPOOOPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP NonePReturns free variables of types, including kind variables as a non-deterministic set. For type synonyms it does not expand the synonym.цGiven a list of tyvars returns a deterministic FV computation that returns the given tyvars with the kind variables free in the kinds of the given tyvars.PAdd the kind variables free in the kinds of the tyvars in the given set. Returns a deterministically ordered list.PAdd the kind variables free in the kinds of the tyvars in the given set. Returns a deterministic set.PQ that returns free variables of a type in a deterministic set. For explanation of why using .6 is not deterministic see Note [Deterministic FV] in  GHC.Utils.FV.PQ that returns free variables of a type in deterministic order. For explanation of why using .6 is not deterministic see Note [Deterministic FV] in  GHC.Utils.FV.QReturns free variables of types, including kind variables as a deterministic set. For type synonyms it does not expand the synonym.QReturns free variables of types, including kind variables as a deterministically ordered list. For type synonyms it does not expand the synonym.QThe worker for Q and tyCoFVsOfTypeList$. The previous implementation used . which is O(n+m) and can make the function quadratic. It's exported, so that it can be composed with other functions that compute free variables. See Note [FV naming conventions] in  GHC.Utils.FV.Eta-expanded because that makes it run faster (apparently) See Note [FV eta expansion] in  GHC.Utils.FV for explanation.Q6Get a deterministic set of the vars free in a coercionQGiven a covar and a coercion, returns True if covar is almost devoid in the coercion. That is, covar can only appear in Refl and GRefl. See (FC6) in Note [ForAllCo] in GHC.Core.TyCo.RepQRetrieve the free variables in this type, splitting them based on whether they are used visibly or invisibly. Invisible ones come first.Q Returns the free variables of a  that are in injective positions. Specifically, it finds the free variables while:Expanding type synonymsIgnoring the coercion in  (ty |> co)'Ignoring the non-injective fields of a NFor example, if F& is a non-injective type family, then: 9injectiveTyVarsOf( Either c (Maybe (a, F b c)) ) = {a,c} If Q ty = itvs, then knowing ty fixes itvs. More formally, if a is in Q ty and S1(ty) ~ S2(ty), then S1(a) ~ S2(a) , where S1 and S2 are arbitrary substitutions.See Note [When does a tycon application need an explicit kind signature?].Q Returns the free variables of a  that are in injective positions. Specifically, it finds the free variables while:Expanding type synonymsIgnoring the coercion in  (ty |> co)'Ignoring the non-injective fields of a NSee Note [When does a tycon application need an explicit kind signature?].QReturns the set of variables that are used invisibly anywhere within the given type. A variable will be included even if it is used both visibly and invisibly. An invisible use site includes: * In the kind of a variable * In the kind of a bound variable in a forall * In a coercion * In a Specified or Inferred argument to a function See Note [VarBndrs, ForAllTyBinders, TyConBinders, and visibility] in GHC.Core.TyCo.RepQLike Q, but for many types.QDo a topological sort on a list of tyvars, so that binders occur before occurrences E.g. given [ a::k, k::*, b::k ] it'll return a well-scoped list [ k::*, a::k, b::k ]This is a deterministic sorting operation (that is, doesn't depend on Uniques).It is also meant to be stable: that is, variables should not be reordered unnecessarily. This is specified in Note [ScopedSort] See also Note [Ordering of implicit variables] in GHC.Rename.HsTypeQ+Get the free vars of a type in scoped orderQ*Get the free vars of types in scoped orderQAll type constructors occurring in the type; looking through type synonyms, but not newtypes. When it finds a Class, it returns the class TyCon.QShould we look under injective type families? See Note [Coverage condition for injective type families] in GHC.Tc.Instance.Family.Qlook under injective type families? See Note [Coverage condition for injective type families] in GHC.Tc.Instance.Family.:QQQQPPPPPPPPPPQQQQQQ/QQPQPPPPPPQQQQQQQPQQPP/PPQPQQQQQQQ:PP/PPQQQQQPQQPPPPPPPPPPPPQQQQPPQQQQQQQQQ/QQQQQQQQQQPPPPNoneQThis tidies up a type for printing in an error message, or in an interface file.;It doesn't change the uniques at all, just the print names.Q Add the free s to the env in tidy form, so that we can tidy the type they are free in Precondition: input free vars are closed over kinds and This function does a scopedSort, so that tidied variables have tidied kinds. See Note [Tidying is idempotent]R Treat a new  as a binder, and give it a fresh tidy name using the environment if one has not already been allocated. See also Q" See Note [Tidying is idempotent]RTidy a list of Types-See Note [Strictness in tidyType and friends]R Tidy a Type-See Note [Strictness in tidyType and friends]R:Grabs the free type variables, tidies them and then uses R to work over the type itselfRCalls R= on a top-level type (i.e. with an empty tidying environment)RTidy a Coercion-See Note [Strictness in tidyType and friends]QRRRQQRQQRRRRRRRRQQRRRRRRRRRQRQRQQQQQRNone.QA substitution of s for -sQA substitution of s for s and s for -sQA substitution of Exprs for non-coercion sQ!Type & coercion & id substitutionThe Subst data type defined in this module contains substitution for tyvar, covar and id. However, operations on IdSubstEnv (mapping from Id to CoreExpr%) that require the definition of the Expr data type are defined in GHC.Core.Subst to avoid circular module dependency.QComposes two substitutions, applying the second one provided first, like in function composition. This function leaves IdSubstEnv untouched because IdSubstEnv is not used during substitution for types.QChecks whether the tyvar and covar environments are empty. This function should be used over Q when substituting for types, because types currently do not contain expressions; we can safely disregard the expression environment when deciding whether to skip a substitution. Using Q gives us a non-trivial performance boost (up to 70% less allocation for T18223)QMake a TCvSubst with specified tyvar subst and empty covar substQMake a TCvSubst with specified covar subst and empty tyvar substQWhat to do with coercion holes. See Note [Coercion holes] in GHC.Core.TyCo.Rep.R Iterates . until there is no more to synonym to expand. NB: coreFullView is non-recursive and can be inlined; core_full_view is the recursive one See Note [Inlining coreView].ֆ Iterates . until there is no more to synonym to expand. NB: coreFullView is non-recursive and can be inlined; core_full_view is the recursive one See Note [Inlining coreView].RexpandSynTyConApp_maybe tc tys! expands the RHS of type synonym tc instantiated at arguments tys , or returns K if tc is not a synonym.׆ A helper for R3 to avoid inlining this cold path into call-sites.Precondition: the call is saturated or over-saturated; i.e. length tvs <= length arg_tysRExpand out all type synonyms. Actually, it'd suffice to expand out just the ones that discard type variables (e.g. type Funny a = Int) But we don't know which those are currently, so we just expand all.R only expands out type synonyms mentioned in the type, not in the kinds of any TyCon or TyVar mentioned in the type.Keep this synchronized with synonymTyConsOfType؆&An INLINE helper for function such as R below.isTyConKeyApp_maybe key ty returns Just tys iff the type  ty = T tys*, where T's unique = key key must not be @; to test for functions, use R:. Thanks to this fact, we don't have to pattern match on N here.RExtract the RuntimeRep classifier of a type from its kind. For example, kindRep * = LiftedRep; Panics if this is not possible. Treats * and Constraint as the sameRGiven a kind (TYPE rr) or (CONSTRAINT rr), extract its RuntimeRep classifier rr. For example,  kindRep_maybe * = Just LiftedRep Returns K% if the kind is not of form (TYPE rr)R9Returns True if the kind classifies unlifted types (like 'Int#') and False otherwise. Note that this returns False for representation-polymorphic kinds, which may be specialized to a kind that classifies unlifted types.RCheck whether a kind is of the form `TYPE (BoxedRep Lifted)` or `TYPE (BoxedRep Unlifted)`.Returns:/`Just Lifted` for `TYPE (BoxedRep Lifted)` and ,3`Just Unlifted` for `TYPE (BoxedRep Unlifted)` and  UnliftedType,K for anything else, e.g. `TYPE IntRep`, `TYPE (BoxedRep l)`, etc.RCheck whether a type of kind L is lifted.R is:True of LiftedRep :: RuntimeRepFalse of type variables, type family applications, and of other reps such as IntRep :: RuntimeRep.RCheck whether a type of kind L is unlifted.True of definitely unlifted Ls such as  UnliftedRep, L, L, ... False of  LiftedRep,6False for type variables and type family applications.ن'An INLINE helper for functions such as R and R.%Checks whether the type is a nullary  application, for a  with the given .RIs a tyvar of type L?RIs a tyvar of type %?RIs a tyvar of type  Multiplicity?R(splitRuntimeRep_maybe rr) takes a Type rr :: RuntimeRep, and returns the (TyCon,[Type]) for the RuntimeRep, if possible, where the TyCon is one of the promoted DataCons of RuntimeRep. Remember: the unique on TyCon that is a a promoted DataCon is the same as the unique on the DataCon See Note [Promoted data constructors] in GHC.Core.TyCon May not be possible if rr1 is a type variable or type family applicationRSee چ.چ`isBoxedRuntimeRep_maybe (rep :: RuntimeRep)` returns `Just lev` if rep% expands to `Boxed lev` and returns K otherwise.Types with this runtime rep are represented by pointers on the GC'd heap.R&Check whether a type (usually of kind L) is lifted, unlifted, or unknown. Returns Nothing if the type isn't of kind L.$`runtimeRepLevity_maybe rr` returns:`Just Lifted` if rr is `LiftedRep :: RuntimeRep``Just Unlifted` if rr is definitely unlifted, e.g. LK if not known (e.g. it's a type variable or a type family application).RR takes a Type of kind Levity, and returns its levity May not be possible for a type variable or type family applicationR2Attempts to obtain the type variable underlying a , and panics with the given message if this is not a type variable type. See also .R2Attempts to obtain the type variable underlying a , without any expansionRIf the type is a tyvar, possibly under a cast, returns it, along with the coercion. Thus, the co is :: kind tv ~N kind tyRAttempt to take a type application apart, whether it is a function, type constructor, or plain type application. Note that type family applications are NEVER unsaturated by this!R1Attempts to take a type application apart, as in R%, and panics if this is not possibleRDoes the AppTy split as in R6, but assumes that any coreView stuff is already doneRJust like splitAppTyNoView_maybe, but does not split (c => t) See Note [Decomposing fat arrow c=>t]RRecursively splits a type as far as is possible, leaving a residual type being applied to and the type arguments applied to it. Never fails, even if that means returning an empty list of type applications.RLike R(, but doesn't look through type synonymsR>Is this a numeric literal. We also look through type synonyms.R=Is this a symbol literal. We also look through type synonyms.R;Is this a char literal? We also look through type synonyms.R2Is this a type literal (symbol, numeric, or char)?RIs this type a custom user error? If so, give us the error message.R=Render a type corresponding to a user type error into a SDoc.RGiven the components of a FunTy figure out the corresponding TyConApp.R=Return Just if this TyConApp should be represented as a FunTyR?Return Just if this TyConAppCo should be represented as a FunCoRThis one works out the FunTyFlag from the argument type See GHC.Types.Var Note [FunTyFlag]R=Like mkFunctionType, compute the FunTyFlag from the argumentsRAttempts to extract the multiplicity, argument and result types from a type, and panics if that is not possible. See also RRAttempts to extract the multiplicity, argument and result types from a typeRExtract the function result type and panic if that is not possibleRExtract the function argument type and panic if that is not possible Just like R/ but for a single argument Try not to iterate ., because it's inefficient to substitute one variable at a time; instead use 'piResultTys"R(piResultTys f_ty [ty1, .., tyn]) gives the type of (f ty1 .. tyn) where f :: f_ty R" is interesting because: 1. f_ty may have more for-alls than there are args 2. Less obviously, it may have fewer for-alls For case 2. think of: piResultTys (forall a.a) [forall b.b, Int] This really can happen, but only (I think) in situations involving undefined. For example: undefined :: forall a. a Term: undefined (forall b. b->b) Int This term should have type (Int -> Int), but notice that there are more type args than foralls in ks type.R), as that's not a TyCon in the type-checker.Note that this may fail (in funTyConAppTy_maybe) in the case of a N" with an argument of unknown kind N0 (e.g. `FunTy (a :: k) Int`, since the kind of a isn't of the form `TYPE rep`. This isn't usually a problem but may be temporarily the case during canonicalization: see Note [Decomposing FunTy] in GHC.Tc.Solver.Equality and Note [The Purely Kinded Type Invariant (PKTI)] in GHC.Tc.Gen.HsType, Wrinkle around FunTyConsequently, you may need to zonk your type before using this function.R Unwrap one layer of newtype on a type constructor and its arguments, using an eta-reduced version of the newtype2 if possible. This requires tys to have at least newTyConInstArity tycon elements.ۆLike ., but avoids checking the coercion for reflexivity, as that can be expensive.R&Make a dependent forall over a TyCoVarR&Make a dependent forall over a TyCoVarR Make a dependent forall over an  variableRLike R, but tv should be a tyvarRLike N/, but assumes all variables are dependent and , a common caseRLike R#, but tvs should be a list of tyvarRLike ,, but assumes the variable is dependent and , a common caseRLike N/, but assumes all variables are dependent and , a common caseRLike mkForAllTys, but assumes all variables are dependent and visibleRGiven a list of type-level vars and the free vars of a result kind, makes PiTyBinders, preferring anonymous binders if the variable is, in fact, not dependent. e.g. mkTyConBindersPreferAnon  k->k(k:*),(b:k),(c:k)- We want (k:*) Named, (b:k) Anon, (c:k) AnonAll non-coercion binders are visible.R b -> IO b` will not be considered a function by this function. It would merely be a forall wrapping a function type.R Bool -> Double) == [(Int, FTF_T_T), (Bool, FTF_T_T)] getRuntimeArgTys (Identity Int -> Bool -> Double) == [(Identity Int, FTF_T_T), (Bool, FTF_T_T)] getRuntimeArgTys (Int -> Identity (Bool -> Identity Double)) == [(Int, FTF_T_T), (Bool, FTF_T_T)] getRuntimeArgTys (forall a. Show a => Identity a -> a -> Int -> Bool) == [(Show a, FTF_C_T), (Identity a, FTF_T_T),(a, FTF_T_T),(Int, FTF_T_T)] Note that, in the last case, the returned types might mention an out-of-scope type variable. This function is used only when we really care about the kinds' of the returned types, so this is OK.*Warning**: this function can return an infinite list. For example:  newtype N a = MkN (a -> N a) getRuntimeArgTys (N a) == repeat (a, FTF_T_T) RLike R, but returns only *invisible* binders, including constraints. Stops at the first visible binder.RSame as R$, but stop when - you have found n -+s, - or you run out of invisible bindersRGiven a  and a list of argument types, filter out any invisible (i.e.,  or  ) arguments.RGiven a . and a list of argument types, filter out any  arguments.RGiven a list of things paired with their visibilities, partition the things into (invisible things, visible things).RGiven a + and a list of argument types to which the 5 is applied, determine each argument's visibility (, , or ).)Wrinkle: consider the following scenario: T :: forall k. k -> k tyConForAllTyFlags T [forall m. m -> m -> m, S, R, Q]After substituting, we get T (forall m. m -> m -> m) :: (forall m. m -> m -> m) -> forall n. n -> n -> n'Thus, the first argument is invisible, S is visible, R is invisible again, and Q is visible.RGiven a + and a list of argument types to which the 5 is applied, determine each argument's visibility (, , or ).(Most of the time, the arguments will be , but not always. Consider f :: forall a. a -> Type. In  f Type Bool, the first argument (Type) is  and the second argument (Bool) is ?. It is precisely this sort of higher-rank situation in which R comes in handy, since  f Type Bool$ would be represented in Core using Ns. (See also #15792).܆Given a function kind and a list of argument types (where each argument's kind aligns with the corresponding position in the argument kind), determine each argument's visibility (, , or ).SGiven a family instance TyCon and its arg types, return the corresponding family type. E.g: 1data family T a data instance T (Maybe b) = MkT b%Where the instance tycon is :RTL, so: +mkFamilyTyConApp :RTL Int = T (Maybe Int)SGet the type on the LHS of a coercion induced by a type/data family instance.STries to compute the %/ of the given type. Returns either a definite %, or K if we aren't sure (e.g. the type is representation-polymorphic).+Panics if the kind does not have the shape TYPE r.S,Is the given type definitely unlifted? See Type#type_classification for what an unlifted type is.0Panics on representation-polymorphic types; See S for a more approximate predicate that behaves better in the presence of representation polymorphism.SReturns:J if the type is  guaranteed unlifted orM if it lifted, OR we aren't sure (e.g. in a representation-polymorphic case)SReturns:J if the type is  guaranteed lifted orM if it is unlifted, OR we aren't sure (e.g. in a representation-polymorphic case)SSee Type#type_classification for what a boxed type is. Panics on representation-polymorphic types; See S for a more approximate predicate that behaves better in the presence of representation polymorphism.S3Is this a type of kind RuntimeRep? (e.g. LiftedRep)S+Drops prefix of RuntimeRep constructors in Ns. Useful for e.g. dropping 'LiftedRep arguments of unboxed tuple TyCon applications:dropRuntimeRepArgs [ 'LiftedRep, 'IntRep , String, Int# ] == [String, Int#]݆ Int then j could be a binary join point returning an Int, but it could *not* be a unary join point returning a -> Int.4TODO: See Note [Excess polymorphism and join points]SDoes this classify a type allowed to have values? Responds True to things like *, TYPE Lifted, TYPE IntRep, TYPE v, Constraint.)True of a kind `TYPE _` or `CONSTRAINT _`SIs this kind equivalent to  i.e. TYPE LiftedRep?SIs this kind equivalent to TYPE (BoxedRep l) for some  l :: Levity?SIs this kind equivalent to TYPE r (for some unknown r)?This considers  Constraint to be distinct from *.SReturns True if a type has a syntactically fixed runtime rep, as per Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.This function is equivalent to `isFixedRuntimeRepKind . typeKind` but much faster. Precondition: The type has kind (TYPE blah)SChecks that a kind of the form ,  Constraint or 'TYPE r is concrete. See S. Precondition:3 The type has kind `TYPE blah` or `CONSTRAINT blah`STests whether the given type is concrete, i.e. it whether it consists only of concrete type constructors, concrete type variables, and applications.3See Note [Concrete types] in GHC.Tc.Utils.Concrete.SDoes a  (that is applied to some number of arguments) need to be ascribed with an explicit kind signature to resolve ambiguity if rendered as a source-syntax type? (See Note [When does a tycon application need an explicit kind signature?]; for a full explanation of what this function checks for.)SScale a payload by ManySScale a payload by OneS8Scale a payload by Many; used for type arguments in coreS isLinear t returns True of a if t is a type of (curried) function where at least one argument is linear (or otherwise non-unrestricted). We use this function to check whether it is safe to eta reduce an Id in CorePrep. It is always safe to return M , because M deactivates the optimisation.SGiven a  RuntimeRep , applies TYPE to it. On the fly it rewrites TYPE LiftedRep --> liftedTypeKind (a synonym) TYPE UnliftedRep --> unliftedTypeKind (ditto) TYPE ZeroBitRep --> zeroBitTypeKind (ditto) NB: no need to check for TYPE (BoxedRep Lifted), TYPE (BoxedRep Unlifted) because those inner types should already have been rewritten to LiftedRep and UnliftedRep respectively, by mkTyConAppsee Note [TYPE and CONSTRAINT] in GHC.Builtin.Types.Prim. See Note [Using synonyms to compress types] in GHC.Core.TypeSJust like mkTYPEappSJust like mkTYPEapp_maybeSGiven a %, apply L to it On the fly, rewrite BoxedRep Lifted --> liftedRepTy (a synonym) BoxedRep Unlifted --> unliftedRepTy (ditto) See Note [TYPE and CONSTRAINT] in GHC.Builtin.Types.Prim. See Note [Using synonyms to compress types] in GHC.Core.TypeSGiven a `[RuntimeRep]`, apply TupleRep to it On the fly, rewrite TupleRep [] -> zeroBitRepTy (a synonym) See Note [TYPE and CONSTRAINT] in GHC.Builtin.Types.Prim. See Note [Using synonyms to compress types] in GHC.Core.Type׆"the variables bound by the synonymthe RHS of the synonym2the type arguments the synonym is instantiated at.Rbindersfree variables of resultSresult kindSShould specified binders count towards injective positions in the kind of the TyCon? (If you're using visible kind applications, then you want True here.The number of args the  is applied to.Does  T t_1 ... t_n need a kind signature? (Where n is the number of arguments)))OQQPPPPP/QQQQQQ/PQPQQNNNNNNNNNNNNNNNNNNNQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRQQRRRRRRRRQQLRRRRS.SR.RSSRSRRRRRRRR.RSR.RSSSRSR.RSSSSSSRRRRR.RRR.SRS.RRSR.SS.RRSSSSRSSSRRSRSRRRRSRRSS.RSSS.R.SRRRRSRRRRSSSRRRR.RRR.R.RRRRS.RSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRR.RSSRRRRRRRSRR.RRSSS.SSS.SR---------.---------NNNMMMMMMMQQQQRRRRRRRR------------NN.---NNNR.RR--.RRRRRRRNNNNNNNNNNRRRRRRORRRR..L.RRRR.RRRRNNRRRRRRRRRRRRRRRRRRRRRRRRNN.RRRSSRRRRRRR.SRRR.R..RRRRRSRRRRRR.RRRRRRRRRRRRMMMMMMMNNR-----------------RRR.RRRRRRSSSSSSSSSSSSS.SSS.RRRRRRRRSSSSRSSSSSSSSS.R.RSS.RSSSSSSRRSSS.SSSSSSS))QQQQ/PPPPQQ/RRNQPPPQQQSS.R.QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRQQQRQRRQQSSSNone ?SOverloaded Literal ValueSInteger-looking literals;SFrac-looking literalsSString-looking literalsSHaskell Overloaded LiteralSHaskell LiteralS CharacterSUnboxed characterSStringSStringS Packed bytesSGenuinely an Int; arises from GHC.Tc.Deriv.Generate, and from TRANSLATIONSliteral Int#Sliteral Word#Sliteral Int8#Sliteral Int16#Sliteral Int32#Sliteral Int64#Sliteral Word8#Sliteral Word16#Sliteral Word32#Sliteral Word64#SGenuinely an integer; arises only from TRANSLATION (overloaded literals are done with HsOverLit)SGenuinely a rational; arises only from TRANSLATION (overloaded literals are done with HsOverLit)S Unboxed FloatSUnboxed DoubleSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS S S S None 3!%PatternSHaskell Field BindingSNote [Punning]S!Filled in by renamer when punningSHaskell Record Update FieldS#Located Haskell Record Update FieldSHaskell Record FieldSLocated Haskell Record FieldSLocated Haskell Record FieldSNewtype to be able to have a specific XRec instance for the Int in SSHaskell Record FieldsHsRecFields is used only for patterns and expressions (not data type declarations)S#Haskell Constructor Pattern DetailsS9Type argument in a data constructor pattern, e.g. the @a in f (Just @a x) = ....SWildcard Pattern, i.e. _SVariable Pattern, e.g. xSLazy Pattern, e.g. ~xSAs pattern, e.g. x@patSParenthesised pattern, e.g. (x)SBang pattern, e.g. !xSSyntactic List, e.g. [x] or [x,y] . Note that [] and (x:xs)% patterns are both represented using S.STuple pattern, e.g. (x, y) (boxed tuples) or  (# x, y #) (requires -XUnboxedTuples)Sghc Or Pattern, e.g. (pat_1; ...; pat_n) . Used by  -XOrPatternsSAnonymous sum pattern, e.g.  (# x | #) . Used by  -XUnboxedSumsSConstructor Pattern, e.g. (), [] or NothingSView Pattern, e.g. someFun -> pat . Used by -XViewPatternsTSplice Pattern, e.g. $(pat)TLiteral Pattern Used for non-overloaded8 literal patterns: Int#, Char#, Int, Char, String, etc.TNatural Pattern, used for all overloaded literals, including overloaded Strings with -XOverloadedStringsTn+k pattern, e.g. n+1 , used by -XNPlusKPatternsT$Pattern with a type signature, e.g. x :: IntT.Embed the syntax of types into patterns, e.g. fn (type t) = rhs. Enabled by -XExplicitNamespaces in conjunction with -XRequiredTypeArguments.TType abstraction which brings into scope type variables associated with invisible forall. E.g. fn @t ... = rhs . Used by -XTypeAbstractions.TTTG Extension point; see Note [Trees That Grow] in Language.Haskell.Syntax.ExtensionS;After typechecking, holds the types of the tuple componentsTuple sub-patterns9TTTTTTTSSSSSSSSSSSSSSSSSSSS%%SSSTTSSTTTSSTTSSSSSTTTTSSSSS9%SSSTTSSTTTSSTTSSSSSTTTT%STTSTTSSSSSSSSSSSSSSSSSSSSSSSTTTTT T"-TTTNone !+3`%Located Haskell Expression%Syntax ExpressionSyntaxExpr is represents the function used in interpreting rebindable syntax. In the parser, we have no information to supply; in the renamer, we have the name of the function (but see Note [Monad fail : Rebindable syntax, overloaded strings] for a wrinkle) and in the type-checker we have a more elaborate structure  SyntaxExprTc.In some contexts, rebindable syntax is not implemented, and so we have constructors to represent that possibility in both the renamer and typechecker instantiations.E.g. (>>=)4 is filled in before the renamer by the appropriate Name for (>>=), and then instantiated by the type checker with its type args etc%Guarded Right-Hand Sides8GRHSs are used both for pattern bindings and for Matches%Haskell Splice%A Haskell expression.T  ModuleName. do { ... }T  ModuleName.'mdo { ... } ie recursive do-expressionT&A command-line Stmt in GHCi pat <- rhsTHaskell arrow match context.TA proc expressionT(A case alternative inside arrow notationT3A , case or cases alternative inside arrow notationTHaskell Statement Context.T1Context for HsDo (do-notation and comprehensions)T!Pattern guard for specified thingTA branch of a parallel stmtTA branch of a transform stmtT'do-notation in an arrow-command contextTHaskell Match ContextContext of a pattern match. This is more subtle than it would seem. See Note [FunBind vs PatBind].T8A pattern matching on an argument of a function bindingT)Patterns and guards in a case alternativeTPatterns and guards in @, case and cases@T$Guards of a multi-way if alternativeT%A pattern match inside arrow notationT"A pattern binding eg [y] <- e = eTGuards of pattern bindings, e.g., (Just b) | Just _ <- x = e | otherwise = e'TRecord update [used only in GHC.HsToCore.Expr to tell matchWrapper what sort of runtime error message to generate]T>Pattern of a do-stmt, list comprehension, pattern guard, etcT!A Template Haskell pattern spliceT1A Template Haskell pattern quotation [p| (a,b) |]TA pattern synonym declarationTAn irrefutable patternTwas f' banged? See Note [FunBind vs PatBind]T fixing of fTfunction binder of f See Note [mc_fun field of FunRhs] See #20415 for a long discussion about this fieldTArithmetic Sequence InformationT1Haskell (Untyped) Quote = Expr + Pat + Type + VarTThe fail operatorThis is used for `.. <-` "bind statements" in do notation, including non-monadic "binds" in applicative.The fail operator is 'Just expr' if it potentially fail monadically. if the pattern match cannot fail, or shouldn't fail monadically (regular incomplete pattern exception), it is K.See Note [Monad fail : Rebindable syntax, overloaded strings] for the type of expression in the L case, and why it is so.See Note [Failing pattern matches in Stmts] for which contexts for 'BindStmt3's should use the monadic fail and which shouldn't.TParenthesised Statement BlockTGhci StatementTGhci Located StatementTGuard StatementTGuard Located StatementTExpression StatementTExpression Located StatementTCommand StatementTCommand Located StatementTdo block StatementT3Located Statement with separate Left and Right id'sTLocated do block StatementTGuarded Right Hand Side.TLocated Guarded Right-Hand SideTThe where clauseT Guarded RHSsU Located MatchUHaskell Record BindingsUHaskell Top-level CommandUTop-level command, introducing a new arrow. This may occur inside a proc (where the stack is empty) or as an argument of a command-forming operator.!Located Haskell Top-level CommandUHaskell arrow application type.UFirst order arrow application - e`U`case pi -> ei `U`cases psi -> ei`UHaskell Tuple ArgumentU The argumentU-The argument is missing, but this is its typeUExtension point; see Note [Trees That Grow] in Language.Haskell.Syntax.ExtensionULocated Haskell Tuple ArgumentU is used for tuple sections (,a,) is represented by 3ExplicitTuple [Missing ty1, Present a, Missing ty3] Which in turn stands for (x:ty1 y:ty2. (x,a,y))UA pragma, written as {-# ... #-}, that may appear within an expression.U%Variable See Note [Located RdrNames]UUnbound variable; also used for "holes" (_ or _x). Turned from HsVar to HsUnboundVar by the renamer, when it finds an out-of-scope variable or hole. The (XUnboundVar p) field becomes an HoleExprRef after typechecking; this is where the erroring expression will be written after solving. See Note [Holes] in GHC.Tc.Types.Constraint.UOverloaded label (Note [Overloaded labels] in GHC.OverloadedLabels)U2Implicit parameter (not in use after typechecking)UOverloaded literalsU Simple (non-overloaded) literalsU%Lambda, Lambda-case, and Lambda-casesU ApplicationUVisible type applicationExplicit type argument; e.g f @Int x y NB: Has wildcards, but no implicit quantificationUOperator applications: NB Bracketed ops such as (+) come out as Vars.UNegation operator. Contains the negated expression and the name of negateU.Parenthesised expr; see Note [Parens in HsSyn]U-Used for explicit tuples and sections thereofUUsed for unboxed sum typesU Multi-way ifUlet(rec)USyntactic list: [a,b,c,...]URecord constructionU Record updateURecord field selection e.g z.x.URecord field selector. e.g. (.x) or (.x.y)This case only arises when the OverloadedRecordDot langauge extensions is enabled. See Note [Record selectors in the AST].U,Expression with an explicit type signature.  e :: typeUArithmetic sequenceUproc notation for ArrowsU Forall-types  forall tvs. t and forall tvs -> t . Used with RequiredTypeArguments, e.g. fn (forall a. Proxy a). See Note [Types in terms]UFunction types a -> b . Used with RequiredTypeArguments, e.g. fn (Int -> Bool). See Note [Types in terms]UHaskell Record Update Fields.U)A regular (non-overloaded) record update.UAn overloaded record update.URecordDotSyntax field updatesUIs this a monadic context?TPost renaming has optional fail and bind / (>>=) operator. Post typechecking, also has multiplicity of the argument and the result type of the function passed to bind; that is, (P, S) in (>>=) :: Q -> (R % P -> S) -> T See Note [The type of bind in Stmts]U0Tells whether this is for lambda, case, or casesLamSingle: one match of arity >= 1 LamCase: many arity-1 matches LamCases: many matches of uniform arity >= 1UUUUUUUUUTTTTTTTUUUUUTTTUUTTT%TTTTTTTTTUUUTTTTUUUUUUUUUUUUUU%TTTTT%UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTUUUTTTTTTTTUTTTTTTUUUU%TTTUTUU%UUUUUUUUUUUTTTTUUUUU%UUUUTTTUUTTTTTTTTTTTTTTTTTTTTTTTTTT%TTTUUUUUUUUUUUUUU%%%UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU%UUUUUTTUUUUUU%TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT%TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT%TTTTTUUUUUUUUU U  U UU UNone VHaskell ModuleAll we actually declare here is the top-level structure for a module.V1Type, class, value, and interface signature declsV Export listNothing+: export list omitted, so export everythingJust [] : export nothing Just [...]: as you would expect...VNothing: "module X where" is omitted (in which case the next field is Nothing too)VHsModule extension point 877878777;;;;;;;;;;;;;;;;;;;;;UUUUUUUUU TTTTTTT77777777%77VVVVVVVV 777777777777777777777777777777777777777777777777777777777777777777777777777777777778888888999999999999999::::::::::::::::::999999999::::99999999999999999999999999::::::::::::::::::::9999999999999999:::99999:::::::::;;;;;;;;;;;;;;;;:::::::9:::::::;:::;;;::::9999999999989:99:999::9;:::98999:::99989:::8889999999999999999999::::::::::::::::::::::::::::::::::::::::999999988888898999TTTTTTTUUUUUTTTUUTTT%TTTTTTTTTUUUTTTTUUUUUUUUUUUUUU%TTTTT%UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTUUUTTTTTTTTUTTTTTTUUUU%TTTUTUU%UUUUUUUUUUUTTTTUUUUU%UUUUTTTUUTTTTTTTTTTTTTTTTTTTTTTTTTT%TTT 88888888888888888888888888888888888888888SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS%%SSSTTSSTTTSSTTSSSSSTTTTSSSSS7666666655555566566666666666666666666666777777777667666666666666666666666666666666666666666666666666666666666666666666666666666676577777776667756%%%56666666656556666 VVVVVVVVNone 35VGoverns the kind of expression that the tick gets placed on when annotating for example using mkTick. If we find that we want to put a tickish on an expression ruled out here, we try to float it inwards until we find a suitable expression.VPlace ticks exactly on run-time expressions. We can still move the tick through pure compile-time constructs such as other ticks, casts or type lambdas. This is the most restrictive placement rule for ticks, as all tickishs have in common that they want to track runtime processes. The only legal placement rule for counting ticks. NB: We generally try to move these as close to the relevant runtime expression as possible. This means they get pushed through tyoe arguments. E.g. we create `(tick f) Bool` instead of `tick (f Bool)`.VAs  PlaceRuntime, but we float the tick through all lambdas. This makes sense where there is little difference between annotating the lambda and annotating the lambda's code.VIn addition to floating through lambdas, cost-centre style tickishs can also be moved from constructors, non-function variables and literals. For example: let x = scc ... C (scc ... y) (scc ... 3) in ...Neither the constructor application, the variable or the literal are likely to have any cost worth mentioning. And even if y names a thunk, the call would not care about the evaluation context. Therefore removing all annotations in the above example is safe.VSpecifies the scoping behaviour of ticks. This governs the behaviour of ticks that care about the covered code and the cost associated with it. Important for ticks relating to profiling.VNo scoping: The tick does not care about what code it covers. Transformations can freely move code inside as well as outside without any additional annotation obligationsVSoft scoping: We want all code that is covered to stay covered. Note that this scope type does not forbid transformations from happening, as long as all results of the transformations are still covered by this tick or a copy of it. For example let x = tick ...6 (let y = foo in bar) in baz ===> let x = tick ... bar; y = tick ... foo in bazIs a valid transformation as far as "bar" and "foo" is concerned, because both still are scoped over by the tick.Note though that one might object to the "let" not being covered by the tick any more. However, we are generally lax with this - constant costs don't matter too much, and given that the "let" was effectively merged we can view it as having lost its identity anyway.Also note that this scoping behaviour allows floating a tick "upwards" in pretty much any situation. For example:case foo of x -> tick ... bar ==> tick ... case foo of x -> barWhile this is always legal, we want to make a best effort to only make us of this where it exposes transformation opportunities.VCost centre scoping: We don't want any costs to move to other cost-centre stacks. This means we not only want no code or cost to get moved out of their cost centres, but we also object to code getting associated with new cost-centre ticks - or changing the order in which they get applied.A rule of thumb is that we don't want any code to gain new annotations. However, there are notable exceptions, for example:let f = y -> foo in tick ... ... (f x) ... ==> tick ... ... foo[x/y] ...In-lining lambdas like this is always legal, because inlining a function does not change the cost-centre stack when the function is called.VAn  {-# SCC #-} profiling annotation, either automatically added by the desugarer as a result of -auto-all, or added by the user.VA "tick" used by HPC to track the execution of each subexpression in the original source code.VA breakpoint for the GHCi debugger. This behaves like an HPC tick, but has a list of free variables which will be available for inspection in GHCi when the program stops at the breakpoint.NB. we must take account of these Ids when (a) counting free variables, and (b) substituting (don't substitute for them)VA source note.Source notes are pure annotations: Their presence should neither influence compilation nor execution. The semantics are given by causality: The presence of a source note means that a local change in the referenced source code span will possibly provoke the generated code to change. On the flip-side, the functionality of annotated code *must* be invariant against changes to all source code *except* the spans referenced in the source notes (see "Causality of optimized Haskell" paper for details).Therefore extending the scope of any given source note is always valid. Note that it is still undesirable though, as this reduces their usefulness for debugging and profiling. Therefore we will generally try only to make use of this property where it is necessary to enable optimizations.Vscopes over the enclosed expression (i.e. not just a tick) Invariant: the False/False case never happensVbump the entry count?Vthe cost centreVthe order of this list is important: it matches the order of the lists in the appropriate entry in .9Careful about substitution! See Note [substTickish] in GHC.Core.Subst.V4Name for source location (uses same names as CCs)VSource coveredV)Tickish in Cmm context (annotations only)߆;Allows attaching extra information to points in expressionsUsed as a data type index for the GenTickish annotations. See Note [Tickish passes]VA "counting tick" (where tickishCounts is True) is one that counts evaluations in some way. We cannot discard a counting tick, and the compiler should preserve the number of counting ticks as far as possible.However, we still allow the simplifier to increase or decrease sharing, so in practice the actual number of ticks may vary, except that we never change the value from zero to non-zero or vice versa.V/Returns the intended scoping rule for a TickishVReturns whether the tick scoping rule is at least as permissive as the given scoping rule.VReturns True for ticks that can be floated upwards easily even where it might change execution counts, such as: Just (tick ... foo) ==> tick ... (Just foo)This is a combination of tickishSoftScope and  tickishCounts. Note that in principle splittable ticks can become floatable using mkNoTick -- even though there's currently no tickish for which that is the case.VReturns True" for a tick that is both counting and> scoping and can be split into its (tick, scope) parts using V and mkNoTick respectively.VReturn True if this source annotation compiles to some backend code. Without this flag, the tickish is seen as a simple annotation that does not have any associated evaluation code.What this means that we are allowed to disregard the tick if doing so means that we can skip generating any code in the first place. A typical example is top-level bindings: foo = tick ...% y -> ... ==> foo = y -> tick ... ...Here there is just no operational difference between the first and the second version. Therefore code generation should simply translate the code as if it found the latter.V)Placement behaviour we want for the ticksVReturns whether one tick "contains" the other one, therefore making the second tick redundant.6Keep track of the type of breakpoints in STG, for GHCi'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV V %V VV V4V3V2V4V5V4V3NoneXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" "!X> >X HNoneVIn Core, without `-dlinear-core-lint`, some function must ignore multiplicities. See Note [Linting linearity] in GHC.Core.Lint.VmkMultSup w1 w2" returns a multiplicity such that mkMultSup w1 w2 >= w1 and mkMultSup w1 w2 >= w2.. See Note [Overapproximating multiplicities].V submult w1 w2' check whether a value of multiplicity w1+ is allowed where a value of multiplicity w2& is expected. This is a partial order.VVVVVVVNNRRSSSSSSVVVVVVMRRVVVVMNSSSSSSVVVVVNVVVVV VV "NoneKXRecord a single usage of an Id, i.e. {n: 1} Exception: We do not record external names (both GlobalIds and top-level LocalIds) because they're not relevant to linearity checking.X|lookupUE x env| returns the multiplicity assigned to |x| in |env|, if |x| is not bound in |env|, then returns |Zero| or |Bottom|.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX& &X None!An ordering relation between two s (known below as t1 :: k1 and t2 :: k2) t1 < t2t1 ~ t2> and there are no casts in either, therefore we can conclude k1 ~ k2t1 ~ t2 yet one of the types contains a cast so they may differ in kind. t1 > t2?This flag controls whether we expand synonyms during comparisonV Just like V, but will return True for types of different kinds as long as their non-coercion structure is identical.VCheck whether two TyConApps are the same; if the number of arguments are different, just checks the common prefix of arguments.V>Type equality on lists of types, looking through type synonymsVType equality comparing both visible and invisible arguments, expanding synonyms and respecting multiplicities.V7Compare types with respect to a (presumably) non-empty /.VLike pickyEqTypeVis$, but returns a Bool for convenienceReal worker for V. No kind check! Inline it at the (handful of local) call sites The "generic" bit refers to the flag paramerisation See Note [Specialising type equality].Real worker for V. No kind check! Inline it at the (handful of local) call sites The "generic" bit refers to the flag paramerisation See Note [Specialising type equality].V.Do these denote the same level of visibility?  arguments are visible, others are not. So this function equates  and . Used for printing.V.Do these denote the same level of visibility?  arguments are visible, others are not. So this function equates  and . Used for printing. Compare two +s. See Note [nonDetCmpType nondeterminism]VReturns True if the visible part of the types might look equal, even if they are really unequal (in the invisible bits)This function is very similar to tc_eq_type but it is much more heuristic. Notably, it is always safe to return True, even with types that might (in truth) be unequal -- this affects error messages only (Originally this test was done by eqType with an extra flag, but the result was hard to understand.)VVVVVVVVVVVVVVVVVVVVVVVVVVVVVV!$V&*V,3None!dXNumeric literal typeXBignat (see Note [BigNum literals])XInt# - according to target machineXInt8# - exactly 8 bitsXInt16# - exactly 16 bitsXInt32# - exactly 32 bitsXInt64# - exactly 64 bitsXWord# - according to target machineXWord8# - exactly 8 bitsXWord16# - exactly 16 bitsXWord32# - exactly 32 bitsXWord64# - exactly 64 bitsX So-called X s are one of:An unboxed numeric literal or floating-point literal which is presumed to be surrounded by appropriate constructors (Int#2, etc.), so that the overall thing makes sense.#We maintain the invariant that the ? in the X constructor is actually in the (possibly target-dependent) range. The mkLit{Int,Word}*Wrap smart constructors ensure this by applying the target machine's wrapping semantics. Use these in situations where you know the wrapping semantics are correct.The literal derived from the label mentioned in a "foreign label" declaration (X)A X3 to be used in place of values that are never used. A characterA stringThe NULL pointerXChar#" - at least 31 bits. Create with YXAny numeric literal that can be internally represented with an Integer.XA string-literal: stored and emitted UTF-8 encoded, we'll arrange to decode it at runtime. Also emitted with a '\0' terminator. Create with YXThe NULL pointer, the only pointer value that can be represented as a Literal. Create with YX.A nonsense value; See Note [Rubbish literals].XFloat#. Create with YXDouble#. Create with YXA label literal. Parameters::1) The name of the symbol mentioned in the declaration2) Flag indicating whether the symbol references a function or a dataXCoerce a literal number into another using wrapping semantics.XNarrow a literal number by converting it into another number type and then converting it back to its original type.X>Check that a given number is in the range of a numeric literalXGet the literal rangeXCreate a numeric X of the given typeXCreate a numeric X$ of the given type if it is in rangeX Creates a X of type Int#X Creates a X of type Int#. If the argument is out of the (target-dependent) range, it is wrapped. See Note [Word Int underflow overflow]X Creates a X of type Int# without checking its range.X Creates a X of type Int#, as well as a 9ean flag indicating overflow. That is, if the argument is out of the (target-dependent) range the argument is wrapped and the overflow flag will be set. See Note [Word Int underflow overflow]Y Creates a X of type Word#Y Creates a X of type Word#. If the argument is out of the (target-dependent) range, it is wrapped. See Note [Word Int underflow overflow]Y Creates a X of type Word# without checking its range.Y Creates a X of type Word#, as well as a 9ean flag indicating carry. That is, if the argument is out of the (target-dependent) range the argument is wrapped and the carry flag will be set. See Note [Word Int underflow overflow]Y Creates a X of type Int8#Y Creates a X of type Int8#8. If the argument is out of the range, it is wrapped.Y Creates a X of type Int8# without checking its range.Y Creates a X of type Word8#Y Creates a X of type Word8#8. If the argument is out of the range, it is wrapped.Y Creates a X of type Word8# without checking its range.Y Creates a X of type Int16#Y Creates a X of type Int16#8. If the argument is out of the range, it is wrapped.Y Creates a X of type Int16# without checking its range.Y Creates a X of type Word16#Y Creates a X of type Word16#8. If the argument is out of the range, it is wrapped.Y Creates a X of type Word16# without checking its range.Y Creates a X of type Int32#Y Creates a X of type Int32#8. If the argument is out of the range, it is wrapped.Y Creates a X of type Int32# without checking its range.Y Creates a X of type Word32#Y Creates a X of type Word32#8. If the argument is out of the range, it is wrapped.Y Creates a X of type Word32# without checking its range.Y Creates a X of type Int64#Y Creates a X of type Int64#8. If the argument is out of the range, it is wrapped.Y Creates a X of type Int64# without checking its range.Y Creates a X of type Word64#Y Creates a X of type Word64#8. If the argument is out of the range, it is wrapped.Y Creates a X of type Word64# without checking its range.Y Creates a X of type Float#Y Creates a X of type Double#Y Creates a X of type Char#Y Creates a X of type Addr#, which is appropriate for passing to e.g. some of the "error" functions in GHC.Err such as GHC.Err.runtimeErrorYTests whether the literal represents a zero of whatever type it isYTests whether the literal represents a one of whatever type it isY Returns the ? contained in the X', for when that makes sense, i.e. for ; and numbers.Y Returns the ? contained in the X', for when that makes sense, i.e. for ; and numbers.YApply a function to the ? contained in the X', for when that makes sense, e.g. for ; and numbers. For fixed-size integral literals, the result will be wrapped in accordance with the semantics of the target type. See Note [Word Int underflow overflow]0Narrow a literal number (unchecked result range)Y-Extend or narrow a fixed-width literal (e.g. Int16##) to a target word-sized literal (Int# or Word#). Narrowing can only happen on 32-bit architectures when we convert a 64-bit literal into a 32-bit one.Y-Extend or narrow a fixed-width literal (e.g. Int16##) to a target word-sized literal (Int# or Word#). Narrowing can only happen on 32-bit architectures when we convert a 64-bit literal into a 32-bit one.YTrue if there is absolutely no penalty to duplicating the literal. False principally of strings."Why?", you say? I'm glad you asked. Well, for one duplicating strings would blow up code sizes. Not only this, it's also unsafe.Consider a program that wants to traverse a string. One way it might do this is to first compute the Addr# pointing to the end of the string, and then, starting from the beginning, bump a pointer using eqAddr# to determine the end. For instance, -- Given pointers to the start and end of a string, count how many zeros -- the string contains. countZeros :: Addr# -> Addr# -> -> Int countZeros start end = go start 0 where go off n | off addrEq#- end = n | otherwise = go (off  plusAddr# 1) n' where n' | isTrue# (indexInt8OffAddr# off 0# ==# 0#) = n + 1 | otherwise = n Consider what happens if we considered strings to be trivial (and therefore duplicable) and emitted a call like countZeros "hello"# ("hello"# plusAddr# 5). The beginning and end pointers do not belong to the same string, meaning that an iteration like the above would blow up terribly. This is what happened in #12757.Ultimately the solution here is to make primitive strings a bit more structured, ensuring that the compiler can't inline in ways that will break user code. One approach to this is described in #8472.Y?True if code space does not go bad if we duplicate this literalYFind the Haskell  the literal occupiesYNeeded for the Ord instance of AltCon, which in turn is needed in h.YYYYYYYYYYYYYYYYYYYYYXXXXXXXYYYYYYYXYYYYYYYYYYYYXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYXXXYYXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY Y Y Y Y Y Y Y YYY6None23A kind of universal type, used for types and kinds. Any time a Type0 is pretty-printed, it is first converted to an  before being printed. See Note [Pretty printing via Iface syntax] in GHC.Types.TyThing.Ppr;Stores the arguments in a type application as a list. See &Note [Suppressing invisible arguments].V Header information only, not rhsV&Show the declaration and its RHS. The Maybe predicate allows filtering of the sub-components which should be printing; any sub-components filtered out will be elided with ....VEverything including GHC-internal information (used in --show-iface)VShow forall flag1Unconditionally show the forall quantifier with (V ) or when (V) the names used are free in the binder or when compiling with -fprint-explicit-foralls.VDo we want to suppress kind annotations on binders? See Note [Suppressing binder signatures]WThere are only a fixed number of CoAxiomRules, so it suffices to use an IfaceLclName to distinguish them. See Note [Adding built-in type families] in GHC.Builtin.Types.LiteralsW.See Note [Free TyVars and CoVars in IfaceType]W!See Note [Holes in IfaceCoercion]WThe various types of TyCons which have special, built-in syntax.Wa regular tyconWa tuple, e.g.  (a, b, c) or  (#a, b, c#). The arity is the tuple width, not the tycon arity (which is twice the width in the case of unboxed tuples).Wan unboxed sum, e.g. (# a | b | c #)WA heterogeneous equality TyCon (i.e. eqPrimTyCon, eqReprPrimTyCon, heqTyCon) that is actually being applied to two types of the same kind. This affects pretty-printing only: see Note [Equality predicates in IfaceType]WWe add a bang to this field as heap analysis showed that this constructor retains a thunk to a value that is usually shared.See !12200 for how this bang saved ~10% residency when loading mi_extra_decls on the agda code base.See Note [Sharing IfaceTyConInfo] for why sharing is so important for W.WA local name in iface syntaxWMake an W from an W.W Build the L: from the binders and the result kind. Keep in sync with L in GHC.Core.TyCon.WThis smart constructor allows sharing of the two most common cases. See Note [Sharing IfaceTyConInfo]!See Note [Sharing IfaceTyConInfo]!See Note [Sharing IfaceTyConInfo]W)Returns true for Type or (TYPE LiftedRep)5Returns true for Constraint or (CONSTRAINT LiftedRep)W Extract an  from an W.W"Extract the variable name from an W.W Extract an  from an W.W"Extract the variable name from an W.Default L variables to  LiftedRep, % variables to %, and  Multiplicity variables to Many. For example: ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b Just :: forall (k :: Multiplicity) a. a % k -> Maybe a  turns in to,. ($) :: forall a (b :: *). (a -> b) -> a -> b  ! Just :: forall a . a -> Maybe a We do this to prevent RuntimeRep, Levity and Multiplicity variables from incurring a significant syntactic overhead in otherwise simple type signatures (e.g. ($)). See Note [Defaulting RuntimeRep variables] and #11549 for further discussion.6The type ('BoxedRep 'Lifted), also known as LiftedRep.The type 'Lifted :: Levity'.W The type 'Many :: Multiplicity'.WLike W, but always uses an explicit forall.W;Render the "forall ... ." or "forall ... ->" bit of a type.Render the ... in (forall ... .) or (forall ... ->). Returns both the list of not-yet-rendered binders and the doc. No anonymous binders here!Pretty-print a type-level equality. Returns (Just doc) if the argument is a  saturated application of eqTyCon (~) eqPrimTyCon (~#) eqReprPrimTyCon (~R#) heqTyCon (~~)See Note [Equality predicates in IfaceType] and Note [The equality types story] in GHC.Builtin.Types.PrimPretty-prints an application of a type constructor to some arguments (whose visibilities are known). This is polymorphic (over a) since we use this function to pretty-print two different things:  Types (from  pprTyTcApp')Coercions (from W)Pretty-print a boxed tuple datacon in regular tuple syntax. Used when -XListTuplePuns is disabled.Pretty-print an unboxed tuple or sum type in its parenthesized, punned, form. Used when -XListTuplePuns is enabled.The tycon should be saturated: as many visible arguments as the arity of the sum or tuple.)NB: this always strips off the invisible L arguments, even with `-fprint-explicit-runtime-reps` and `-fprint-explicit-kinds`.Pretty-print an unboxed tuple or sum type either in the punned or unpunned form, depending on whether -XListTuplePuns is enabled.Pretty-print an unboxed sum type. The sum should be saturated: as many visible arguments as the arity of the sum.Pretty-print a tuple type (boxed tuple, constraint tuple, unboxed tuple). The tuple should be saturated: as many visible arguments as the arity of the tuple. Print an  with a promotion tick if needed, without parens, suitable for use in infix contexts Print an  with a promotion tick if needed, possibly with parens, suitable for use in prefix contextsWPrints "(C a, D b) =>", including the arrow. Used when we want to print a context in a type, so we use & to decide whether to parenthesise a singleton predicate; e.g. Num a => a -> aWPrints a context or ()- if empty You give it the context precedenceWThis is the byte tag we expect to read when the next value is not an  value, but an offset into a lookup table. See Note [Deduplication during iface binary serialisation].&Must not overlap with any byte tag in W.Like W but checks for a specific byte tag that indicates that we won't be able to read a  value but rather an offset into a lookup table. Consequentially, we look up the value for the  in the look up table.See Note [Deduplication during iface binary serialisation] for details.WSerialises an  to the given .Serialising inner  IfaceType' s uses the  of  which may be using a deduplication table. See Note [Deduplication during iface binary serialisation].WDeserialises an  from the given .Reading inner  IfaceType' s uses the  of  which may be using a deduplication table. See Note [Deduplication during iface binary serialisation].if printing coercions otherwisedefault L/% variables?default  Multiplicity variables?*visibility of the first binder in the listWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVWWWWWWVVVVWWWWWWWWVWWWWVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVV----WWWWWWWWWWWWWWWWWWWWWWWWVWWWWVWWWWWWVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW----VVVVVVVVVVVVWWWWWWWWWWWWWWWVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW>W W W W W W !W W W W X X #X X X #X X X X X X X X X X X (X X X X X "X !X X X X %X X X X XX&(X*-X XX XX XX XXXXXX!X#&X XXXXNoneXUsed when we want to fingerprint a structure without depending on the fingerprints of external Names that it refers to.XXXXXXJNonedebugPprType is a simple pretty printer that prints a type without going through IfaceType. It does not format as prettily as the normal route, but it's much more direct, and that can be useful for debugging. E.g. with -dppr-debug it prints the kind on type-variable  occurrences1 which the normal route fundamentally cannot do.ZPrint a user-level forall; see Note [When to print foralls] in GHC.Iface.Type.ZDisplay all foralls, runtime-reps, and kind information when provided 9 argument is M. See GHC.Tc.Errors.Ppr Note [Showing invisible bits of types in error messages]ZThis variant preserves any use of TYPE in a type, effectively locally setting -fprint-explicit-runtime-reps.ZPretty prints a , using the family instance in case of a representation tycon. For example: data T [a] = ...In that case we want to print T [a], where T is the family #ZZZZZZZZZZZZZZZZZZZZZ&&&&&&&&#&&&&&&&&ZZZZZZZZZZZZZZZZZZZZZNone\ bPattern SynonymSee Note [Pattern synonym representation] See Note [Pattern synonym signature contexts]Argument typesbBuild a new pattern synonymbThe  of the b+, giving it a unique, rooted identificationb Should the b be presented infix?bArity of the pattern synonymbIs this a 'vanilla' pattern synonym (no existentials, no provided constraints)?b5Extract the type for any given labelled field of the DataConbPrint the type of a pattern synonym. The foralls are printed explicitlyb&Is the pattern synonym declared infix?9Universally-quantified type variables and required dicts;Existentially-quantified type variables and provided dictsOriginal argumentsOriginal result typeMatcherBuilder/Names of fields for a record pattern synonymbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb b b b b b NoneYTrie of [RoughMatchTc] Examples*  insert [OtherTc] 1 insert [OtherTc] 2 lookup [OtherTc] == [1,2] Y/The position only matches the specified KnownTcY1The position definitely doesn't match any KnownTcYThe position can match anythingZ!Order of result is deterministic.ZN.B. Returns a  for matches, which allows us to avoid rebuilding all of the lists we find in ,, which would otherwise be necessary due to  if we returned a list. We use a list for unifiers because the tail is computed lazily and we often only care about the first couple of potential unifiers. Constructing a bag forces the tail which performs much too much work.>See Note [Matching a RoughMap] See Note [Matches vs Unifiers]Place a Y# in normal form, turning all empty s into "s. Necessary after removing items.ZFilter all elements that might match a particular key with the given predicate.ZZZZZZZZZZZZZZZZZYYYYYYYZYYZZZYYYYZZZZZYZZZZZZZZZZZ !Z 'Z 1Z ZZ ENone/=K$Sometimes we want to look through a newtype< and get its associated coercion. This function strips off newtype1 layers enough to reveal something that isn't a newtype&. Specifically, here's the invariant: 5topNormaliseNewType_maybe rec_nts ty = Just (co, ty') then (a) co : ty ~R ty'". (b) ty' is not a newtype.The function returns Nothing for non-newtypes, or unsaturated applicationsThis function does *not* look through type families, because it has no access to the type family environment. If you do have that at hand, consider to use topNormaliseType_maybe, which should be a drop-in replacement for topNormaliseNewType_maybe If topNormliseNewType_maybe ty = Just (co, ty'), then co : ty ~R ty'KIf it is the case that c :: (t1 ~ t2)i.e. the kind of c relates t1 and t2, then coercionKind c = Pair t1 t2.KMakes a coercion type from two types: the types whose equality is proven by the relevant KSlowly checks if the coercion is reflexive. Don't call this in a loop, as it walks over the entire coercion.KTests if this coercion is obviously reflexive. Guaranteed to work very quickly. Sometimes a coercion can be reflexive, but not obviously so. c.f. KKTests if this coercion is obviously a generalized reflexive coercion. Guaranteed to work very quickly.K$Make a "coercion between coercions".KGiven co :: (a :: k) ~ (b :: k') produce  co' :: k ~ k'.K!Make a nominal reflexive coercionK%Make a generalized reflexive coercionKInstantiates a !. Works for both tyvar and covarKmkTransCo creates a new  by composing the two given s transitively: (co1 ; co2)K(Create a symmetric version of the given  that asserts equality between the same types but in the other "direction", so a kind of t1 ~ t2 becomes the kind t2 ~ t1.K6Make a universal coercion between two arbitrary types.KMake a phantom coercion between two types. The coercion passed in must be a nominal coercion between the kinds of the types.KBuild a function  from two other s. That is, given  co1 :: a ~ b and  co2 :: x ~ y produce co :: (a -> x) ~ (b -> y) or (a => x) ~ (b => y), depending on the kind of a/b. This (most common) version takes a single FunTyFlag, which is used for both fco_afl and ftf_afr of the FunCoKMake a Coercion from a tycovar, a kind coercion, and a body coercion.KApply a  to another . The second coercion must be Nominal, unless the first is Phantom. If the first is Phantom, then the second can be either Phantom or Nominal.KApply a type constructor to a list of coercions. It is the caller's responsibility to get the roles correct on argument coercions.KMake a reflexive coercionZ9The result of stepping in a normalisation function. See [.ZNothing more to doZ2Utter failure. The outer function should fail too.ZWe stepped, yielding new bits; ^ ev is evidence; Usually a co :: old type ~ new typeZA function to check if we can reduce a type by one step. Used with [.ZTests if this MCoercion is obviously generalized reflexive Guaranteed to work very quickly.Z'Compose two MCoercions via transitivityZGet the reverse of an ZCast a type by an ZLike Z, but with an ZThis breaks a  with type T A B C ~ T D E F into a list of  s of kinds A ~ D, B ~ E and E ~ F. Hence: decomposeCo 3 c [r1, r2, r3] = [nth r1 0 c, nth r2 1 c, nth r3 2 c]ZExtract a covar, if possible. This check is dirty. Be ashamed of yourself. (It's dirty because it cares about the structure of a coercion, which is morally reprehensible.)Z-Attempt to take a coercion application apart.ZLike Z(, but only returns Just for tyvar binderZLike Z(, but only returns Just for covar binderZGiven a coercion `co :: (t1 :: TYPE r1) ~ (t2 :: TYPE r2)` produce a coercion `rep_co :: r1 ~ r2` But actually it is possible that co :: (t1 :: CONSTRAINT r1) ~ (t2 :: CONSTRAINT r2) or co :: (t1 :: TYPE r1) ~ (t2 :: CONSTRAINT r2) or co :: (t1 :: CONSTRAINT r1) ~ (t2 :: TYPE r2) See Note [mkRuntimeRepCo]ZReturns the type coerced if this coercion is a generalized reflexive coercion. Guaranteed to work very quickly.ZReturns the type coerced if this coercion is reflexive. Guaranteed to work very quickly. Sometimes a coercion can be reflexive, but not obviously so. c.f. ZZExtracts the coerced type from a reflexive coercion. This potentially walks over the entire coercion, so avoid doing this in a loop.Z*Make a representational reflexive coercionZApplies multiple  s to another  , from left to right. See also K.ZMake a Coercion quantified over a type/coercion variable; the variable has the same kind and visibility in both sides of the coercionLike K, but there is no need to check that the inner coercion isn't Refl; the caller has done that. (For example, it is guaranteed in Z.) The kind of the tycovar should be the left-hand kind of the kind coercion.ZReturn the left-hand type of the axiom, when the axiom is instantiated at the types given.Z5Instantiate the left-hand side of an unbranched axiomZ$Make a coercion from a coercion holeZ Extract the nth field of a FunCoZGiven ty :: k1,  co :: k1 ~ k2 , produces co' :: ty ~r (ty |> co)ZGiven r, ty :: k1, and co :: k1 ~N k2 , produces co' :: (ty |> co) ~r tyZGiven ty :: k1,  co :: k1 ~ k2, co2:: ty ~r ty', produces @co' :: (ty |> co) ~r ty' It is not only a utility function, but it saves allocation when co is a GRefl coercion.ZGiven ty :: k1,  co :: k1 ~ k2, co2:: ty' ~r ty, produces @co' :: ty' ~r (ty |> co) It is not only a utility function, but it saves allocation when co is a GRefl coercion.Changes a role, but only a downgrade. See Note [Role twiddling functions]ZLike , but panics if the change isn't a downgrade. See Note [Role twiddling functions]ZConverts a coercion to be nominal, if possible. See Note [Role twiddling functions]Zlike mkKindCo, but aggressively & recursively optimizes to avoid using a KindCo constructor. The output role is nominal.say g = promoteCoercion h. Then, instCoercion g w yields Just g' , where g' = promoteCoercion (h w)%. fails if this is not possible, if g coerces between a forall and an -> or if second parameter has a representational role and can't be used with an InstCo.Repeated use of ZCreates a new coercion with both of its types casted by different casts !castCoercionKind2 g r t1 t2 h1 h2, where  g :: t1 ~r t2 , has type (t1 |> h1) ~r (t2 |> h2). h1 and h2 must be nominal.ZcastCoercionKind1 g r t1 t2 h = coercionKind g r t1 t2 h h That is, it's a specialised form of castCoercionKind, where the two kind coercions are identical castCoercionKind1 g r t1 t2 h, where  g :: t1 ~r t2 , has type (t1 |> h) ~r (t2 |> h). h/ must be nominal. See Note [castCoercionKind1]ZCreates a new coercion with both of its types casted by different casts castCoercionKind g h1 h2, where  g :: t1 ~r t2 , has type (t1 |> h1) ~r (t2 |> h2). h1 and h2 must be nominal. It calls coercionKindRole#, so it's quite inefficient (which I stands for) Use castCoercionKind2 instead if t1, t2, and r are known beforehand.[Make a forall , where both types related by the coercion are quantified over the same variable.[If `instNewTyCon_maybe T ts = Just (rep_ty, co)` then `co :: T ts ~R# rep_ty`-Checks for a newtype, and for being saturated[Try one stepper and then try the next, if the first doesn't make progress. So if it returns NS_Done, it means that both steppers are satisfied[A Z that unwraps newtypes, careful not to fall into a loop. If it would fall into a loop, it produces Z.[A general function for normalising the top-level of a type. It continues to use the provided Z until that function fails, and then this function returns. The roles of the coercions produced by the Z must all be the same, which is the role returned from the call to [.Typically ev is Coercion.If topNormaliseTypeX step plus ty = Just (ev, ty') then ty ~ev1~ t1 ~ev2~ t2 ... ~evn~ ty' and ev = ev1 plus ev2 plus ... plus evn If it returns Nothing then no newtype unwrapping could happen[Syntactic equality of coercions[ Compare two s, with respect to an RnEnv2[liftCoSubst role lc ty produces a coercion (at role role) that coerces between  lc_left(ty) and  lc_right(ty) , where lc_left is a substitution mapping type variables to the left-hand types of the mapped coercions in lc, and similar for lc_right.[,Extend a lifting context with a new mapping.[Extend the substitution component of a lifting context with a new binding for a coercion variable. Used during coercion optimisation.[Extend a lifting context with a new mapping, and extend the in-scope setExtend a lifting context with existential-variable bindings. See Note [extendLiftingContextEx][+Erase the environments in a lifting context[Like Q , but works on a lifting contextThe "lifting" operation which substitutes coercions for type variables in a type to produce a coercion.For the inverse operation, see  liftCoMatch[,Is a var in the domain of a lifting context?["Apply "sym" to all coercions in a Z[ Lookup a - in the substitution in a Z[Get the / from a Z[Apply K to multiple s[Get a coercion's kind and role.["Retrieve the role from a coercion.[Creates a primitive nominal type equality predicate. t1 ~# t2 Invariant: the types are not Coercions[Creates a primitive representational type equality predicate. t1 ~R# t2 Invariant: the types are not Coercions[3Makes a lifted equality predicate at the given role[Creates a primitive nominal type equality predicate with an explicit (but homogeneous) kind: (~#) k k ty1 ty2[Assuming that two types are the same, ignoring coercions, find a nominal coercion between the types. This is useful when optimizing transitivity over coercion applications, where splitting two AppCos might yield different kinds. See Note [EtaAppCo] in GHC.Core.Coercion.Opt.[Is there a hetero-kind coercion hole in this type? (That is, a coercion hole with ch_hetero_kind=True.) See wrinkle (EIK2) of Note [Equalities with incompatible kinds] in GHC.Tc.Solver.Equality[6Is there a hetero-kind coercion hole in this coercion?[Set the type of a M K!role of the created coercion, "r":: phi1 ~N phi2 g1 :: phi1 g2 :: phi2 :: g1 ~r g2KCoercions on which this dependsrole of the built coercion, "r"t1 :: k1t2 :: k2 :: t1 ~r t2K :: t1 ~r t2%:: s1 ~N s2, where s1 :: k1, s2 :: k2:: t1 s1 ~r t2 s2Z multiplicityargumentresultOne of the above three desired role current rolemust be nominal[ original LCnew variable to map......to this lifted version[ Original LCnew variable to map...to this coercionoriginal lifting contextex. var / value pairs[coercion gettercallbackcoercion gettercallbackcoercion gettercallback[ZZZZZZZZZKZKK[[KK[K[ZZKZ[[[Z[[[KZZ[[[[KZZ[KZZZKZ[[[[[[[[[[[[ZKZZZZKZ[KZKZZZKKKZ[ZKZZZZZZZKKKZK[KK[ZZ[[KKZ[ZKZK[KZKZZZKZZZKZZZZZZZK[ZZZZZZZZ[[[[ZK[ZZZZZ[[QPQQPQPZNNNQQQQQQQQQQRR&.-ZZZZZZZZNNNMNNNNNNNNNNNNQ&&&- NNNNNNNNNNNMNNNNNN&&&- ZZZZZKKKKKKK[[[KZKZKKZZZZZZZ[Z[KKKZZZKKKZKKKZ[KZKZKZKKKZKZZZZKZZZ[[[[[ZZZZZ[[K[ZZKZZZZZZZZZZZZK&KKZZKZZZZZZZZZZZZZZZZ-.ZZZPPPQQQNQQQQQQQQQQQQ[[[[[[[[[[[[[[[[ZZZ[[[[[[[[[KZZZZZZZRRZ[ZZ[[[[[ >[ #[ None \>A choice of equality relation. This is separate from the type   because  3 does not define a (non-trivial) equality relation.\A predicate in the solver. The solver tries to prove Wanted predicates from Given ones.\A typeclass predicate.\5A type equality predicate, (t1 ~#N t2) or (t1 ~#R t2)\An irreducible predicate.\A quantified predicate.8See Note [Quantified constraints] in GHC.Tc.Solver.Solve\Get the equality relation relevant for a pred type Returns NomEq for dictionary predicates, etc\Does this type classify a core (unlifted) Coercion? At either role nominal or representational (t1 ~# t2) or (t1 ~R# t2) See Note [Types for coercions, predicates, and evidence] in GHC.Core.TyCo.Rep\Decomposes a predicate if it is an implicit parameter. Does not look in superclasses. See also [Local implicit parameters].\Is a  an ExceptionContext implicit parameter?(If so, return the name of the parameter. Is a type a  CallStack?\Is a  a  CallStack implicit parameter?(If so, return the name of the parameter.\ Is a type a  CallStack?/[[[[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.\\\\\\\\-/\\\\\\.\\\\\\\\\\\\\\[[[[\\\\\\\\\\\\\\\\\\\-\\\ \ \None"`Stores ` as well as a kind coercion.1Used when rewriting arguments to a type function f.Invariant: when the stored reductions are of the form co_i :: ty_i ~ xi_i, the kind coercion is of the form kco :: typeKind (f ty_1 ... ty_n) ~ typeKind (f xi_1 ... xi_n)The type function f depends on context.`A collection of `:s where the coercions and the types are stored separately.Use a to obtain ` from a list of `s.This datatype is used in a, mkClassPredRedns and a-, which expect separate types and coercions.Invariant: the two stored lists are of the same length, and the RHS type of each coercion is the corresponding type.`A ` in which the  has   role.`A ` in which the  has   role.`!Stores a heterogeneous reduction.The stored kind coercion must relate the kinds of the stored reduction. That is, in "HetReduction (Reduction co xi) kco, we must have: / co :: ty ~ xi kco :: typeKind ty ~ typeKind xi`A `4 is the result of an operation that rewrites a type ty_in. The ` includes the rewritten type ty_out and a  co such that co :: ty_in ~ ty_out, where the role of the coercion is determined by the context. That is, the LHS type of the coercion is the original type ty_in+, while its RHS type is the rewritten type ty_out.A Reduction is always homogeneous, unless it is wrapped inside a `-, which separately stores the kind coercion.See Note [The Reduction type].a!Create a heterogeneous reduction.Pre-condition: the provided kind coercion (second argument) relates the kinds of the stored reduction. That is, if the coercion stored in the ` is of the form  co :: ty ~ xi4Then the kind coercion supplied must be of the form:  kco :: typeKind ty ~ typeKind xia%Homogenise a heterogeneous reduction.Given "HetReduction (Reduction co xi) kco, with 1 co :: ty ~ xi kco :: typeKind(ty) ~ typeKind(xi)'this returns the homogeneous reduction: hco :: ty ~ ( xi |> sym kco )a Create a ` from a pair of a  and a 'Type.Pre-condition: the RHS type of the coercion matches the provided type (perhaps up to zonking).Use a! when you only have the coercion.a4Get the original, unreduced type corresponding to a `.This is obtained by computing the LHS kind of the stored coercion, which may be slow.aTurn a  into a `- by inspecting the RHS type of the coercion. Prefer using a when you already know the RHS type of the coercion, to avoid computing it anew.a1Downgrade the role of the coercion stored in the `.a1Downgrade the role of the coercion stored in the `, from   to  .a0Compose a reduction with a coercion on the left.Pre-condition: the provided coercion's RHS type must match the LHS type of the coercion that is stored in the reduction.aThe reflexive reduction.a Create a ` from a kind cast, in which the casted type is the rewritten type.Given ty :: k1, mco :: k1 ~ k2, produces the ` ty ~res_co~> (ty |> mco) at the given  .a Create a ` from a kind cast, in which the casted type is the rewritten type.Given ty :: k1, mco :: k1 ~ k2, produces the ` ty ~res_co~> (ty |> mco) at the given  .a Create a ` from a kind cast, in which the casted type is the original (non-rewritten) type.Given ty :: k1, mco :: k1 ~ k2, produces the ` (ty |> mco) ~res_co~> ty at the given  .a Create a ` from a kind cast, in which the casted type is the original (non-rewritten) type.Given ty :: k1, mco :: k1 ~ k2, produces the ` (ty |> mco) ~res_co~> ty at the given  .a Apply a cast to the result of a `.Given a ` ty1 ~co1~> (ty2 :: k2) and a kind coercion kco with LHS kind k2, produce a new ` ty1 ~co2~> ( ty2 |> kco ) of the given  ; (which must match the role of the coercion stored in the ` argument).a Apply a cast to the result of a ` , using an .Given a ` ty1 ~co1~> (ty2 :: k2) and a kind coercion mco with LHS kind k2, produce a new ` ty1 ~co2~> ( ty2 |> mco ) of the given  ; (which must match the role of the coercion stored in the ` argument).aApply a cast to a `1, casting both the original and the reduced type.Given cast_co and `  ty ~co~> xi, this function returns the ` ,(ty |> cast_co) ~return_co~> (xi |> cast_co) of the given  ; (which must match the role of the coercion stored in the ` argument).Pre-condition: the  passed in is the same as the LHS type of the coercion stored in the `.aApply casts on both sides of a ` (of the given  ).Use a when you want to cast both the original and reduced types in a ` using the same coercion.Pre-condition: the  passed in is the same as the LHS type of the coercion stored in the `.a Apply one ` to another. Combines K and mkAppTy.aCreate a function `. Combines K and N.a Create a `& associated to a  type, from a kind ` and a body `. Combines K and .a Create a ` of a quantified type from a ` of the body. Combines Z and N.a Create a `# from a coercion between coercions. Combines K and ..aCreate a reflexive ` whose RHS is the given , with the specified  .aCreate `. from individual lists of coercions and types.The lists should be of the same length, and the RHS type of each coercion should match the specified type in the other list.a Combines Z and R.a TyConAppCo for ` s: combines K and ..aReduce the arguments of a K .aObtain ` from a list of `s by unzipping.aheterogeneous reduction kind coerciona desired role current rolea original typecoercion to cast with'rewritten type, with rewriting coerciona original type!coercion to cast with on the left'rewritten type, with rewriting coercion"coercion to cast with on the rightamultiplicity reductionargument reductionresult reductionakind reductionbody reductiona!role of the created coercion, "r"co :: phi1 ~N phi2 g1 :: phi1 g2 :: phi2res_co :: g1 ~r g2)aaaaaaaaaaaaaaaaaaaaaaaaaaaaa````````````)``````````aaaaaaaaaaaaaaaaaaaaaaaaaaaa``aa None [A [ is a [ which allows us to distinguish between binding forms whose binders have different types. For example, if we are doing a  lookup on (x :: Int) -> ()), we should not pick up an entry in the  for (x :: Bool) -> (): we can disambiguate this by matching on the type (or kind, if this a binder in a type) of the binder.We also need to do the same for multiplicity! Which, since multiplicities are encoded simply as a , amounts to have a Trie for a pair of types. Tries of pairs are composition.[ DeBruijn a represents a modulo alpha-renaming. This is achieved by equipping the value with a [, which tracks an on-the-fly deBruijn numbering. This allows us to define an % instance for  DeBruijn a., even if this was not (easily) possible for a. Note: we purposely don't export the constructor. Make a helper function if you find yourself needing it.[A [ doesn't do a kind-check. Thus, when lookup up (t |> g), you'll find entries inserted under (t), even if (g) is non-reflexive.[ TypeMap a is a map from  to a. If you are a client, this is the type you want. The keys in this map may have different kinds.!An equality relation between two s (known below as t1 :: k2 and t2 :: k2) t1 /= t2t1 ~ t2? and there are not casts in either, therefore we can conclude k1 ~ k2t1 ~ t2 yet one of the types contains a cast so they may differ in kind TypeMapX a is the base map from  DeBruijn Type to a, but without the  optimization. See Note [Computing equality on types] in GHC.Core.Type.[ TypeMapG a is a map from  DeBruijn Type to a. The extended key makes it suitable for recursive traversal, since it can track binders, but it is strictly internal to this module. If you are including a [ inside another , this is the type you want. Note that this lookup does not do a kind-check. Thus, all keys in this map must have the same kind. Also note that this map respects the distinction between Type and  Constraint, despite the fact that they are equivalent type synonyms in Core.Squeeze out any synonyms, and change TyConApps to nested AppTys. Why the last one? See Note [Equality on AppTys] in GHC.Core.TypeWe also keep (Eq a => a) as a FunTy, distinct from ((->) (Eq a) a).[ Extend a [$ with a type in the given context. 8extendTypeMapWithScope m (mkDeBruijnContext [a,b,c]) t v is equivalent to #extendTypeMap m (forall a b c. t) v<, but allows reuse of the context over multiple insertions.[Construct a deBruijn environment with the given variables in scope. e.g. mkDeBruijnEnv [a,b,c] constructs a context  forall a b c.[Synthesizes a  DeBruijn a from an a9, by assuming that there are no bound binders (an empty [<). This is usually what you want if there isn't already a [ in scope.'[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[['[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ [ [ 4[ .[ [ [ [ [ [ [ [ 1[ [ [ [ [ [ [ [ [ [ None[A regular type variable[#Declare that this type variable is apart from the type provided. That is, the type variable will never be instantiated to that type. See also Note [Binding when looking up instances] in GHC.Core.InstEnv.[Why are two types [? [ takes precedence: This is used (only) in Note [Infinitary substitution in lookup] in GHC.Core.InstEnv As of Feb 2022, we never differentiate between MARTypeFamily and MARTypeVsConstraint; it's really only MARInfinite that's interesting here.[matching e.g. F Int ~? Bool[matching e.g. a ~? Maybe a[matching Type ~? Constraint or the arrow types See Note [Type and Constraint are not apart] in GHC.Builtin.Types.Prim[See Note [Unification result][2Some unification functions are parameterised by a [, which says whether or not to allow a certain unification to take place. A [ takes the  involved along with the " it will potentially be bound to.It is possible for the variable to actually be a coercion variable (Note [Matching coercion variables]), but only when one-way matching. In this case, the  will be a N.[tcMatchTy t1 t2) produces a substitution (over fvs(t1)) s such that s(t1) equals t2. The returned substitution might bind coercion variables, if the variable is an argument to a GADT constructor.Precondition: typeKind ty1 V typeKind ty2We don't pass in a set of "template variables" to be bound by the match, because tcMatchTy (and similar functions) are always used on top-level types, so we can bind any of the free variables of the LHS. See also Note [tcMatchTy vs tcMatchTyKi][Like [, but allows the kinds of the types to differ, and thus matches them as well. See also Note [tcMatchTy vs tcMatchTyKi][This is similar to [, but extends a substitution See also Note [tcMatchTy vs tcMatchTyKi][Like [ but over a list of types. See also Note [tcMatchTy vs tcMatchTyKi][Like [ but over a list of types. See also Note [tcMatchTy vs tcMatchTyKi][Like [, but extending a substitution See also Note [tcMatchTy vs tcMatchTyKi][Like [, but extending a substitution See also Note [tcMatchTy vs tcMatchTyKi]=Same as tc_match_tys_x, but starts with an empty substitution Worker for [ and [[This one is called from the expression matcher, which already has a MatchEnv in hand[Allow binding only for any variable in the set. Variables may be bound to any type. Used when doing simple matching; e.g. can we find a substitution S = [a :-> t1, b :-> t2] such that S( Maybe (a, b->Int ) = Maybe (Bool, Char -> Int) [-Allow the binding of any variable to any type[Given a list of pairs of types, are any two members of a pair surely apart, even after arbitrary type function evaluation and substitution?[Simple unification of two types; all type variables are bindable Precondition: the kinds are already equal[Like [, but also unifies the kinds\Unify two types, treating type family applications as possibly unifying with anything and looking through injective type family applications. Precondition: kinds are the same\Like \ but also unifies the kinds\tcUnifyTysFG bind_tv tys1 tys2! attempts to find a substitution s% (whose domain elements all respond [ to bind_tv ) such that s(tys1) and that of s(tys2) are equal, as witnessed by the returned Coercions. This version requires that the kinds of the types are the same, if you unify left-to-right.This function is actually the one to call the unifier -- a little too general for outside clients, though.(Converts any SurelyApart to a MaybeApart\\ is sort of inverse to [. In particular, if  liftCoMatch vars ty co == Just s, then liftCoSubst s ty == co , where == there means that the result of [ has the same type as the original co; but may be different under the hood. That is, it matches a type against a coercion of the same "shape", and returns a lifting substitution which could have been used to produce the given coercion from the given type. Note that this function is incomplete -- it might return Nothing when there does indeed exist a possible lifting context.This function is incomplete in that it doesn't respect the equality in V. That is, it's possible that this will succeed for t1 and fail for t2, even when t1 V t2. That's because it depends on there being a very similar structure between the type and the coercion. This incompleteness shouldn't be all that surprising, especially because it depends on the structure of the coercion, which is a silly thing to do.The lifting context produced doesn't have to be exacting in the roles of the mappings. This is because any use of the lifting context will also require a desired role. Thus, this algorithm prefers mapping to nominal coercions where it can do so. does all the actual work for \. [Substitution to extendTemplateTarget[TemplateTargetOne-shot; in principle the template variables could be free in the target[TemplateTargetOne-shot substitution[Substitution to extendTemplateTargetOne-shot substitution[Substitution to extendTemplateTargetOne-shot substitution match kinds? match kinds?[template variablestype substitution to extendTemplateTarget\True  =" do two-way unification; False  =: do one-way matching. See end of sec 5.2 from the paper\A regular one-shot (idempotent) substitution that unifies the erased types. See comments for \True  = unify; False  = matchTrue  = doing an injectivity checkTrue  = treat the kinds as wellsee Note [Rewrite rules ignore multiplicities in FunTy] in GHC.Core.Unifysubstitution to extendambient helpful infoincoming substty, type to match+co :: lty ~r rty, coercion to match against :: kind(lsubst(ty)) ~N kind(lty) :: kind(rsubst(ty)) ~N kind(rty)Just env ==> liftCoSubst Nominal env ty == co, modulo roles. Also: Just env ==> lsubst(ty) == lty and rsubst(ty) == rty, where lsubst = lcSubstLeft(env) and rsubst = lcSubstRight(env)#[\\\[[[[[[[[[[[[\\\\[[[[[[[[[[[[[[[#[[[[[[[[[[[\\\\[[[[[[[[[[[[[[[[[\\\ \ $\ %\ 5\ \ "\ \ \ \ \ \%None)&9(An ( is a tyvar/type pair representing an equality made in rejigging a GADT constructor(Data Constructor Representation See Note [Data constructor workers and wrappers](A data constructor(Returns an Id which looks like the Haskell-source constructor by using the wrapper if it exists (see \') and failing over to the worker (see ()(Is this data constructor in a "type data" declaration? See Note [Type data declarations] in GHC.Rename.Module.(The "full signature" of the ( returns, in order:1) The result of \2) The result of (3) The non-dependent GADT equalities. Dependent GADT equalities are implied by coercion variables in return value (2).4) The other constraints of the data constructor type, excluding GADT equalities&5) The original argument types to the ( (i.e. before any change of the representation of the type) with linearity annotations#6) The original result type of the ((The "stupid theta" of the ( , such as  data Eq a in: data Eq a => T a = ...See Note [The stupid context].(Returns just the instantiated value argument types of a (, (excluding dictionary args)(-The labels for the fields of this particular ((*Source-level arity of the data constructor(s for the type variables of the constructor, in the order the user wrote them(The type variables of the constructor, in the order the user wrote them(The existentially-quantified type/coercion variables of the constructor including dependent (kind-) GADT equalities(The type constructor that we are building via this data constructor(Get the Id of the ( worker: a function that is the "actual" constructor and has no top level binding in the program. The type may be different from the obvious one written in the source program. Panics if there is no such  for this ((The  of the (+, giving it a unique, rooted identification\Haskell Implementation BangBangs of data constructor arguments as generated by the compiler after consulting HsSrcBang, flags, etc.\(Lazy field, or one with an unlifted type\$Strict but not unpacked field True  = we could have unpacked, but opted not to because of -O0. See Note [Detecting useless UNPACK pragmas]\;Strict and unpacked field co :: arg-ty ~ product-ty HsBang\Haskell Source BangBangs on data constructor arguments as written by the user, including the source code for exact-printing.?In the AST, the SourceText is deconstructed and hidden inside 1 extension point.Tag, used for ordering (s\Make a \ from all parts\Make a non-dependent (\Compare strictness annotations\Build a new data constructor\The tag used for ordering (s\The original type constructor used in the definition of this data constructor. In case of a data family instance, that will be the family type constructor.\The representation type of the data constructor, i.e. the sort type that will represent values of this type at runtime\ Should the ( be presented infix?\ b -> T [a] rather than: 3T :: forall a c. forall b. (c~[a]) => a -> b -> T cThe type variables are quantified in the order that the user wrote them. See )Note [DataCon user type variable binders].NB: If the constructor is part of a data instance, the result type mentions the family tycon, not the internal one.\Finds the instantiated types of the arguments required to construct a ( representation NB: these INCLUDE any dictionary args but EXCLUDE the data-declaration context, which is discarded It's all post-flattening etc; this is a representation type\Given a data constructor dc with n( universally quantified type variables a_{1}, a_{2}, ..., a_{n}&, and given a list of argument types dc_args of length m where m <= n, then: dataConInstUnivs dc dc_args  Will return: ?[dc_arg_{1}, dc_arg_{2}, ..., dc_arg_{m}, a_{m+1}, ..., a_{n}] ;That is, return the list of universal type variables with a_{1}, a_{2}, ..., a_{m} instantiated with  dc_arg_{1},  dc_arg_{2}, ...,  dc_arg_{m}. It is possible for m to be less than n, in which case the remaining n - m elements will simply be universal type variables (with their kinds possibly instantiated). Examples:Given the data constructor D :: forall a b. Foo a b and dc_args  [Int, Bool], then dataConInstUnivs D dc_args will return  [Int, Bool].Given the data constructor D :: forall a b. Foo a b and dc_args [Int], then @dataConInstUnivs D dc_args will return [Int, b].Given the data constructor E :: forall k (a :: k). Bar k a and dc_args [Type], then @dataConInstUnivs D dc_args will return [Type, (a :: Type)].This is primarily used in GHC.Tc.Deriv.* in service of instantiating data constructors' field types. See 2Note [Instantiating field types in stock deriving] for a notable example of this.\Returns the argument types of the wrapper, excluding all dictionary arguments and without substituting for any type variables\Returns constraints in the wrapper type, other than those in the dataConEqSpec\Returns the arg types of the worker, including *all* non-dependent evidence, after any flattening has been done and without substituting for any type variables\ The string package:module.name identifying a constructor, which is attached to its info table and used by the GHCi debugger and the heap profiler\Vanilla (8s are those that are nice boring Haskell 98 constructors\ Is this the ( of a newtype?]Should this DataCon be allowed in a type even without -XDataKinds? Currently, only Lifted & Unlifted]Were the type variables of the data con written in a different order than the regular order (universal tyvars followed by existential tyvars)?This is not a cheap test, so we minimize its use in GHC as much as possible. Currently, its only call site in the GHC codebase is in  mkDataConRep in MkId , and so ] is only called at most once during a data constructor's lifetime.]Extract the type constructor, type argument, data constructor and it's representation4 argument types from a type if it is a product type.Precisely, we return Just" for any data type that is all of:$Concrete (i.e. constructors visible)Single-constructor... which has no existentialsWhether the type is a data type or a newtype.\"Is the constructor declared infix?#TyConRepName for the promoted TyCon(Strictness/unpack annotations, from userField labels for the constructor, if it is a record, otherwise empty Universals. Existentials.6TyVars which must be instantiated with concrete types User-written -/s. These must be Inferred/Specified. See Note [TyVarBinders in DataCons] GADT equalities 0Theta-type occurring before the arguments proper Original argument types Original result type See comments on CRepresentation type constructorConstructor tag:The "stupid theta", context of the data declaration e.g. data Eq a => T a ... Worker IdRepresentation\A datacon with no existentials or equality constraints However, it can have a dcTheta (notably it can be a class dictionary, with superclasses)Instantiated at these types]A product type, perhaps\]]\]\\((\\(\\\\(\\\(\\\\\\\\\](\(\\\(\\((]((\\\\\\\\\]\\\\\\\((\\\\\(]]&(\(\\\\\\\(\\\\\\\\\ ((\\\\\\\ \\ \\\\\\\ \(\\\\\ \\&\\((\\\(\\\\\(\\((\(\\\\(\]\(\\\(\\((\\\\\]\\\\\(]\\(]]]]\\\\\\](]  ] ] $] "] ] ] ] #] ] ]  ] ] ] ] ]] None ^Gets rid of the stuff that prevents us from understanding the runtime representation of a type. Including: 1. Casts 2. Newtypes 3. Foralls 4. Synonyms But not type/data families, because we don't have the envs to hand.^Count the arity of a function post-unarisation, including zero-width arguments.The post-unarisation arity may be larger than the arity of the original function type. See Note [Unarisation].^Give the demands on the arguments of a Core constructor application (Con dc args) at runtime. Assumes the constructor is not levity polymorphic. For example unboxed tuples won't work.^ True if the type has zero width.^Given the arguments of a sum type constructor application, return the unboxed sum rep type.E.g.+(# Int# | Maybe Int | (# Int#, Float# #) #)We call `ubxSumRepType [ [IntRep], [LiftedRep], [IntRep, FloatRep] ]`, which returns [WordSlot, PtrSlot, WordSlot, FloatSlot]INVARIANT: Result slots are sorted (via Ord SlotTy), except that at the head of the list we have the slot for the tag.Returns the bigger type if one fits into the other. (commutative)Note that lifted and unlifted pointers are *not* in a fits-in relation for the reasons described in Note [Don't merge lifted and unlifted slots] in GHC.Stg.Unarise.^,Discovers the primitive representation of a . Returns a list of L: it's a list because of the possibility of no runtime representation (void) or multiple (unboxed tuple/sum) See also Note [Getting from RuntimeRep to PrimRep]^,Discovers the primitive representation of a . Returns a list of L: it's a list because of the possibility of no runtime representation (void) or multiple (unboxed tuple/sum) See also Note [Getting from RuntimeRep to PrimRep] Returns Nothing if rep can't be determined. Eg. levity polymorphic types.^Like ^(, but assumes that there is at most one L output; an empty list of PrimReps becomes a VoidRep. This assumption holds after unarise, see Note [Post-unarisation invariants]. Before unarise it may or may not hold. See also Note [RuntimeRep and PrimRep] and Note [VoidRep]^%Find the runtime representation of a . Defined here to avoid module loops. Returns a list of the register shapes necessary. See also Note [Getting from RuntimeRep to PrimRep]Take a kind (of shape TYPE rr) and produce the Ls of values of types of this kind. See also Note [Getting from RuntimeRep to PrimRep]^Take a kind (of shape `TYPE rr` or `CONSTRAINT rr`) and produce the Ls of values of types of this kind. See also Note [Getting from RuntimeRep to PrimRep] Returns Nothing if rep can't be determined. Eg. levity polymorphic types.^7Take a type of kind RuntimeRep and extract the list of L that it encodes. See also Note [Getting from RuntimeRep to PrimRep]. The  [PrimRep]% is the final runtime representation after unarisation.^7Take a type of kind RuntimeRep and extract the list of L that it encodes. See also Note [Getting from RuntimeRep to PrimRep]. The  [PrimRep]% is the final runtime representation after unarisation.Returns Nothing: if rep can't be determined. Eg. levity polymorphic types.^ Convert a L to a  of kind RuntimeRep^Convert a PrimRep back to a Type. Used only in the unariser to give types to fresh Ids. Really, only the type's representation matters. See also Note [RuntimeRep and PrimRep]0^^^^^^^^^^^^^^^^^^^^^^LLLLLLLLLLLLLLLL^^^^^^^^^^0^^^^^^^^^LLLLLLLLLLLLLLLL^^^^^^^^^^^^^^^^^^^^^^^^ ^ ^None)@]A demand transformer> is a monotone function from an incoming evaluation context (]) to a ], describing how the denoted thing (i.e. expression, function) uses its arguments and free variables, and whether it diverges.See Note [Understanding DmdType and DmdSig] and Note [DmdSig: demand signatures, and demand-sig arity]]The depth of the wrapped ] encodes the arity at which it is safe to unleash. Better construct this through ^.. See Note [Understanding DmdType and DmdSig]]Characterises how an expressionEvaluates its free variables (]) including divergence infoEvaluates its arguments (])]Demand on arguments]=Demands on free variables. See Note [Demand type Divergence]]9Captures the result of an evaluation of an expression, byListing how the free variables of that expression have been evaluated (])7Saying whether or not evaluation would surely diverge (])See Note [Demand env Equality].]] characterises whether something surely diverges. Models a subset lattice of the following exhaustive set of divergence results: nnontermination (e.g. loops)ithrows imprecise exceptionpthrows precise exceptioncconverges (reduces to WHNF).The different lattice elements correspond to different subsets, indicated by juxtaposition of indicators (e.g. nc definitely doesn't throw an exception, and may or may not reduce to WHNF).  Dunno (nipc) | ExnOrDiv (nip) | Diverges (ni) %As you can see, we don't distinguish n and i. See Note [Precise exceptions and strictness analysis] for why p is so special compared to i.]5Definitely throws an imprecise exception or diverges.]Definitely throws a *precise* exception, an imprecise exception or diverges. Never converges, hence ]! See scenario 1 in Note [Precise exceptions and strictness analysis].]7Might diverge, throw any kind of exception or converge.]A sub-demand describes an evaluation context (in the sense of an operational semantics), e.g. how deep the denoted thing is going to be evaluated. See ] for examples.See Note [SubDemand denotes at least one evaluation] for a more detailed description of what a sub-demand means.See Note [Demand notation] for the extensively used short-hand notation. See also Note [Why Boxity in SubDemand and not in Demand?].]Polymorphic demand, the denoted thing is evaluated arbitrarily deep, with the specified cardinality at every level. The   applies only to the outer evaluation context as well as all inner evaluation context. See Note [Boxity in Poly] for why we want it to carry  . Expands to  via  and to ] via ].Poly b n is semantically equivalent to  Prod b [n :* Poly b n, ...] or Call n (Poly Boxed n)@.  and ] do these rewrites.In Note [Demand notation]: L === P(L,L,...) and  L === C(L), B === P(B,B,...) and  B === C(B), !A === !P(A,A,...) and  !A === C(A)(, and so on.We'll only see ] with ] (B), ] (A), ] (L) and sometimes ] (S) through ], never ] (M) or ]$ (1) (grep the source code). Hence ], which is closed under lub and plus.,Why doesn't this constructor simply carry a ] instead of its fields? See Note [Call SubDemand vs. evaluation Demand]. Call n sd% describes the evaluation context of n function applications (with one argument), where the result of each call is evaluated according to sd. sd describes program traces in which the denoted thing was called at all, see Note [SubDemand denotes at least one evaluation]. That Note also explains why it doesn't make sense for n( to be absent, hence we forbid it with ]3. Absent call demands can still be expressed with ]. Used only for values of function type. Use the smart constructor  whenever possible!] Prod b ds describes the evaluation context of a case scrutinisation on an expression of product type, where the product components are evaluated according to ds. The   b6 says whether or not the box of the product was used.]A demand describes.How many times a variable is evaluated, via a ] inality, and0How deep its value was evaluated in turn, via a ]. C(1,d).]mkCalledOnceDmds n d returns C(1,C1...C(1,d)) where there are n C1's.]Peels one call level from the sub-demand, and also returns how many times we entered the lambda body.] Extract the ] of a ]. PRECONDITION: The SubDemand must be used in a context where the expression denoted by the Demand is under evaluation.]"See Note [Computing one-shot info]]"See Note [Computing one-shot info]]"See Note [Computing one-shot info]]*saturatedByOneShots n C(M,C(M,...)) = True  = There are at least n nested C(M,..) calls. See Note [Demand on the worker] in GHC.Core.Opt.WorkWrap:See Note [Asymmetry of plusDmdType], which concludes that < needs to be symmetric. Strictly speaking, we should have (plusDivergence Dunno Diverges = ExnOrDiv. But that regresses in too many places (every infinite loop, basically) to be worth it and is only relevant in higher-order scenarios (e.g. Divergence of f (throwIO blah)). So  currently is  glbDivergence , really.In a non-strict scenario, we might not force the Divergence, in which case we might converge, hence Dunno.] True if the ] indicates that evaluation will not return. See Note [Dead ends].] Build a potentially terminating ]< from a finite map that says what has been evaluated so far]] is a monoid via ] and ]; this is its msum]%Compute the least upper bound of two ]*s elicited /by the same incoming demand/!]The demand type of doing nothing (lazy, absent, no Divergence information). Note that it is 'not' the top of the lattice (which would be "may use everything"), so it is (no longer) called topDmdType.The demand type of an unspecified expression that is guaranteed to throw a (precise or imprecise) exception or diverge.This makes sure we can use the demand type with n arguments after eta expansion, where n must not be lower than the demand types depth. It appends the argument list with the correct .)A conservative approximation for a given ] in case of an arity decrease. Currently, it's just nopDmdType.^When e is evaluated after executing an IO action that may throw a precise exception, we act as if there is an additional control flow path that is taken if e throws a precise exception. The demand type of this control flow path * is lazy and absent (]9) and boxed in all free variables and arguments * has ] ]> result See Note [Precise exceptions and strictness analysis]#So we can simply take a variant of ],  . Why not ]? Because then the result of e can never be ]4! That means failure to drop dead-ends, see #18086.^Turns a ] computed for the particular & into a ] unleashable at that arity. See Note [Understanding DmdType and DmdSig].^True if the signature diverges or throws an exception in a saturated call. See Note [Dead ends].^True if the signature diverges or throws an imprecise exception in a saturated call. NB: In constrast to ^ this returns False for ]. See Note [Dead ends] and Note [Precise vs imprecise exceptions].^9True when the signature indicates all arguments are boxed^Returns true if an application to n value args would diverge or throw an exception.If a function having ] is applied to a less number of arguments than its syntactic arity, we cannot say for sure that it is going to diverge. Hence this function conservatively returns False in that case. See Note [Dead ends].Transfers the boxity of the left arg to the demand structure of the right arg. This only makes sense if applied to new and old demands of the same value.^ Add extra (]7) arguments to a strictness signature. In contrast to ^, this prepends8 additional argument demands. This is used by FloatOut.^We are expanding (x y. e) to (x y z. e z) or reducing from the latter to the former (when the Simplifier identifies a new join points, for example). In contrast to ^, this appends extra arg demands if necessary. This works by looking at the ] (which was produced under a call demand for the old arity) and trying to transfer as many facts as we can to the call demand of new arity. An arity increase (resulting in a stronger incoming demand) can retain much of the info, while an arity decrease (a weakening of the incoming demand) must fall back to a conservative default.^ Extrapolate a demand signature (] ) into a ].Given a function's ] and a ] for the evaluation context, return how the function evaluates its free variables and arguments.^ A special ] for data constructors that feeds product demands into the constructor arguments.^ A special ] for dictionary selectors that feeds the demand on the result into the indicated dictionary component (if saturated). See Note [Demand transformer for a dictionary selector].^1Remove the demand environment from the signature.^#Remove all `C_01 :*` info (but not CM sub-demands) from the demand^#Remove all `C_01 :*` info (but not CM. sub-demands) from the strictness signature^Drop all boxity^See Note [Demand notation] Current syntax was discussed in #19016.^See Note [Demand notation]^See Note [Demand notation]^)We have to respect Poly rewrites through  and ].^See Note [Demand env Equality].]depending on saturation]^]]]]]]^]^]^^^^]^]]^]]^]]]]^^]^^]]]]]]]]]]]]]]]^^]]^]]]]^]]]^]]^]^]]]]]]]^]]^^]^^^]]]]]]]]]]^^^^]]^^^^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]  ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]^]^^^]^]]^^^^^^^^^^^^^^^^]^^^]]]]^^^^^^^^^^^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ None) ^The arity of the wrapped ^ is the arity at which it is safe to unleash. See Note [Understanding DmdType and DmdSig] in GHC.Types.Demand^The result of ^.^The abstract domain A_t+ from the original 'CPR for Haskell' paper.^^) eventually unleashed when applied to ^ arguments^Number of value arguments the denoted expression eats before returning the ^ The number of field Cprs equals \&. If all of them are top, better use %, as ensured by the pattern synonym ^.FlatConCpr tag is an efficient encoding for  tag [TopCpr..]5. Purely for compiler perf. Can be constructed with ^.^ Unpacks a ^-shaped ^ and returns the field ^s wrapped in a ^. Otherwise, it returns ^ with the appropriate ^ to assume for each field. The use of ^( allows O(1) space for the common, non-^ case.^Turns a ^ computed for the particular & into a ^ unleashable at that arity. See Note [Understanding DmdType and DmdSig] in GHC.Types.Demand^Add extra value args to CprSig^BNF: cpr ::= '' -- TopCpr | n -- FlatConCpr n | n '(' cpr1 ',' cpr2 ',' ... ')' -- ConCpr n [cpr1,cpr2,...] | 'b' -- BotCpr*Examples: * `f x = f x` has result CPR b" * `1(1,)` is a valid (nested) ^! denotation for `(I# 42#, f 42)`.^BNF: cpr_ty ::= cpr -- short form if arty == 0 | '\' arty '.' cpr -- if arty > 0Examples: * `f x y z = f x y z` has denotation `3.b` * `g !x = (x+1, x+2)` has denotation `1.1(1,1)`._Only print the CPR result^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ ^ ^ ^ ^ _ _ __( (NoneJaStandardFormInfo tells whether this thunk has one of a small number of standard formsaInformation about an identifier, from the code generator's point of view. Every identifier is bound to a LambdaFormInfo in the environment, which gives the code generator enough info to be able to tail call or return that identifier.b9Maps names in the current module to their LambdaFormInfosbCodegen-generated Id infos, to be passed to downstream via interfaces.This stuff is for optimization purposes only, they're not compulsory.When CafInfo of an imported Id is not known it's safe to treat it as CAFFY.When LambdaFormInfo of an imported Id is not known it's safe to treat it as `LFUnknown True` (which just says "it could be anything" and we do slow entry).See also Note [Conveying CAF-info and LFInfo between modules] above.b,The C stub which is used for IPE informationb;LambdaFormInfos of exported closures in the current module.bExported Non-CAFFY closures in the current module. Everything else is either not exported of CAFFY.bbbbbaaaabaaabbaaaabbbbbaabaaabbaaaaaab %b #b NonebA constructor-like thingbIs this a 'vanilla' constructor-like thing (no existentials, no provided constraints)?bNumber of argumentsb"Names of fields used for selectorsbThe 3* (arity and field labels) associated to a b. Compute a 3 from a b.bReturns just the instantiated value argument types of a b, (excluding dictionary args)b- s for the type variables of the b. For pattern synonyms, this will always consist of the universally quantified variables followed by the existentially quantified type variables. For data constructors, the situation is slightly more complicated@see )Note [DataCon user type variable binders] in GHC.Core.DataCon.b0Existentially quantified type/coercion variablesbThe "stupid theta" of the b , such as  data Eq a in: data Eq a => T a = ...It is empty for b* as they do not allow such contexts. See Note [The stupid context] in GHC.Core.DataCon.bb returns True except for uni-directional pattern synonyms, which have no builderb7Returns the strictness information for each constructorb%Returns the type of the whole patternbThe "full signature" of the b returns, in order:,1) The universally quantified type variables72) The existentially quantified type/coercion variables3) The equality specification;4) The provided theta (the constraints provided by a match)<5) The required theta (the constraints required for a match)6) The original argument types (i.e. before any change of the representation of the type)7) The original result typeb5Extract the type for any given labelled field of the bb-The ConLikes that have *all* the given fieldsbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb b b b b b None3A list of conlikes which represents a complete pattern match. These arise from COMPLETE signatures. See also Note [Implementation of COMPLETE pragmas].;The optional, concrete result TyCon name the set applies toThe set of constructor names Does this COMPLETE set apply at this type?See the part about "result type constructors" in Note [Implementation of COMPLETE pragmas] in GHC.HsToCore.Pmc.Solver.  - -;% %ANone<Expressions where binders are sThe common case for the type of binders and variables when we are manipulating the Core language within GHCThis is the data type that represents GHCs core intermediate language. Currently GHC uses System FC  https://www.microsoft.com/en-us/research/publication/system-f-with-type-equality-coercions/ for this purpose, which is closely related to the simpler and better known System F  %http://en.wikipedia.org/wiki/System_F.We get from Haskell source to this Core language in a number of stages: The source code is parsed into an abstract syntax tree, which is represented by the data type  with the names being This syntax tree is renamed, which attaches a > to every  (yielding a ?) to disambiguate identifiers which are lexically identical. For example, this program: 3 f x = let f x = x + 1 in f (x - 2) Would be renamed by having Unique,s attached so it looked something like this:  f_1 x_2 = let f_3 x_4 = x_4 + 1 in f_3 (x_2 - 2) 'But see Note [Shadowing in Core] below. The resulting syntax tree undergoes type checking (which also deals with instantiating type class arguments) to yield a  type that has B as it's names.Finally the syntax tree is  desugared from the expressive  type into this  type, which has far fewer constructors and hence is easier to perform optimization, analysis and code generation on.The type parameter b3 is for the type of binders in the expression tree.0The language consists of the following elements:5Variables See Note [Variable occurrences in Core]Primitive literals.Applications: note that the argument may be a 7. See Note [Representation polymorphism invariants]Lambda abstraction See Note [Representation polymorphism invariants]Recursive and non recursive lets. Operationally this corresponds to allocating a thunk for the things bound and then executing the sub-expression.See Note [Core letrec invariant] See Note [Core let-can-float invariant] See Note [Representation polymorphism invariants] See Note [Core type and coercion invariant]Case expression. Operationally this corresponds to evaluating the scrutinee (expression examined) to weak head normal form and then examining at most one level of resulting constructor (i.e. you cannot do nested pattern matching directly with this).The binder gets bound to the value of the scrutinee, and the * must be that of all the case alternatives0IMPORTANT: see Note [Case expression invariants]Cast an expression to a particular type. This is used to implement newtypes (a newtype. constructor or destructor just becomes a _ in Core) and GADTs.Ticks. These are used to represent all the source annotation we support: profiling SCCs, HPC ticks, and GHCi breakpoints.;A type: this should only show up at the top level of an Arg A coercion_A clone of the _0 type but allowing annotation at every tree node_A clone of the _0 type but allowing annotation at every tree node_A clone of the 0 type but allowing annotation at every tree node_;Annotated core: allows annotation at every node in the tree_ Binders are tagged with a t_$Case alternatives where binders are s_!Binding groups where binders are s_'Argument expressions where binders are s__& says when unfolding should take place_Properties of a _ that could be computed on-demand from its template. See Note [UnfoldingCache]_ Records the  unfolding of an identifier, which is approximately the form the identifier would have if we substituted its definition in for the identifier. This type should be treated as abstract everywhere except in GHC.Core.Unfold_+We have no information about the unfolding._:We have no information about the unfolding, because this  came from an hi-boot1 file. See Note [Inlining and hs-boot files] in GHC.CoreToIface for what this is used for._%It ain't one of these constructors.  OtherCon xs also indicates that something has been evaluated and hence there's no point in re-evaluating it.  OtherCon [] is used even for non-data-type values to indicated evaluated-ness. Notably: 1data C = C !(Int -> Int) case x of { C f -> ... }Here, f gets an  OtherCon [] unfolding._;An unfolding with redundant cached information. Parameters:uf_tmpl: Template used to perform unfolding; NB: Occurrence info is guaranteed correct: see Note [OccInfo in unfoldings and rules]'uf_is_top: Is this a top level binding? uf_is_value:  exprIsHNF* template (cached); it is ok to discard a  on this variableuf_is_work_free: Does this waste only a little work if we expand it inside an inlining? Basically this is a cached version of exprIsWorkFree!uf_guidance: Tells us about the size of the unfolding template_The / in the _ is a superset of variables that are currently in scope. See Note [The InScopeSet invariant]._A _ is:"Local" if the function it is a rule for is defined in the same module as the rule itself."Orphan" if nothing on the LHS is defined in the same module as the rule itself_Built-in rules are used for constant folding and suchlike. They have no free variables. A built-in rule is always visible (there is no such thing as an orphan built-in rule.)_True iff the fn at the head of the rule is defined in the same module as the rule and is not an implicit  (like a record selector, class operation, or data constructor). This is different from _, where a rule can avoid being an orphan if *any* Name in LHS of the rule was defined in the same module as the rule._%Whether or not the rule is an orphan._ the rule was defined in, used to test if we should see an orphan rule._True  = this rule is auto-generated (notably by Specialise or SpecConstr) False  = generated at the user's behest See Note [Trimming auto-rules] in GHC.Iface.Tidy% for the sole purpose of this field._Right hand side of the rule Occurrence info is guaranteed correct See Note [OccInfo in unfoldings and rules]_Left hand side arguments_Variables quantified over_7Name at the head of each argument to the left hand side_ Name of the B at the head of this rule_When the rule is active_1Name of the rule, for communication with the user_This function does the rewrite. It given too many arguments, it simply discards them; the returned  is just the rewrite of _ applied to the first _ args_Number of arguments that _1 consumes, if it fires, including type arguments_Is this instance an orphan? If it is not an orphan, contains an ? witnessing the instance's non-orphanhood. See Note [Orphans]_Binding, used for top level bindings in a module and local bindings in a let._3A case alternative constructor (i.e. pattern match)_ A literal: case e of { 1 -> ... } Invariant: always an *unlifted* literal See Note [Literal alternatives]_Trivial alternative: case e of { _ -> ... }_A case split alternative. Consists of the constructor leading to the alternative, the variables bound from the constructor, and the expression to be executed given that binding. The default alternative is (DEFAULT, [], rhs)_Type synonym for expressions that occur in function argument positions. Only _ should contain a  at top level, general  should not_+Helper function. You can use the result of _ with ` for instance._ & binds makes a single mutually-recursive bindings with all the rhs/lhs pairs in binds_ & binds makes one non-recursive binding for each rhs/lhs pairs in binds_Returns true if _ is orphan._Returns true if _ is not an orphan._The number of arguments the _4 must be applied to before the rule can match on it`The  of the B' at the head of the rule left hand side`Set the  of the B' at the head of the rule left hand side`There is no known _` body) == (x -> f body)`Attempt to remove the last N arguments of a function call. Strip off any ticks or coercions encountered along the way and any at the end.`Like  collectArgs, but also looks through floatable ticks if it means that we can find more arguments.`$Will this variable exist at runtime?`/Will this argument expression exist at runtime?`Returns True for value arguments, false for type args NB: coercions are value arguments (zero width, to be sure, like State#, but still value args).`Returns True iff the expression is a  or  expression at its top level`Returns True iff the expression is a  expression at its top level`Returns True iff the expression is a ; expression at its top level. Note this does NOT include s.`8The number of binders that bind values rather than types`The number of argument expressions that are values rather than types at their top level`Takes a nested application expression and returns the function being applied and the arguments to which it is applied`As ` but for _ rather than `As ` but for _ rather than ``````_```````````````````````````_``_````````_````````````_```````````````````````````````_````_````````````'._____________________________________________________________________________________________________________________E&%%%%%--------______________________________`-_______-_---_______-_--_``````````````````````````````_.`````````````````````````````______________________________%%%%%````````````````````````````'_________________````````______________________&____E_`````_`__```` ` ` ` ` 3` ` `` ` ```;None 3 T9Identifier DetailsThe  of an Id7 give stable, and necessary, information about the Id.Identifier InformationAn  gives optional information about an Id. If present it never lies, but it may not be present, in which case there is always a conservative assumption which can be made.Two Id:s may have different info even though they have the same Unique (and are hence the same Id); for example, one might lack the properties attached to the other. Most of the ; gives information about the value, or definition, of the Id4, independent of its usage. Exceptions to this are b, b, b and b.!Performance note: when we update , we have to reallocate this entire record, so it is a good idea not to let this data structure get too big. Check if an  says b.Just a synonym for b. Written separately so it can be exported in the hs-boot file.Basic . that carries no useful information whatsoeverbTick box for Hpc-style coverageb%Constant applicative form InformationRecords whether an Id+ makes Constant Applicative Form referencesbIndicates that the Id is for either: A function or static constructor that refers to one or more CAFs, orA real live CAFb9A function or static constructor that refers to no CAFs.bRule Information$Records the specializations of this Id, that we know about in the form of rewrite _s that target thembInline Pragma InformationTells when the inlining is active. When it is active the thing may be inlined, depending on how big it is.If there was an INLINE pragma, then as a separate matter, the RHS will have been made to look small with a Core inline Note The default b is %, so the info serves entirely as a way to inhibit inlining until we want itbArity InformationAn b of n, tells us that partial application of this Id to up to n-1* value arguments does essentially no work.7That is not necessarily the same as saying that it has n6 leading lambdas, because coerces may get in the way.The arity might increase later in the compilation process, if an extra lambda floats up to the binding site. Invariant: the & of an Id must never exceed the number of value arguments that appear in the type of the Id'. See Note [Arity and function types].Encodes arities, OneShotInfo, CafInfo. From least-significant to most-significant bits:Bit 0 (1): OneShotInfoBit 1 (1): CafInfoBit 2 (1): unusedBits 3-32(30): Call Arity infoBits 33-62(30): Arity infob If lfInfo = Just info, then the info is guaranteed correct0. If lfInfo = Nothing, then we do not have a a for this Id, so (for imported Ids) we make a conservative version. See Note [The LFInfo of Imported Ids] in GHC.StgToCmm.Closure For locally-defined Ids other than DataCons, the b field is always Nothing. See also Note [LFInfo of DataCon workers and wrappers]Bitfield packs CafInfo, OneShotInfo, arity info, and call arity info in one 64-bit word. Packing these fields reduces size of  from 12 words to 7 words and reduces residency by almost 4% in some programs. See #17497 and associated MR.See documentation of the getters for what these packed fields mean.bID demand informationbInformation on whether the function will ultimately return a freshly allocated constructor.bA strictness signature. Describes how a function uses its arguments See Note [idArity varies independently of dmdTypeDepth] in GHC.Core.Opt.DmdAnalbHow the Id occurs in the programb"Any inline pragma attached to the IdbThe Id s unfoldingbSpecialisations of the Ids function which exist. See Note [Specialisations and RULES in IdInfo]b%Parent of a record selector function.Either the parent  or b1 depending on the origin of the record selector.For a data family, this is the instance , **not** the family .b*Parent of a data constructor record field.For a data family, this is the instance .b/Parent of a pattern synonym record field: the b itself.bThe Id for a record selectorbThe Id is for a data constructor workerbThe Id is for a data constructor wrapperbThe Id, is a superclass selector or class operationb'A representation-polymorphic pseudo-op.bThe Id is for a primitive operator.bThe Id is for a foreign call. Type will be simple: no type families, newtypes, etcbThe Id4 is for a HPC tick box (both traditional and binary)b$A dictionary function. Bool = True  = the class has only one method, so may be implemented with a newtype, so it might be bad to be strict on this dictionaryb&A coercion variable This only covers  un-lifted coercions, of type (t1 ~# t2) or (t1 ~R# t2), not their lifted variantsbAn Id< for a join point taking n arguments Note [Join points] in GHC.Core+ Can also work as a WorkerLikeId if given &s. See Note [CBV Function Ids] The [CbvMark] is always empty (and ignored) until after Tidy.bAn Id for a worker like function, which might expect some arguments to be passed both evaluated and tagged. Worker like functions are create by W/W and SpecConstr and we can expect that they aren't used unapplied. See Note [CBV Function Ids] See Note [Tag Inference] The [CbvMark] is always empty (and ignored) until after Tidy for ids from the current module.bWhich type variables of this representation-polymorphic 'Id should be instantiated to concrete type variables?See Note [Representation-polymorphism checking built-ins] in GHC.Tc.Utils.Concrete.b+Info about a lambda-bound variable, if the Id is onebId arity, as computed by GHC.Core.Opt.Arity%. Specifies how many arguments this Id9 has to be applied to before it does any meaningful work.bId CAF infobHow this is called. This is the number of arguments to which a binding can be eta-expanded without losing any sharing. n  =% all calls have at least n argumentsbEssentially returns the b field, but does not expose the unfolding of a strong loop breaker.This is the right thing to call if you plan to decide whether an unfolding will inline.b True of a non-loop-breaker Id that has a stable; unfolding that is (a) always inlined; that is, with an _ guidance, or (b) a DFunUnfolding which never needs to be inlinedcMore informative  we can use when we know the Id has no CAF referencesc$It is always safe to assume that an Id has an arity of 0c1Assume that no specializations exist: always safecRetrieve the locally-defined free variables of both the left and right hand sides of the specialization rulescChange the name of the function the rule is keyed on all of the _sAssumes that the Id$ has CAF references: definitely safecThis is used to remove information on lambda binders that we have setup as part of a lambda group, assuming they will be applied all at once, but turn out to be part of an unsaturated lambda as in e.g: (\x1. \x2. e) arg1c9Lazify (remove the top-level demand, only) the demand in  Keep nested demands; see Note [Floatifying demand info when floating] in GHC.Core.Opt.SetLevelscFloatify the demand in  But keep nested demands; see Note [Floatifying demand info when floating] in GHC.Core.Opt.SetLevelsc.Remove usage (but not strictness) info on the cRemove usage environment info from the strictness signature on the c'Zap info that depends on free variablesZaps any core unfolding, but  preserves/ evaluated-ness, i.e. an unfolding of OtherCon&''''&'bbbccbbcbcccbcccbbbccbbbcccbbbbbcbbbcbcccccccca&&&&&&&&&&&&&&&&&&%%%bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb&bbbbbbbbc&&&b&&bccccccccccbcbbcbbbcbcbccbbbbbbb&&&&&&&&&&'''bb&&&&%%%''bbcccccbbbbbbccbbabbbbbbb bbbbbbbbcccc !c c c ccc cBNone#cLike c, but skips non-Ids. Useful for scaling a mixed list of ids and tyvars.cNot only does this set the  ;, it also evaluates the type to try and reduce space usagec'For an explanation of global vs. local s, see GHC.Types.Var.Var#globalvslocalcMake a global % without any extra information at allcMake a global - with no global information but some generic c'For an explanation of global vs. local s, see GHC.Types.Var#globalvslocalcMake a local CoVarcLike c6, but checks the type to see if it should make a covarcCreate a local  that is marked as exported. This prevents things attached to it from being removed as dead code. See Note [Exported LocalIds]cCreate a system local . These are local s (see Var#globalvslocal3) that are created by the compiler out of thin aircLike c+, but checks to see if we have a covar typecCreate a user local . These are local s (see GHC.Types.Var#globalvslocal8) with a name and location that the user might recognizecLike c', but checks if we have a coercion typecWorkers get local names. CoreTidy$ will externalise these if necessaryc Create a template local: a family of system local s in bijection with Ints, typically used in unfoldingsc-Create a template local for a series of typescCreate a template local for a series of type, but start from a specified template localcIf the , is that for a record selector, extract the b. Panic otherwise.cAn Id for which we might require all callers to pass strict arguments properly tagged + evaluated.See Note [CBV Function Ids]cDoesn't return strictness marksc*Get from either the worker or the wrapper  to the ('. Currently used only in the desugarer. INVARIANT: idDataCon (dataConWrapId d) = d : remember, (, can return either the wrapper or the workercReturns True of an  which may not have a binding, even though it is defined in this module.cc tells whether an s info is implied by other declarations, so we don't need to put its signature in an interface file, even if it's mentioned in some other interface unfolding.cThis function counts all arguments post-unarisation, which includes arguments with no runtime representation -- see Note [Unarisation and arity]cReturns true if an application to n args diverges or throws an exception See Note [Dead ends] in GHC.Types.Demand.c Accesses the Id's b.cc says whether either (a) the  has a strict demand placed on it or (b) definitely has a "strict type", such that it can always be evaluated strictly (i.e an unlifted type) We need to check (b) as well as (a), because when the demand for the given z hasn't been computed yet but z9 has a strict type, we still want `isStrictId id` to be M. Returns False if the type is levity polymorphic; False is always safe.c Returns the s unfolding, but does not expose the unfolding of a strong loop breaker. See b.?If you really want the unfolding of a strong loopbreaker, call c.cReturns an unfolding only if (a) not a strong loop breaker and (b) always activecReturns an unfolding only if (a) not a strong loop breaker and (b) active in according to is_activecExpose the unfolding if there is one, including for loop breakersc5If all marks are NotMarkedStrict we just set nothing.c2Remove any cbv marks on arguments from a given Id.c-Turn this id into a WorkerLikeId if possible.c:Similar to trimUnfolding, but also removes evaldness info.cccccddccdcccdcccccdddcccdcdddcdccccccdcccccccccccccccccccccccccccccccccccccccccccccdccccccccdcccccccdccdddccccdddddcdcddcdddcdd---.....---_-----.----cccccccccccccccccccccccc--ccccc.---cc-cccccdddddddcddccccc...ccccccccccccccccccdcccc-ccccccddddddddddcccddddddd_ccccccccccdddddccccccccccccccccccccccddddddDNone A global typecheckable-thing, essentially anything that has a name. Not to be confused with a  TcTyThing, which is also a typecheckable thing but in the *local* context. See GHC.Tc.Utils.Env for how to retrieve a  given a .dClass that abstracts out the common ability of the monads in GHC to lookup a  in the monadic environment by . Provides a number of related convenience functions for accessing particular kinds of dDetermine the  s brought into scope by another  other than itself. For example, Id's don't have any implicit TyThings as they just bring themselves into scope, but classes bring their dictionary datatype, type constructor and some selector functions into scope, just for a start!dReturns True if there should be no interface-file declaration for this thing on its own: either it is built-in, or it is part of some other declaration, or it is generated implicitly by some other declaration.dtyThingParent_maybe x returns (Just p) when pprTyThingInContext should print a declaration for p (albeit with some "..." in it) when asked to show x It returns the *immediate* parent. So a datacon returns its tycon but the tycon could be the associated type of a class, so it in turn might have a parent.dThe 4 s that a - should bring into scope. Used to build the 4 for the InteractiveContext.d?Obtain information pertinent to the renamer about a particular .This extracts out renamer information from typechecker information.dGet the  from a 4 if it is a type constructor thing. Panics otherwisedGet the J from a 2 if it is a coercion axiom thing. Panics otherwisedGet the ( from a 4 if it is a data constructor thing. Panics otherwisedGet the b from a 5 if it is a data constructor thing. Panics otherwisedGet the  from a < if it is a id *or* data constructor thing. Panics otherwisedddddddddddddddddddddddddddddd!ddddddddddddddddddddddddddddddd d d 4None A renaming substitution from s to s. Like /4, but not maintaining pairs of substitutions. Like , but with the domain being s instead of entire CoreExpr.  emptySubst =  /Constructs a new % assuming the variables in the given / are in scope.Substitutes an " for another one according to the + given in a way that avoids shadowing the /', returning the result and an updated 1 that should be used by subsequent substitutions. 4substBndrs = runState . traverse (state . substBndr)Substitutes an occurrence of an identifier for its counterpart recorded in the .Substitutes an occurrence of an identifier for its counterpart recorded in the . Does not generate a debug warning if the identifier to to substitute wasn't in scope.Add the  to the in-scope set and remove any existing substitutions for it.Add a substitution for an  to the : you must ensure that the in-scope set is such that TyCoSubst Note [The substitution invariant] holds after extending the substitution like this.  None +3%The type used in binder positions in  GenStgExprs.Let(-no-escape)-bound thing with a flag indicating whether it occurs as an argument or in a nullary application (see GHC.Stg.Lift.Analysis#arg_occs).Every other kind of binderCaptures details of the syntax tree relevant to the cost model, such as closures, multi-shot lambdas and case expressions.Gets the bound  out a .Returns K for s and L the flag indicating occurrences as argument or in a nullary applications otherwise. free vars how often the RHS was entered   # NoneB %declarations enclosing the breakpointbreakpoint identifier'the breakpoint we stopped at (Nothing  = exception)Essentially a GlobalRdrEnv, but with additional cached values to allow efficient re-calculation when the imports change. Fields are strict to avoid space leaks (see T4029) All operations are in GHC.Runtime.Context. See Note [icReaderEnv recalculation]:Just the things defined at the prompt (excluding imports!)The final environmentªline number (for errors)êfilename (for errors)Ī stepping mode)ŪªĪê)ŪªĪêNonedA measure of the size of the expressions, strictly greater than 0 Counts *leaves*, not internal nodes. Types and coercions are not counted. ddddddddddd dddddddddddd None`dEvaluate all the fields of the - that are generally demanded by the compilerddddddddddddddNone6?A function to produce an annotation for a given right-hand-side-Annotate with the size of the right-hand-side No annotation4Pretty print the argument in a function application.3generate an annotation to place before the bindingbindings to showthe pretty resultdddddddddddddddddddddddddddddddd d d d #d d &d d 7d d 0d 1d 1None &zz p ol returns M if an overloaded literal ol, needs to be parenthesized under precedence p.zz p l returns M if a literal l- needs to be parenthesized under precedence p.See Note [Printing of literals in Core] in GHC.Types.Literal for the reasoning.z0Convert a literal from one index type to anotherzpmPprHsLit pretty prints literals and is used when pretty printing pattern match warnings. All are printed the same (i.e., without hashes if they are primitive and not wrapped in constructors if they are boxed). This happens mainly for too reasons: * We do not want to expose their internal representation * The warnings become too messy/zzzzzzzzzzzzzzzzSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSzzzzzzzzzzzzzzzzz 0z 2z z -z (None  CoreMapX a is the base map from DeBruijn CoreExpr to a, but without the  optimization. CoreMapG a is a map from DeBruijn CoreExpr to a. The extended key makes it suitable for recursive traversal, since it can track binders, but it is strictly internal to this module. If you are including a  inside another , this is the type you want. CoreMap a is a map from  to a3. If you are a client, this is the type you want.[[[[[[[[         0  None# ('Type constructor for n-ary unboxed sum.(=Data constructor for i-th alternative of a n-ary unboxed sum.(Specialization of  for tuples) "type LiftedRep = 'BoxedRep 'Lifted) &type UnliftedRep = 'BoxedRep 'Unlifted)Build the type of a small tuple that holds the specified type of thing Flattens 1-tuples. See Note [One-tuples].eMake a fake, recovery  from an existing one. Used when recovering from errors in type declarationseBuilt-in syntax isn't "in scope" so these OccNames map to wired-in Names with BuiltInSyntax. However, this should only be necessary while resolving names produced by Template Haskell splices since we take care to encode built-in syntax names specially in interface files. See Note [Symbol table representation of names] in GHC.Iface.Binary.Moreover, there is no need to include names of things that the user can't write (e.g. type representation bindings like $tc(,,,)).This is only for Tuple n, not for Unit or SoloSee Note [Small Ints parsing]Analyze a string as the suffix of an OccName of a tuple or sum tycon to determine its arity and boxity (based on the presence of a #).eIf the given name is that of a constraint tuple, return its arity.Cached type constructors, data constructors, and superclass selectors for constraint tuples. The outer array is indexed by the arity of the constraint tuple and the inner array is indexed by the superclass position.Given the TupleRep/SumRep tycon and list of RuntimeReps of the unboxed tuple;sum arguments, produces the return kind of an unboxed tuplesum type constructor. unboxedTupleSumKind [IntRep, LiftedRep] --> TYPE (TupleRep/SumRep [IntRep, LiftedRep])/OccName for n-ary unboxed sum type constructor.OccName for i-th alternative of n-ary unboxed sum data constructor.‡Cached type and data constructors for sums. The outer array is indexed by the arity of the sum and the inner array is indexed by the alternative.eSpecialization of  for sumsÇCreate type constructor and data constructors for n-ary unboxed sum.ć@type ZeroBitRep = 'Tuple '[]e Given a type ty, if ty is not of kind Type, return a data constructor that will box it, and the type of the boxed thing, which does4 now have kind Type. See Note [Boxing constructors]Ň+See Note [Boxing constructors] wrinkle (W1)e,Make a tuple type. The list of types should not include any RuntimeRep specifications. Boxed 1-tuples are flattened. See Note [One-tuples]e,Make a tuple type. The list of types should not include any RuntimeRep specifications. Boxed 1-tuples are *not* flattened. See Note [One-tuples] and Note [Don't flatten tuples from HsSyn] in  GHC.Core.MakeeMake a *promoted* list.eExtract the elements of a promoted list. Panics if the type is not a promoted listf>Replaces constraint tuple names with corresponding boxed ones.fShould this name be considered in-scope, even though it technically isn't?This ensures that we don't filter out information because, e.g., Data.Kind.Type isn't imported. See Note [pretendNameIsInScope].Ƈdeclared infix? datacon name univ tyvars ex tycovarsconcrete tyvarsuser-written tycovarsargseof the elements of the listelementseThe promoted list@B)ee(eede)e((ee(e(eee)edeee)deee)e)e))eeeeeeddeeeefe))eeeee)d()()()()ee)eedefeeeee(eeeeeeeeeee))))))e))))eeeee((ee)eeeeeeeeeedd(((effff(ffeeeeee((eeeeeeeefeeeeeeeee())eee(e(eee(()(()eee(eeeee))e)e))e))e(e)))))))))d()()))e()eee)eee))eOOOOOOMddddddddddeeeeeeedeeeeeeeeeeeeeeeeeeedddddddeee)edeeeeeeeeeeeeedeeeeeeee)ee@eeBeeeeeeeeeeeeeeeeeeeee)e((((()ee)eeeeeeee(efee(eee((ee(ee(eee((e)Me))OOOOOO))))e))))eee)deeedeed)dee))))))))))e)))e)))))))))))))))))))))((((((()))eee((ee((((((e(eeeeeefe(fffffffNoneأPer-module cache of original s given s٣The NameCache makes sure that there is just one Unique assigned for each original name; i.e. (module-name, occ-name) pair and provides something of a lookup mechanism for those names.-Update the name cache with the given function-Update the name cache with the given functionAdditionally, it ensures that the given Module and OccName are evaluated. If not, chaos can ensue: we read the name-cache then pull on mod (say) which does some stuff that modifies the name cache This did happen, with tycon_mod in GHC.IfaceToCore.tcIfaceAlt (DataAlt..) ߣޣݣ٣ڣۣܣأ ٣ڣۣܣݣأޣߣNone*-What caused us to create a f? metavariable? See Note [ConcreteTv] in GHC.Tc.Utils.Concrete.-A f< used to enforce the representation-polymorphism invariants.See  for more information.-$A mapping from skolem type variable  to concreteness information,See Note [Representation-polymorphism checking built-ins] in GHC.Tc.Utils.Concrete.-The  has no outer forall'd type variables which must be instantiated to concrete types.-Is this type variable a concrete type variable, i.e. it is a metavariable with f f?fThe Paterson size of a given type, in the sense of Note [Paterson conditions] in GHC.Tc.Validityafter expanding synonyms,2ignoring coercions (as they are not user written).f?The type mentions a type family, so the size could be anything.f(The type does not mention a type family.f)number of type constructors and variablesf#free tyvars, including repetitions;fIndicates whether a Paterson condition failure occurred in an instance declaration or a type family equation. Useful for differentiating context in error messages.fWhy did the Paterson conditions fail; that is, why was the context P not Paterson-smaller than the head H?2See Note [Paterson conditions] in GHC.Tc.Validity.fSome type variables occur more often in P than in H. See (PC1) in Note [Paterson conditions] in GHC.Tc.Validity.fP contains a type family. See (PC3) in Note [Paterson conditions] in GHC.Tc.Validity.fWhat restrictions are on this metavariable around unification? These are checked in GHC.Tc.Utils.Unify.checkTopShapefThis MetaTv is an ordinary unification variable A TauTv is always filled in with a tau-type, which never contains any ForAlls.fA variant of TauTv, except that it should not be unified with a type, only with a type variable See Note [TyVarTv] in GHC.Tc.Utils.TcMTypef6A unification variable used in the GHCi debugger. It is/ allowed to unify with a polytype, unlike TauTvfA unification variable that can only be unified with a concrete type, in the sense of Note [Concrete types] in GHC.Tc.Utils.Concrete. See Note [ConcreteTv] in GHC.Tc.Utils.Concrete. See also Note [The Concrete mechanism] in GHC.Tc.Utils.Concrete for an overview of how this works in context.fWhat to expect for an argument to a rebindable-syntax operator. Quite like , but allows for holes to be filled in by tcSyntaxOp. The callback called from tcSyntaxOp gets a list of types; the meaning of these types is determined by a left-to-right depth-first traversal of the f tree. So if you pass in >SynAny `SynFun` (SynList `SynFun` SynType Int) `SynFun` SynAny/you'll get three types back: one for the first f, the element) type of the list, and one for the last f". You don't get anything for the f, because you've said positively that it should be an Int, and so it shall be.You'll also get three multiplicities back: one for each function arrow. See also Note [Linear types] in Multiplicity.-This is defined here to avoid defining it in GHC.Tc.Gen.Expr boot file.fAny typef5A rho type, skolemised or instantiated as appropriatef6A list type. You get back the element type of the listf A function.f A known type.fLike f, but on kind levelfLike f, but for an expected type.See f.fAn f which has a fixed RuntimeRep.For a f f , the stored f' must have a fixed RuntimeRep. For an f f, the f field must be of the form  Just frr_orig.f-The type that fills in this hole should be a Type, that is, its kind should be TYPE rr for some rr :: RuntimeRep.Additionally, if the f field is  Just frr_orig then rr must be concrete, in the sense of Note [Concrete types] in GHC.Tc.Utils.Concrete.fSee Note [FixedRuntimeRep context in ExpType] in GHC.Tc.Utils.TcMTypef5See Note [TcLevel of ExpType] in GHC.Tc.Utils.TcMTypefThis  is for debugging onlyfAn expected type to check against during type-checking. See Note [ExpType] in GHC.Tc.Utils.TcMType&, where you'll also find manipulators.fA f is a f# which has a syntactically fixed L in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.In particular, this means that: does not panic,A does not return K.0This property is important in functions such as matchExpectedFunTys, where we want to provide argument types which have a known runtime representation. See Note [Return arguments with a fixed RuntimeRep.fA type which has a syntactically fixed RuntimeRep as per Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.fMake an f suitable for checking.f0Returns the expected type when in checking mode.fReturns the expected type when in checking mode. Panics if in inference mode.fLike f but accepts a regular TcTypefLike mkFunTys but for ffFinds outermost type-family applications occurring in a type, after expanding synonyms. In the list (F, tys) that is returned we guarantee that tys matches F's arity. For example, given type family F a :: * -> * (arity 1) calling tcTyFamInsts on (Maybe (F Int Bool) will return (F, [Int]), not (F, [Int,Bool])This is important for its use in deciding termination of type instances (see #11581). E.g. type instance G [Int] = ...(F Int )... we don't need to take into account when asking if the calls on the RHS are smaller than the LHSfLike f, except that the output records whether the type family and its arguments occur as an  invisible argument in some type application. This information is useful because it helps GHC know when to turn on -fprint-explicit-kinds during error reporting so that users can actually see the type family being mentioned.As an example, consider: class C a data T (a :: k) type family F a :: k instance C (T @(F Int) (F Bool)) -There are two occurrences of the type family F in that C instance, so f (C (T @(F Int) (F Bool))) will return: [ (M, F, [Int]) , (J, F, [Bool]) ] F Int is paired with M since it appears as an  invisible argument to C , whereas F Bool is paired with J since it appears an a visible argument to C.See also Note [Showing invisible bits of types in error messages] in GHC.Tc.Errors.Ppr.fIn an application of a  to some arguments, find the outermost occurrences of type family applications within the arguments. This function will not consider the 4 itself when checking for type family applications.See f for more details on how this works (as this function is called inside of f).fCheck that a type does not contain any type family applications.fIs this type variable a concrete type variable, i.e. it is a metavariable with f f? Returns the -( stored in the type variable if so, or K otherwise.f?Is this type concrete type variable, i.e. a metavariable with f f?fIs this type a concrete type variable? If so, return the associated  and -.gReturns the (kind, type) variables in a type that are as-yet-unknown: metavariables and RuntimeUnksg-Make a sigma ty where all type variables are >. That is, they cannot be used with visible type application.gMake a sigma ty where all type variables are "specified". That is, they can be used with visible type applicationg$Splits a forall type into a list of -s and the inner type. Always succeeds, even if it returns an empty list.g;Splits a type into a PiTyVarBinder and a body, if possible.gLike g, but splits off only named binders, returning just the tyvars.gLike g, but only splits Ns with  type variable binders.gLike g, but only splits a N if argf_pred argf is M, where argf is the visibility of the ForAllTy's binder and  argf_pred is a predicate over visibilities provided as an argument to this function.gLike g, but only splits Ns with = type variable binders. All split tyvars are annotated with ().gLike g, but only splits Ns with  type variable binders. All split tyvars are annotated with their .gLike g$, but splits off only named binders.g4Split a sigma type into its parts. This only splits  invisible type variable binders, as these are the only forms of binder that the typechecker will implicitly instantiate.gSplit a sigma type into its parts, going underneath as many arrows and foralls as possible. See Note [tcSplitNestedSigmaTys]gLike tcRepSplitTyConApp_maybe, but only returns the .gSplit off exactly the specified number argument types Returns (Left m) if there are m missing arrows in the type (Right (tys,res)) if the type looks like t1 -> ... -> tn -> resg?Strips off n *visible* arguments and returns the resulting typegLike g, but also says M for f typesg&Check whether the type is of the form Any :: k, returning the kind k.g8Is the type inhabited by machine floating-point numbers?Used to check that we don't use floating-point literal patterns in Core.See #9238 and Note [Rules for floating-point comparisons] in GHC.Core.Opt.ConstantFold.g Is a type :?gFor every arg a tycon can take, the returned list says True if the argument is taken visibly, and False otherwise. Ends with an infinite tail of Trues to allow for oversaturation.gIf the tycon is applied to the types, is the next argument visible?gShould this type be applied to a visible argument? E.g. (s t): is t a visible argument of s?gltPatersonSize ps1 ps2 returns:Nothing iff ps1% is definitely strictly smaller than ps2, Just ps_fail otherwise; ps_fail says what went wrong.gWhen this says True, ignore this class constraint during a termination check See (PS1) in Note [The PatersonSize of a type]fthe type variables which appear more often in the context | P is not smaller in size than H. See (PC2) in Note [Paterson conditions] in GHC.Tc.Validity.f'the type constructor of the type familyLJ7Is this an invisible argument to some type application?ȇ7Is this an invisible argument to some type application?))\\\\\\VVVVVVVVVVVVPP/QQQ/PPPQQZZZZZZZZZZNNNNNNNNNNNNQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQML.RR.S..SRSSRSSR.RRRRRR.RRRggffgggffgfgffggggfggf-ffffgfgggfgggg-fgggfgffggggfgfgggff-fgggfggfggggfffgfggggfg-gggggggggg-ffgggfffgggfgggggggggggggggggggggggggggggggggffffffgg---NQQQ---fffffffffffffffff-ffffffffffffffffffffffffffffffffffffffffffffffff-fffffffffff-----ffffffffffffffffffffffNfffffffffffffffffffffffffffffffffffffffffffff-ffffff---fffffffffff-fRfgf---f-fff--ffgggggffgggffgggggggggR.RggggggggggggggggggRRggggggRgggggggggggggggggggSMg.gggggVVVVVVVVVVVVggggggggggfffffffffffffffffffffgggggggggggfggQgg)).RS-----NNRRRRRNNNNNN..RLNNNN\\\\\\ggggRS--QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQSSS./PPQQPQPPQ/ZZZZZZZZZZgggfg  g g g #g  g g g !NoneDg(Warning emitted when the default is usedgNothing for built-in, Just the current module or the module whence the default was imported see Note [Default exports] in GHC.Tc.Gen.Exportgalways a class constructorg"Default environment mapping class TyCons to their default type listsggggggggggggggggggggggggggggggg1 1"g/ /None ɇ.Do we force the result to be representational?gCoercion optimisation optionsg.Enable coercion optimisation (reduce its size)goptCoercion applies a substitution to a coercion, *and* optimises it to reduce its sizeʇOptimize a coercion, making no assumptions. All coercions in the lifting context are already optimized (and sym'd if nec'y)ˇOptimize a coercion, knowing the coercion's role. No other assumptions.̇Optimize a coercion, knowing the coercion's non-Phantom role, and with an optional downgrade͇ Optimize a non-phantom coercion.· Optimize a non-phantom coercion.χOptimize a phantom coercion. The input coercion may not necessarily be a phantom, but the output sure will be.Ї/Conditionally set a role to be representationalчIf we require a representational role, return that. Otherwise, return the "default" role provided.ˇ$IsSwapped => apply Sym to the resultThe role of the input coercionЇ current roleч"default" roleggggggggNone sIface type for LambdaFormInfo. Fields not relevant for imported Ids are omitted in this type.sExported named defaultssThis corresponds to HsSrcBangsThis corresponds to an HsImplBang; that is, the final implementation decision about the data constructor argtName of associated axiom and branches for pretty printing purposes, or K for an empty closed family without an axiom See Note [Pretty printing via Iface syntax] in GHC.Types.TyThing.PprtA binding top-level , in an interface file (e.g. the name of an t).tno user import listt#Show a declaration but not its RHS.tShow declaration and its RHS, including GHc-internal information (e.g. for  --show-iface).tPretty Print an IfaceExprThe first argument should be a function that adds parens in context that need an atomic value (e.g. function args)ttttttttttttttttWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWsssttssssssstttttttttsssssssssttttttttttttttsssssssssssssssstttttttsstttttttttttttttttttttttttttttttttttttttttttttssssssssssssssssssssssssssssttttttssssssssssttssssssssssssssssssssssssssssssssssssssstssstttsssssssssttttVVWWWWWWVVVVWWWWWWWWVWWWWVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWVVVVVVVVVVVVVVVV---- tttttttttttttttttttttttttttttttttttttttttttttttttsstttttttssttttttssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssttttttttttttsssssss ttttttttttttssssssssssstttttttttttttttttttttVVVVVVVVVttt t t $t $t !t !t %t t t !t !t !t t t "t "t t t u u u u !u !u u u u u !u #u #u 'u  u  u $u u u "u u u !u u u !u  u  u $u #u #u 'u u u u u  u u u u  Type ` = Just `Type -> Type` hsTyKindSig `Maybe :: ((Type -> Type))` = Just `Type -> Type`This is used to extract the result kind of type synonyms with a CUSK:2type S = (F :: res_kind) ^^^^^^^^yRetrieve the name of the "head" of a nested type application. This is somewhat like GHC.Tc.Gen.HsType.splitHsAppTys, but a little more thorough. The purpose of this function is to examine instance heads, so it doesn't handle *all* cases (like lists, tuples, (~), etc.).y Compute the  associated with an 5.yy id fixity args! pretty-prints an application of id to args , using the fixity to tell whether id. should be printed prefix or infix. Examples: pprHsArgsApp T Prefix [HsTypeArg Bool, HsValArg Int] = T @Bool Int pprHsArgsApp T Prefix [HsTypeArg Bool, HsArgPar, HsValArg Int] = (T @Bool) Int pprHsArgsApp (++) Infix [HsValArg Char, HsValArg Double] = Char ++ Double pprHsArgsApp (++) Infix [HsValArg Char, HsValArg Double, HsVarArg Ordering] = (Char ++ Double) Ordering ҇.Pretty-print a prefix identifier to a list of 5s.ӇPretty-print an 5 in isolation.yDecompose a pattern synonym type signature into its constituent parts.Note that this function looks through parentheses, so it will work on types such as  (forall a.  ...). The downside to this is that it is not generally possible to take the returned types and reconstruct the original type (parentheses and all) from them.y$Decompose a sigma type (of the form forall  tvs. context => body) into its constituent parts. Only splits type variable binders that were quantified invisibly (e.g.,  forall a., with a dot).This function is used to split apart certain types, such as instance declaration types, which disallow visible forall)s. For instance, if GHC split apart the forall in "instance forall a -> Show (Blah a)6, then that declaration would mistakenly be accepted!Note that this function looks through parentheses, so it will work on types such as  (forall a.  ...). The downside to this is that it is not generally possible to take the returned types and reconstruct the original type (parentheses and all) from them.y;Decompose a GADT type into its constituent parts. Returns (outer_bndrs, mb_ctxt, body), where: outer_bndrs are 6 if the type has explicit, outermost type variable binders. Otherwise, they are 6.mb_ctxt is Just5 the context, if it is provided. Otherwise, it is Nothing.body, is the body of the type after the optional foralls and context.?This function is careful not to look through parentheses. See Note [GADT abstract syntax] (Wrinkle: No nested foralls or contexts)  GHC.Hs.Decls for why this is important.yDecompose a type of the form forall  tvs. body into its constituent parts. Only splits type variable binders that were quantified invisibly (e.g.,  forall a., with a dot).This function is used to split apart certain types, such as instance declaration types, which disallow visible forall)s. For instance, if GHC split apart the forall in "instance forall a -> Show (Blah a)6, then that declaration would mistakenly be accepted!Note that this function looks through parentheses, so it will work on types such as  (forall a.  ...). The downside to this is that it is not generally possible to take the returned types and reconstruct the original type (parentheses and all) from them. Unlike y, this function does not look through parentheses, hence the suffix _KP (short for "Keep Parentheses").yDecompose a type of the form forall  tvs. body into its constituent parts. Only splits type variable binders that were quantified invisibly (e.g.,  forall a., with a dot).This function is used to split apart certain types, such as instance declaration types, which disallow visible forall)s. For instance, if GHC split apart the forall in "instance forall a -> Show (Blah a)6, then that declaration would mistakenly be accepted!Unlike y, this function does not look through parentheses, hence the suffix _KP (short for "Keep Parentheses").yDecompose a type of the form context => body into its constituent parts.Note that this function looks through parentheses, so it will work on types such as  (context =>  ...). The downside to this is that it is not generally possible to take the returned types and reconstruct the original type (parentheses and all) from them.ԇDecompose a type of the form context => body into its constituent parts.Unlike y, this function does not look through parentheses, hence the suffix _KP (short for "Keep Parentheses").y3Decompose a type class instance type (of the form forall  tvs. context => instance_head-) into its constituent parts. Note that the [Name] s returned correspond to either:The implicitly bound type variables (if the type lacks an outermost forall), orThe explicitly bound type variables (if the type has an outermost forall).?This function is careful not to look through parentheses. See 6Note [No nested foralls or contexts in instance types] for why this is important.y3Decompose a type class instance type (of the form forall  tvs. context => instance_head ) into the  instance_head.y3Decompose a type class instance type (of the form forall  tvs. context => instance_head ) into the  instance_head and retrieve the underlying class type constructor (if it exists).yPrints the explicit forall in a type family equation if one is written. If there is no explicit forall, nothing is printed.yPrints the outermost forall in a type signature if one is written. If there is no outermost forall, nothing is printed.y3Prints a forall; When passed an empty list, prints forall ./ forall -> only when  -dppr-debug is enabled.yy p t returns M if the type t% needs parentheses under precedence p.yy p ty checks if y p ty is true, and if so, surrounds ty with an 6 . Otherwise, it simply returns ty.yy p ctxt checks if ctxt is a single constraint c such that y p c is true, and if so, surrounds c with an 6 to form a parenthesized ctxt . Otherwise, it simply returns ctxt unchanged.yThis instance is meant for debug-printing purposes. If you wish to pretty-print an application of 5s, use y instead.yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy777777777\\\\\\xxxxxxyyxxxxyyyyxyyyyxxxxxxxxxxx 7666666655555566566666666666666666666666777777777667666666666666666666666666666666666666666666666666666666666666666666666666666676577777776677566677666666yyxxxyyyy66666666666666666666666666666x77777777777yy66666667xxxxxx6666666666667777776666666666666666666yyyy66666xyyyyxxxxxyyyy66666666666677y6666666756656yy5yx77\\\\\\ yy66666666y66667555555yyyxxxxxyyyy7yyyyyyyyyyy7y7yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy7yyyyyyyyyyyy y y y y 4y !y y +y +y 0y 9y 5y .y ?y y y y 0y1y !y $y y y y 4y :y 7y *y !y yy y None .&oEvery node in an expression annotated with its (non-global) free variables, both Ids and TyVars, and type.oEvery node in an expression annotated with its (non-global) free variables, both Ids and TyVars, and type. NB: see Note [The FVAnn invariant]oEvery node in a binding group annotated with its (non-global) free variables, both Ids and TyVars, and type.oFind all locally-defined free Ids or type variables in an expression returning a non-deterministic set.oFind all locally-defined free Ids or type variables in an expression returning a composable FV computation. See Note [FV naming conventions] in  GHC.Utils.FV for why export it.oFind all locally-defined free Ids or type variables in an expression returning a deterministic set.oFind all locally-defined free Ids or type variables in an expression returning a deterministically ordered list.o2Find all locally-defined free Ids in an expressionoFind all locally-defined free Ids in an expression returning a deterministic set.oFind all locally-defined free Ids in an expression returning a deterministically ordered list.oFind all locally-defined free Ids in several expressions returning a deterministic set.oFind all locally-defined free Ids in several expressions returning a deterministically ordered list.oFind all locally-defined free Ids or type variables in several expressions returning a non-deterministic set.ՇFind all locally-defined free Ids or type variables in several expressions returning a composable FV computation. See Note [FV naming conventions] in  GHC.Utils.FV for why export it.oFind all locally-defined free Ids or type variables in several expressions returning a deterministically ordered list.o4Find all locally defined free Ids in a binding groupo=Finds free variables in an expression selected by a predicateoFinds free variables in an expression selected by a predicate returning a deterministically ordered list.ևFinds free variables in an expression selected by a predicate returning a deterministic set.oFinds free variables in several expressions selected by a predicateoFinds free variables in several expressions selected by a predicate returning a deterministically ordered list.ׇFinds free variables in several expressions selected by a predicate returning a deterministic set.oo collects the names of the concrete types and type constructors that make up the LHS of a type family instance, including the family name itself.For instance, given `type family Foo a b`: `type instance Foo (F (G (H a))) b = ...` would yield [Foo,F,G,H]Used (via orphNamesOfFamInst) in the implementation of ":info" in GHCi. and when determining orphan-hood for a FamInst or module؇Finds the free external names of an expression, notably including the names of type constructors (which of course do not show up in o).oFinds the free external# names of several expressions: see  exprOrphNames for detailsهThose locally-defined variables free in the left and/or right hand sides of the rule, depending on the first argument. Returns an / computation.ڇThose locally-defined variables free in the left and/or right hand sides from several rules, depending on the first argument. Returns an / computation.oThose variables free in the right hand side of a rule returned as a non-deterministic setoThose locally-defined free s in the right hand side of several rules returned as a non-deterministic setoThis finds all locally-defined free Ids on the left hand side of a rule and returns them as a non-deterministic setoThis finds all locally-defined free Ids on the left hand side of a rule and returns them as a deterministically ordered listoThose variables free in the both the left right hand sides of a rule returned as a non-deterministic setoThose variables free in the both the left right hand sides of rules returned as a deterministic setoThose variables free in both the left right hand sides of several rulesoMake a b containing a number of _!s, suitable for putting into an oInverse function to po$Extract the vars reported in a FVAnnp Annotate a  with its (non-global) free type and value variables at every tree node.o Says which s are interestingo Says which s are interestingև Says which s are interestingׇ Says which s are interesting1oooooooooooooooooooopooooooooooooooooooooooooooo/1oooooooooooo/oooooooooooooooooooooooooooooooopoooNone"ۇCollect class instance matches, including matches that we know are overridden but might still be useful to override other instances (which we call "guards").'See Note [Instance overlap and guards].܇Guards: matches that we know we won't pick in the end, but might still be useful for ruling out other instances, as per #20946. See Note [Instance overlap and guards], (A).݇Minimal matches: we have knocked out all strictly more general matches that are overlapped by a match in this list.ww says whether a piece of evidence has a singleton type; For example, given (d1 :: C Int), will any other (d2 :: C Int) do equally well? See Note [Coherence and specialisation: overview] above, and Note [Desugaring non-canonical evidence] in GHC.HsToCore.Bindsw=Why a particular typeclass application couldn't be looked up.wTyvars aren't an exact match.wOne of the tyvars is flexible.wNo matching instance was found.wSet of visible orphan modules, according to what modules have been directly imported. This is based off of the dep_orphs field, which records transitively reachable orphan modules (modules that define orphan instances).ww represents the combination of the global type class instance environment, the local type class instance environment, and the set of transitively reachable orphan modules (according to what modules have been directly imported) used to test orphan instance visibility.wA type-class instance. Note that there is some tricky laziness at work here. See Note [ClsInst laziness and the rough-match fields] for more details.wis_dfun_name = idName . is_dfun.We use w for the visibility check, w, which needs to know the  which the dictionary is defined in. However, we cannot use the  attached to w since doing so would mean we would potentially pull in an entire interface file unnecessarily. This was the cause of #12367.wTop of type args The class itself is always the first element of this listw Class namewA fuzzy comparison function for class instances, intended for sorting instances before displaying them to the user.wCollects the names of concrete types and type constructors that make up the head of a class instance. For instance, given `class Foo a b`:`instance Foo (Either (Maybe Int) a) Bool` would yield [Either, Maybe, Int, Bool].Used in the implementation of ":info" in GHCi.The g is because of instance Foo a => Baz T where ... The decl is an orphan if Baz and T are both not locally defined, even if Foo *is* locally definedwTest if an instance is visible, by checking that its origin module is in w2. See Note [Instance lookup and orphan instances]wChecks for an exact match of ClsInst in the instance environment. We use this when we do signature checking in  GHC.Tc.Modulew/Makes no particular effort to detect conflicts.wTrue when when the instance heads are the same e.g. both are Eq [(a,b)] Used for overriding in GHCi Obviously should be insensitive to alpha-renamingwLook up an instance in the given instance environment. The given class application must match exactly one instance and the match may not contain any flexi type variables. If the lookup is unsuccessful, yield 'Left errorMessage'.wSee Note [Rules for instance lookup] ^ See Note [Safe Haskell Overlapping Instances] in  GHC.Tc.Solver ^ See Note [Safe Haskell Overlapping Instances Implementation] in  GHC.Tc.SolverއRemove from the argument list any InstMatches for which another element of the list is more specific, and overlaps it, using the rules of Note [Rules for instance lookup], esp (IL3)Incoherent instances are discarded, unless all are incoherent, in which case exactly one is kept.߇Computes whether the first class instance overrides the second, i.e. the first is more specific and can overlap the second.More precisely, instA ߇ instB returns M precisely when:instA is more specific than instB,instB is not more specific than instA,instA is overlapping OR instB is overlappable.Add a new solution, knocking out strictly less specific ones See Note [Rules for instance lookup] and Note [Instance overlap and guards].Property/: the order of insertion doesn't matter, i.e. ;insert_overlapping inst1 (insert_overlapping inst2 matches) gives the same result as ;insert_overlapping inst2 (insert_overlapping inst1 matches).wthe name of the class)the rough match signature of the instancethe  of the dictionary bindingthe  of the dictionary.may this instance overlap?is this instance an orphan?warning emitted when solvedwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwZZ&wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww&&&&&&&&&&&--wwwwwwwwww&&&&&&&&&&&&wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwZZwww w w w w &w %w &w w w None pwWhere to store evidence for expression holes See Note [Holes] in GHC.Tc.Types.Constraintw Evidence for  CallStack implicit parameters.wEvCsPushCall origin loc stk represents a call from origin, occurring at loc, in a calling context stk.wInstructions on how to make a Typeable0 dictionary. See Note [Typeable evidence terms]wDictionary for  Typeable T where T is a type constructor with all of its kind variables saturated. The [EvTerm] is Typeable" evidence for the applied kinds..wDictionary for Typeable (s t), given a dictionaries for s and t.wDictionary for Typeable (s % w -> t), given a dictionaries for w, s, and t.w%Dictionary for a type literal, e.g. Typeable "foo" or  Typeable 3 The w is evidence of, e.g.,  KnownNat 3 (see #10348)xIf a & is &$, flip the orientation of a coercionxSmart constructor to create a x x.PRECONDITION: the "from" type of the first wrapper must have a syntactically fixed RuntimeRep (see Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete).xIdentifies the  lambda-bound dictionaries of an x. This is used (only) to allow the pattern-match overlap checker to know what Given dictionaries are in scope.7We specifically do not collect dictionaries bound in a x. These are either superclasses of lambda-bound ones, or (extremely numerous) results of binding Wanted dictionaries. We definitely don't want all those cluttering up the Given dictionaries for pattern-match overlap checking!x,Any sort of evidence Id, including coercionsxd |> cox Create a  that unwraps an implicit-parameter dictionary to expose the underlying value. We expect the - to have the form `IP sym ty`, and return a  `co :: IP sym ty ~ ty`x Create a > that wraps a value in an implicit-parameter dictionary. See x.xConvert the QuoteWrapper into a normal HsWrapper which can be used to apply its contents.x-The Semigroup instance is a bit fishy, since  WpCompose, as a data constructor, is "syntactic" and not associative. Concretely, if a, b, and c aren't WpHole: (a <> b) <> c ?= a <> (b <> c)> (a `WpCompose` b) `WpCompose` c /= @ a `WpCompose` (b `WpCompose` c)However these two associations are are "semantically equal" in the sense that they produce equal functions when passed to GHC.HsToCore.Binds.dsHsWrapper.w&where to write the erroring expression expected type of that expressionfor debug output onlyxthe "from" type of the first wrapper MUST have a fixed RuntimeRepEither "from" type or "to" type of the second wrapper (used only when the second wrapper is the identity)xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&Mwwwxwxxxxxxxxxxxxxwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxwwxxxxxxxxxx&&& xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxwwwxwxxxxxxwwwwwwwwwxxxxxxxxxxxxxwwwwwwwwwwxxxxMxxxx &&&&xxxwwxxx x x x x x x x x x x x  x x  x6?x x x x None 3 sz!Type checker Specification PragmazThe Id to be specialised, a wrapper that specialises the polymorphic function, and inlining spec for the specialised functionz*Located Type checker Specification Pragmasz#Type checker Specialisation Pragmasz conveys  SPECIALISE/ pragmas from the type checker to the desugarerzSuper-specialised: a default method should be macro-expanded at every call site{A type signature in generated code, notably the code generated for record selectors. We simply record the desired Id itself, replete with its name, type and IdDetails. Otherwise it's just like a type signature: there should be an accompanying binding{Optional namespace specifier for fixity signatures, WARNINIG and DEPRECATED pragmas. Examples:{-# WARNING in "x-partial" data Head "don't use this pattern synonym" #-} -- C DataNamespaceSpecifier{-# DEPRECATED type D "This type was deprecated" #-} -- C TypeNamespaceSpecifier5infixr 6 data $ -- C DataNamespaceSpecifier{Abstraction Bindings Export{SPECIALISE pragmas{See Note [ABExport wrapper] Shape: (forall abs_tvs. abs_ev_vars => abe_mono) ~ abe_poly{(Any INLINE pragma is attached to this Id{Typechecked, generalised bindings, used in the output to the type checker. See Note [AbsBinds].{Typechecked user bindings{#Evidence bindings Why a list? See GHC.Tc.TyCl.Instance4 Note [Typechecking plan for instance declarations]{AbsBinds only gets used when idL = idR after renaming, but these need to be idL's for the collect... code in HsUtil to have the right type{Includes equality constraints{Check if namespace specifiers overlap, i.e. if they are equal or if at least one of them doesn't specify a namespace{Check if namespace is covered by a namespace specifier: * NoNamespaceSpecifier covers both namespaces * TypeNamespaceSpecifier covers the type namespace only * DataNamespaceSpecifier covers the data namespace only{7Extracts the name for a SPECIALIZE instance pragma. In {, the src field of 7 signature contains the SourceText for a SPECIALIZE instance pragma of the form: "SourceText {-# SPECIALIZE"Extraction ensures that all variants of the pragma name (with a Z or an S+) are output exactly as used in the pragma.{Using SourceText in case the pragma was spelled differently or used mixed caseAfter the type-checker, the FunBind extension field contains the ticks to put on the rhs, if any, and a coercion from the type of the MatchGroup to the type of the Id. Example: 1 f :: Int -> forall a. a -> a f x y = y Then the MatchGroup will have type (Int -> a' -> a') (with a free type variable a'). The coercion will take a CoreExpr of this type and convert it to a CoreExpr of type Int -> forall a'. a' -> a' Notice that the coercion captures the free a'.After the renamer (but before the type-checker), the FunBind extension field contains the locally-bound free variables of this defn. See Note [Bind free vars]{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{877878777{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{z{{{{{{zzzzz{77777777777777777777777777777777777777777777777777777777777777777777777777777777777{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{z{{{{{{zzzzz{{ -{ <{ ?{ -{ { ={ <{ { ?{ { { { '{ { { { { {{{ {{{{{None  )+3 {This is the extension field for ConPat, added after typechecking It adds quite a few extra fields, to support elaboration of pattern matching.{Extra wrapper to pass to the matcher Only relevant for pattern-synonyms; ignored for data cons{%Bindings involving those dictionaries{Ditto *coercion variables* and *dictionaries* One reason for putting coercion variable here I think is to ensure their kinds are zonked{Existentially bound type variables in correctly-scoped order e.g. [k:* x:k]{The universal arg types 1-1 with the universal tyvars of the constructor/pattern synonym Use (conLikeResTy pat_con cpt_arg_tys) to get the type of the pattern{8Extension constructor for Pat, added after typechecking.{#Coercion Pattern (translation only):During desugaring a (CoPat co pat) turns into a cast with co+ on the scrutinee, followed by a match on pat.{Pattern expansion: original pattern, and desugared pattern, for RebindableSyntax and other overloaded syntax such as OverloadedLists. See Note [Rebindable syntax and XXExprGhcRn].{Type of whole pattern, t1{)Why not LPat? Ans: existing locn will do{Coercion Pattern If co :: t1 ~ t2, p :: t2, then (CoPat co p) :: t1)Print with type info if -dppr-debug is on|isIrrefutableHsPat p is true if matching against p cannot fail in the sense of falling through to the next pattern. (NB: this is not quite the same as the (silly) defn in 3.17.2 of the Haskell 98 report.)If isIrrefutableHsPat returns M(, the pattern is definitely irrefutable.$However, isIrrefutableHsPat returns J if it's in doubt. It's a best effort guess with the information we have available:we sometimes call | from the renamer, in which case we don't have type information to hand. This means we can't properly handle GADTs, nor the result TyCon of COMPLETE pragmas.even when calling | in the typechecker, we don't keep track of any long distance information like the pattern-match checker does.|%Is the pattern any of combination of:(pat) pat :: Type~pat!pat x (variable)|Is this pattern boring from the perspective of pattern-match checking, i.e. introduces no new pieces of long-distance information which could influence pattern-match checking?See Note [Boring patterns].|| p pat returns M if the pattern pat% needs parentheses under precedence p. p cp returns M if the constructor patterns cp% needs parentheses under precedence p.|0Parenthesize a pattern without token information|| p pat checks if | p pat is true, and if so, surrounds pat with a S. Otherwise, it simply returns pat.| Are we in a -XStrict1 context? See Note [-XStrict and irrefutability]How to check whether the b in a S pattern is irrefutableThe (located) pattern to check|||{||||||||||||T{TTTTTTT{{{{{{{{{{{{{{{{{{{{SSSSSSSSSSSSSSSSSSSS%%SSSTTSSTTTSSTTSSSSSTTTTSSS%SSSTTSSTTTSSTTSSSSSTTTT%TT{{{{{{{{{{{{S{{{{{{{{STTSSSSSSSSSSSSSSSSSSSSSTT{T||||||||||||||{|T| <| (| (| | | | |None 3An accumulator to build a prefix data constructor, e.g. when parsing  MkT A B C), the accumulator will evolve as follows:  1. PrefixDataConBuilder [] MkT 2. PrefixDataConBuilder [A] MkT 3. PrefixDataConBuilder [A, B] MkT 4. PrefixDataConBuilder [A, B, C] MkT There are two reasons we have a separate builder type instead of using HsConDeclDetails GhcPs directly: It's faster, because  gives us constant-time snoc.Having a separate type helps ensure that we don't forget to finalize a RecTy into a 6 (we do that in dataConBuilderDetails).See Note [PatBuilder] for another builder type used in the parser. Here the technique is similar, but the motivation is different.?See Note [Ambiguous syntactic categories] and Note [PatBuilder]"Last two are the locations of the '|' before and after the payload ' #None 3g |does this have a CUSK? See Note [CUSKs: complete user-supplied kind signatures]|Partition a list of HsDecls into function/pattern bindings, signatures, type family declarations, type family instances, and documentation comments.Panics when given a declaration that cannot be put into any of the output groups.2The primary use of this function is to implement .|The fixity signatures for each top-level declaration and class method in an :7. See Note [Top-level fixity signatures in an HsGroup]|Does this declaration have a complete, user-supplied kind signature? See Note [CUSKs: complete user-supplied kind signatures]|-Maybe return name of the result type variable|A short description of a DerivStrategy'.|Return L fields> if a data constructor declaration uses record syntax (i.e., 6 ), where fields- are the field selectors. Otherwise, return K.| Convert a : to a %| Eliminate a 9.} Map over the via type if dealing with 9. Otherwise, return the 9 unchanged.|||||||||}|||||||}|||||}||||}|||||;;;;;;;;;;;;;;;;;{{{{{{|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||8888888999999999999999:::::::::::::::999999999::::99999999999999999999999999::::::::::::::::::::9999999999999999:::99999:::::::::;;;;;;;;;;;;;;;;:::::::9:::::::;:::;;;::::9999999999989:99:999::9;:::98999:::99989:8889999999999999999999::::::::::::::::::::::::::::::::::::::::999999988888898;;;;;;;;;;;;;;;;;::::::::::::::::::::::::||::::|::::::::::::::::::::::::||||||||||||||||||||||||||||||||||||||||||||||||||||||::::::::;;;;;;;|;;;;;|||||;||:::::::::::::::||999999999999::::999999|999999|||9999999999999999999999999999999|999999||}||99999999999999999||||||||{{{{{{99999;}}9999999:::::::9999999999999999999999::::::::::::::::99999|||||||||||||999999;888888898988888888;8888}::::::::::|||:::::::;:::;;;:|||;||5} 1} } ,} .} } } } 1} 1} /} /} 2} -} } } /} 3} 1} } 5} .} } 4} .} ?} -} } &} %} .} } } #} } } } } } } } #} }  }  } }}}}}}}} None !3'V8The result of splicing; See Note [Lifecycle of a splice]V%TH finalizers produced by the splice.V&Finalizers produced by a splice with See Note [Delaying modFinalizers in untyped splices] in GHC.Rename.Splice. For how this is used.}Pending Type-checker Splice}Pending Renamer Splice}Applicative Argument}True  = was a BodyStmt, False  =1 was a BindStmt. See Note [Applicative BodyStmt]}!The fail operator, after renamingThe fail operator is needed if this is a BindStmt where the pattern can fail. E.g.: (Just a) <- stmt The fail operator will be invoked if the pattern match fails. It is also used for guards in MonadComprehensions. The fail operator is Nothing if the pattern match can't fail},context of the do expression, used in pprArg}}2 represents an applicative expression built with  and  . It is generated by the renamer, and is desugared into the appropriate applicative expression by the desugarer, but it is intended to be invisible in error messages..For full details, see Note [ApplicativeDo] in GHC.Rename.Expr}Match separator location, `=` or ->}'Command Syntax Table (for Arrow syntax)~Variable pointing to record selector See Note [Non-overloaded record field selectors] and Note [Record selectors in the AST]~Variable pointing to record selector See Note [Non-overloaded record field selectors] and Note [Record selectors in the AST]~The different source constructs that we use to instantiate the "original" field in an `XXExprGhcRn original expansion`~0Information about the parent of a record update:/the parent type constructor or pattern synonym,the relevant con-likes,the field labels.~ Location of 'case' or cases keyword, depending on related U.~ Location of '\' keyword~)HsWrap appears only in typechecker output~7An expression with wrappers, used for rebindable syntaxThis should desugar to syn_res_wrap $ syn_expr (syn_arg_wraps[0] arg0) (syn_arg_wraps[1] arg1) ...:where the actual arguments come from elsewhere in the AST.~The function to use in rebindable syntax. See Note [NoSyntaxExpr].~Post-Type checking TableWe use a PostTcTable where there are a bunch of pieces of evidence, more than is convenient to keep individually.~Post-Type checking ExpressionPostTcExpr is an evidence expression attached to the syntax tree by the type checker (c.f. postTcType).~This is used for rebindable-syntax pieces that are too polymorphic for tcSyntaxOp (trS_fmap and the mzip in ParStmt)~Make a 'SyntaxExpr GhcRn' from an expression Used only in getMonadFailOp. See Note [Monad fail : Rebindable syntax, overloaded strings] in GHC.Rename.Expr~Make a % from a 4 (the "rn" is because this is used in the renamer).~!Wrap a located expression with a ~~Wrap a located expression with a PopSrcExpr with an appropriate location~4Build an expression using the extension constructor U, and the two components of the expansion: original expression and expanded expressions.~4Build an expression using the extension constructor U, and the two components of the expansion: original do stmt and expanded expression~4Build an expression using the extension constructor U, and the two components of the expansion: original do stmt and expanded expression an associate with a provided location~7Wrap the expanded version of the expression with a pop.~Build a ~ out of an extension constructor, and the two components of the expansion: original and expanded typechecked expressions.~Build a ~ out of an extension constructor. The two components of the expansion are: original statement and expanded typechecked expression.~~ p e returns M if the expression e% needs parentheses under precedence p.~4Parenthesize an expression without token information~~ p e checks if ~ p e is true, and if so, surrounds e with an U. Otherwise, it simply returns e..Is there only one RHS in this list of matches?fixity (filled in by the renamer), for forms that were converted from OpApp's by the renamer~source expressionexpanded expressionsuitably wrapped ~~source statementexpanded expressionsuitably wrapped ~~source patternexpanded expressionsuitably wrapped ~~%Location for the expansion expressionsource statementexpanded expressionsuitably wrapped located ~~$Location for the expansion statementsource statementexpanded expressionsuitably wrapped ~~source expressionexpanded typechecked expressionsuitably wrapped ~~source do statementexpanded typechecked expressionsuitably wrapped ~~~~~~~~~~~~~~~~~~~~~~~~~VVV~~VVV~~~~~~~~~~~~UUUUUUUUU~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}~~~~~~~}}}}}}}}}}}}}}}~~~}}}}}~~~~~~~~~~~~}}}}~~~~~~}}~~~~~~~~}~~~~UVVVV~~}}}}}}}}}~~}}}}}}V~~~~~~~~~~V}}}}}}}}}}}}}}}}}}}}~~~~~~}~}~~~}~~TTTTTTTUUUUUTTTUUTTT%TTTTTTTTTUUUTTTTUUUUUUUUUUUUUU%TTTTT%UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTUUUTTTTTTTTUTTTTTTUUUU%TTTUTUU%UUUUUUUUUUUTTTTUUUUU%UUUUTTTUUTTTTTTTTTTTTTTTTTTTTTTTTTT%TTT~~~~~~~~~~~~~~~~~~~~~~~~VVV~~VVV~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}~~~~~~~}}}}}}}}}}}}}}}~~~}}}}}~~~~~~~~~~~~}}}}~~~~~~}}~~~~~~~~}~~~~UVVVV~~}}}}}}}}}~~}}}}}}V~~~~~~~~~~V}}}}}}}}}}}}}}}}}}}}~~~~~~}~}~~~}~~7  0    8 ( ! 9 2 . ?  4   *  ! ! 6                 3   $ $      None &"##! ˆ È Ĉ"ň"ƈ"Lj*Ȉ*Ɉ*ʈ(ˈ(̈(͈,Έ,ψ,Ј=ш=҈=ӈ<Ԉ<Ո<ֈ׈؈وڈۈ܈'݈'ވ'߈&&&***)))???111''',,,)))***)))???=--- ###!!)))%%%##$$'' ,,,#''';///65+...5555555552222!‰ÉĉʼnƉljȉɉʉˉ͉̉ΉωЉщ҉ӉԉՉ։׉؉ىډۉ܉(݉(މ(߉%%%(((&&&'''+++///...111---'''---((()))(((((()))------++++++---)))(((+++666///---444'''...000******Š.Ê.Ċ.Ŋ*Ɗ*NJ*Ȋ/Ɋ/ʊ/ˊ)̊)͊)Ί&ϊ&Њ&ъ(Ҋ(ӊ(Ԋ*Պ*֊*׊'؊'ي'ڊ&ۊ&܊&݊)ފ)ߊ)+++111)))###&&&)))0000111  .??.>>.==.::-99-88-552442332222//4..4--4,,4None.Subtract two natural numbers.Compute the exact logarithm of a natural number. The logarithm base is the second argument.Divide two natural numbers.Compute the exact root of a natural number. The second argument specifies which root we are computing.Compute the n-th root of a natural number, rounded down to the closest natural number. The boolean indicates if the result is exact (i.e., True means no rounding was done, False means rounded down). The second argument specifies which root we are computing. Compute the logarithm of a number in the given base, rounded down to the closest integer. The boolean indicates if we the result is exact (i.e., True means no rounding happened, False means we rounded down). The logarithm base is the second argument. ppppppppppppppppppppJJJJpppppJJJJpppppppppppppppNone+ 1a monad for the normalisation functions, reading p, a Z, and a  .p;Result of testing two type family equations for injectiviy.pEither RHSs are distinct or unification of RHSs leads to unification of LHSspRHSs unify but LHSs don't unify under that substitution. Relevant for closed type families where equation after unification might be overlapped (in which case it is OK if they don't unify). Constructor stores axioms after unification.p Create a p from  indices. INVARIANTS: * The fs_tvs are distinct in each FamInst of a range value of the map (so we can safely unify them)p/Makes no particular effort to detect conflicts.pCheck whether two type family axioms don't violate injectivity annotation.pCreate a coercion constructor (axiom) suitable for the given newtype . The % should be that of a new coercion J, the  s the arguments expected by the newtype8 and the type the appropriate right hand side of the newtype/, with the free variables a subset of those s.pCheck whether an open type family equation can be added to already existing instance environment without causing conflicts with supplied injectivity annotations. Returns list of conflicting axioms (type instance declarations).pDo an apartness check, as described in the "Closed Type Families" paper (POPL '14). This should be used when determining if an equation (J) of a closed type family can be used to reduce a certain target type family application.pGet rid of *outermost* (or toplevel) * type function redex * data family redex * newtypes returning an appropriate Representational coercion. Specifically, if topNormaliseType_maybe env ty = Just (co, ty') then (a) co :: ty ~R ty' (b) ty' is not a newtype, and is not a type-family or data-family redexHowever, ty' can be something like (Maybe (F ty)), where (F ty) is a redex.Always operates homogeneously: the returned type has the same kind as the original type, and the returned coercion is always homogeneous.pTry to simplify a type-family application, by *one* step If topReduceTyFamApp_maybe env r F tys = Just (HetReduction (Reduction co rhs) res_co) then co :: F tys ~R# rhs res_co :: typeKind(F tys) ~ typeKind(rhs) Type families and data families; always Representational rolep flattened target arguments. Make sure they're flattened! See Note [Flattening type-family applications when matching instances] in GHC.Core.Unify.the candidate equation we wish to use Precondition: this matches the targetTrue  = equation can fire?ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp?pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp p p p !p p p  Nonesݩ A map from s to s, constructed by typechecking local declarations or interface filesީߩݩݩީߩNoneThe / is essentially a cache for information in the ModIface for home modules only. Information relating to packages will be loaded into global environments in ExternalPackageState.&Complete match pragmas for this moduleAnnotations present in this module: currently they only annotate things also declared in this moduleDomain may include Ids from other modulesDFunId"s for the instances in this module,default declarations exported by this moduleLocal type environment for this particular module Includes Ids, TyCons, PatSynsConstructs an empty ModDetails  None?yWhether m is a synonym for .ySomething is promoted to the type-level without a promotion tick.z"Explain how something is in scope.z8It was locally bound at this particular source location.z6It was imported by this particular import declaration.zSuggest how to fix an import.zSome module exports what we want, but we aren't explicitly importing it.zSome module exports what we want, but we are explicitly hiding it.z5The module exports what we want, but it isn't a type.z=The module exports what we want, but it's a type and we have ExplicitNamespaces on.z;Suggest importing a data constructor to bring it into scopezThe ' of the parent of the data constructor.zWhere to suggest importing the DataCon from.The 98 tracks whether to suggest using an import of the form import (pattern Foo), depending on whether -XPatternSynonyms was enabled.zAn z< for a '.hsig' file. This is generated by GHC in case of a DriverUnexpectedSignature and suggests a way to instantiate a particular signature, where the first argument is the signature name and the second is the module where the signature was defined. Example:src/MyStr.hsig:2:11: error: Unexpected signature: @MyStr@ (Try passing -instantiated-with="MyStr= MyStr" replacing  MyStr as necessary.)zThe deriving strategy that was assumed when not explicitly listed in the source. This is used solely by the missing-deriving-strategies warning. There's no Via# case because we never assume that.z$A type for hints emitted by GHC. A hint suggests a possible way to deal with a particular warning or error.zAn "unknown" hint. This type constructor allows arbitrary -- hints to be embedded. The typical use case would be GHC plugins -- willing to emit hints alongside their custom diagnostics.zSuggests adding a particular language extension. GHC will do its best trying to guess when the user is using the syntax of a particular language extension without having the relevant extension enabled.Example: If the user uses the keyword "mdo" (and we are in a monadic block), but the relevant extension is not enabled, GHC will emit a 'SuggestExtension RecursiveDo'.Test case(s): parser should_failT12429, parser should_fail$T8501c, parser should_failT18251e, ... (and many more)zSuggests possible corrections of a misspelled pragma. Its argument represents all applicable suggestions.%Example: {-# LNGUAGE BangPatterns #-}Test case(s): parsershould_compileT21589zSuggests that a monadic code block is probably missing a "do" keyword.Example: main = putStrLn "hello" putStrLn "world"Test case(s): parser should_failT8501a, parser should_fail)readFail007, parser should_failInfixAppPatErr, parser should_failT984z;Suggests that a "let" expression is needed in a "do" block.Test cases: None (that explicitly test this particular hint is emitted).zSuggests to add an ".hsig" signature file to the Cabal manifest.Triggered by: -, if Cabal is being used.Example: See comment of DriverUnexpectedSignature.Test case(s): driver/T12955zSuggests to explicitly list the instantiations for the signatures in the GHC invocation command.Triggered by: ", if Cabal is not being used.Example: See comment of DriverUnexpectedSignature.Test case(s): driver/T12955z'Suggests to use spaces instead of tabs.Triggered by: .)Examples: None Test Case(s): Nonez4Suggests adding a whitespace after the given symbol.+Examples: None Test Case(s): parsershould_compile T18834a.hszSuggests adding a whitespace around the given operator symbol, as it might be repurposed as special syntax by a future language extension. The second parameter is how such operator occurred, if in a prefix, suffix or tight infix position.Triggered by: .;Example: h a b = a+b -- not OK, no spaces around l.Test Case(s): parsershould_compile T18834b.hsz.Suggests wrapping an expression in parentheses)Examples: None Test Case(s): NonezSuggests to increase the -fmax-pmcheck-models limit for the pattern match checker.Triggered by: Test case(s): pmcheckshould_compile)TooManyDeltas pmcheckshould_compile)TooManyDeltas pmcheckshould_compileT11822zSuggests adding a type signature, typically to resolve ambiguity or help GHC inferring types.zSuggests to explicitly discard the result of a monadic action by binding the result to the '_' wilcard.>Example: main = do _ <- getCurrentTimezSuggests adding an identifier to the export list of a signature.zSuggests increasing the limit for the number of iterations in the simplifier.zSuggests to explicitly import  from the + module, because using "*" to mean  relies on the StarIsType extension, which will become deprecated in the future.Triggered by:  Example: None Test case(s): wcompat-warnings/WCompatWarningsOn.hszSuggests placing the  qualified keyword after the module name.Triggered by: = Example: None Test case(s): module/mod184.hsz0Suggests using TemplateHaskell quotation syntax.Triggered by:  only if TemplateHaskell is enabled. Example: None Test case(s): parser should_fail T13450TH.hsz;Suggests alternative roles in case we found an illegal one.Triggered by: 2 Example: None Test case(s): roles should_fail Roles7.hszSuggests qualifying the m1 operator in modules where StarIsType is enabled.Triggered by:  Test case(s): warningsshould_compile StarBinder.hszSuggests that for a type signature 'M.x :: ...' the qualifier should be omitted in order to be accepted by GHC.Triggered by: # Test case(s): module/mod98zSuggests to move an orphan instance (for a typeclass or a type or data family), or to newtype-wrap it.Triggered by:  Test cases(s): warningsshould_compile&T9178 typecheckshould_compile*T4912 indexed-typesshould_compileT22717_fam_orphzSuggests to use a standalone deriving declaration when GHC can't derive a typeclass instance in a trivial way.Triggered by: ! Test cases(s): typecheck should_fail tcfail086zSuggests to add a standalone kind signature when GHC can't perform kind inference.Triggered by:  Test case(s): typecheck should_fail T22560_fail_dzSuggests the user to fill in the wildcard constraint to disambiguate which constraint that is.6Example: deriving instance _ => Eq (Foo f a)Triggered by: $ Test cases(s): partial-sigs should_fail T13324_fail2zSuggests to use the appropriate Template Haskell tick: a single tick for a term-level ),, or a double tick for a type-level ).Triggered by: .zSuggests enabling -ddump-splices to help debug an issue when a  is not in scope or is used in multiple different namespaces (e.g. both as a data constructor and a type constructor).Concomitant with  NoExactName or SameName errors, see e.g. "GHC.Rename.Env.lookupExactOcc_either". Test cases: T5971, T7241, T13937.zSuggests adding a tick to refer to something which has been promoted to the type level, e.g. a data constructor.Test cases: T9778, T19984.zSomething is split off from its corresponding declaration. For example, a datatype is given a role declaration in a different module.&Test cases: T495, T8485, T2713, T5533.zSuggest a similar name that the user might have meant, e.g. suggest  when the user has written travrese.Test case: mod73.zRemind the user that the field selector has been suppressed because of -XNoFieldSelectors.4Test cases: NFSSuppressed, records-nofieldselectors.z,Suggest importing from a module, removing a hiding clause, or explain to the user that we couldn't find a module with the given .,Test cases: mod28, mod36, mod87, mod114, ...zFound a pragma in the body of a module, suggest placing it in the header.zSuggest using pattern matching syntax for a non-bidirectional pattern synonymTest cases: patsyn should_fail,record-exquant typecheck should_failT3176zSuggest tips for making a definition visible for the purpose of writing a SPECIALISE pragma for it in a different module.Test cases: nonezSuggest renaming implicitly quantified type variable in case it captures a term's name.zSuggest enabling one of the SafeHaskell modes Safe, Unsafe or Trustworthy.zSuggest removing a record wildcard from a pattern when it doesn't bind anything useful.zSuggest moving a method implementation to a different instance to its superclass that defines the canonical version of the method.z7Suggest to increase the solver maximum reduction depth zSuggest removing a method implementation when a superclass defines the canonical version of that method.zSuggest eta-reducing a type synonym used in the implementation of abstract data. zRemind the user that there is no field of a type and name in the record, constructors are in the usual order $x$, $r$, $a$ zSuggest binding the type variable on the LHS of the type declarationzSuggest using an anonymous wildcard instead of a named wildcard zSuggest explicitly quantifying a type variable instead of relying on implicit quantification z>Suggest binding explicitly; e.g data T @k (a :: F k) = .... z#Suggest a default declaration; e.g default Cls (Ty1, Ty2) zSuggest using explicit deriving strategies for a deriving clause.Triggered by: .See comment of %TcRnNoDerivingClauseStrategySpecified for context.zSuggest using an explicit deriving strategy for a standalone deriving instance.Triggered by: .See comment of )TcRnNoStandaloneDerivingStrategySpecified for context.z,Suggest add parens to pattern `e -> p :: t` z0Whether this is a family instance (of the given p), or a class instance (K).zSuggest to enable the input extension. This is the hint that GHC emits if this is not a "known" fix, i.e. this is GHC giving its best guess on what extension might be necessary to make a certain program compile. For example, GHC might suggests to enable BlockArguments when the user simply formatted incorrectly the input program, so GHC here is trying to be as helpful as possible. If the input  is not empty, it will contain some extra information about the why the extension is required, but it's totally irrelevant/redundant for IDEs and other tools.zSuggest to enable the input extensions. The list is to be intended as  disjunctive' i.e. the user is suggested to enable any) of the extensions listed. If the input  is not empty, it will contain some extra information about the why the extensions are required, but it's totally irrelevant/redundant for IDEs and other tools.zSuggest to enable the input extensions. The list is to be intended as  conjunctive' i.e. the user is suggested to enable all& the extensions listed. If the input  is not empty, it will contain some extra information about the why the extensions are required, but it's totally irrelevant/redundant for IDEs and other tools.zSuggest to enable the input extension in order to fix a certain problem. This is the suggestion that GHC emits when is more-or-less clear "what's going on". For example, if both DeriveAnyClass and GeneralizedNewtypeDeriving5 are turned on, the right thing to do is to enabled DerivingStrategies, so in contrast to z GHC will be a bit more "imperative" (i.e. "Use X Y Z in order to ... "). If the input  is not empty, it will contain some extra information about the why the extensions are required, but it's totally irrelevant/redundant for IDEs and other tools.zThe bindings we have available in scope when suggesting an explicit type signature.z8An unknown binding (i.e. too complicated to turn into a )z4Suggests a single extension without extra user info.zLike z. but allows supplying extra info for the user.zSuggests to enable every extension in the list.zLike z. but allows supplying extra info for the user.zSuggests to enable any extension in the list.zLike z. but allows supplying extra info for the user.zWhether a constructor name is printed out as a bare symbol, e.g. :.*True for symbolic names in infix position.Used for pretty-printing.z$Display info about the treatment of m under NoStarIsType.%With StarIsType, three properties of m hold:(a) it is not an infix operator (b) it is always in scope (c) it is a synonym for Data.Kind.TypeHowever, the user might not know that they are working on a module with NoStarIsType and write code that still assumes (a), (b), and (c), which actually do not hold in that module.Violation of (a) shows up in the parser. For instance, in the following examples, we have m! not applied to enough arguments:data A :: * data F :: * -> *Violation of (b) or (c) show up in the renamer and the typechecker respectively. For instance:type K = Either * BoolThis will parse differently depending on whether StarIsType is enabled, but it will parse nonetheless. With NoStarIsType it is parsed as a type operator, thus we have ((*) Either Bool). Now there are two cases to consider: There is no definition of (*) in scope. In this case the renamer will fail to look it up. This is a violation of assumption (b).There is a definition of the (*) type operator in scope (for example coming from GHC.TypeNats). In this case the user will get a kind mismatch error. This is a violation of assumption (c).The user might unknowingly be working on a module with NoStarIsType or use m as  out of habit. So it is important to give a hint whenever an assumption about m is violated. Unfortunately, it is somewhat difficult to deal with (c), so we limit ourselves to (a) and (b).z returns appropriate hints to the user depending on the extensions enabled in the module and the name that triggered the error. That is, if we have NoStarIsType and the error is related to m0 or its Unicode variant, we will suggest using '; otherwise we won't suggest anything.z8fixity declaration, role annotation, type signature, ...the 4 for the declaration sitez(move the implementation from this method... to this methodDocumentation URLz(method with non-canonical implementation/possible other method to use as the RHS insteadDocumentation URLzThose deriving clauses that we assumed a particular strategy for.z The deriving strategy we assumed3The instance signature (e.g 'Show a => Show (T a)')zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzyyyyyzzzzzzzzzzzzzzzz ,z zNone#EPretty-print an z.Pretty-print a z.# #None + 6A newtype that is a witness to the `-fprint-error-index-links` flag. It alters the  Outputable instance to emit DiagnosticCode* as ANSI hyperlinks to the HF error indexA diagnostic code is a namespaced numeric identifier unique to the given diagnostic (error or warning).All diagnostic codes defined within GHC are given the GHC namespace.5See Note [Diagnostic codes] in GHC.Types.Error.Codes.the actual diagnostic codediagnostic code prefix (e.g. GHC)Used to describe warnings and errors o The message has a file/line/column heading, plus "warning:" or "error:", added by mkLocMessage o With  the message is suppressed o Output is intended for end usersIgnore this message, for example in case of suppression of warnings users don't want to see. See Note [Suppressing Messages]The class for a diagnostic message. The main purpose is to classify a message within GHC, to distinguish it from a debug/dump message vs a proper diagnostic, for which we include a .Log message intended for compiler developers No file/line/column stuffLog messages intended for end users. No file/line/column stuff.Diagnostics from the compiler. This constructor is very powerful as it allows the construction of a - with a completely arbitrary permutation of  and ,. As such, users are encouraged to use the mkMCDiagnostic smart constructor instead. Use this constructor directly only if you need to construct and manipulate diagnostic messages directly, for example inside ". In all the other circumstances,  especially when emitting compiler diagnostics, use the smart constructor.The Maybe  field carries a code (if available) for this diagnostic. If you are creating a message not tied to any error-message type, then use Nothing. In the long run, this really should always have a . See Note [Diagnostic codes].An envelope for GHC's facts about a running program, parameterised over the domain-specific5 (i.e. parsing, typecheck-renaming, etc) diagnostics.%To say things differently, GHC emits  diagnostics= about the running program, each of which is wrapped into a  that carries specific information like where the error happened, etc. Finally, multiple s are aggregated into Ё that are returned to the user.%The actual reason caused this message0See Note [Warnings controlled by multiple flags]=The SrcSpan is used for sorting errors into line-number orderLike a ), but resolved against a specific set of DynFlags? to work out which warning flag actually enabled this warning. The reason why a Ɓ was emitted in the first place. Diagnostic messages are born within GHC with a very precise reason, which can be completely statically-computed (i.e. this is an error or a warning no matter what), or influenced by the specific state of the DynFlags) at the moment of the creation of a new Ɓ#. For example, a parsing error is always going to be an error, whereas a 'WarningWithoutFlag Opt_WarnUnusedImports' might turn into an error due to '-Werror' or '-Werror=warn-unused-imports'. Interpreting a  together with its associated  gives us the full picture.Born as a warning."Warning was enabled with the flag.+Warning was enabled with a custom category.Born as an error. A generic Ɓ message, without any further classification or provenance: By looking at a  we don't know neither where it was generated nor how to interpret its payload (as it's just a structured document). All we can do is to print it out and look at its . A generic Hint message, to be used with .ā4An existential wrapper around an unknown diagnostic.ƁA class identifying a diagnostic. Dictionary.com defines a diagnostic as:"a message output by a computer diagnosing an error in a computer program, computer system, or component device".A Ɓ carries the actual description of the message (which, in GHC's case, it can be an error or a warning) and the reason4 why such message was generated in the first place.ǁ1Type of configuration options for the diagnostic.ȁ&Extract the error message text from a Ɓ.Ɂ9Extract the reason for this diagnostic. For warnings, a  includes the warning flag.ʁExtract any hints a user might use to repair their code to avoid this diagnostic.ˁGet the  associated with this Ɓ. This can return K for at least two reasons: >The message might be from a plugin that does not supply codes.The message might not yet have been assigned a code. See the Ɓ instance for .Ideally, case (2) would not happen, but because some errors in GHC still use the old system of just writing the error message in-place (instead of using a dedicated error type and constructor), we do not have error codes for all errors. #18516 tracks our progress toward this goal.΁A ΁ is isomorphic to a '[SDoc]' but it carries the invariant that the input '[SDoc]' needs to be rendered  decorated into its final form, where the typical case would be adding bullets between each elements of the list. The type of decoration depends on the formatting function used, but in practice GHC uses the formatBulleted.ЁA collection of messages emitted by GHC during error reporting. A diagnostic message is typically a warning or an error. See Note [Messages]. INVARIANT: All the messages in this collection must be relevant, i.e. their  should not be . The smart constructor ԁ# will filter out any message which  is .ҁThe single warning case  is very common.ׁAdds a Message to the input collection of messages. See Note [Discarding Messages].؁Joins two collections of messages together. See Note [Discarding Messages].ف Joins many Ё s togetherہCreates a new ΁ out of a list of .܁Creates a new ΁ out of a single ݁ Joins two ΁ together. The resulting ΁ will have a number of entries which is the sum of the lengths of the input.ށ5Apply a transformation function to all elements of a ΁.Make a "simple" unknown diagnostic which doesn't have any configuration options.Make an unknown diagnostic which uses the same options as the context it will be embedded into.Embed a more complicated diagnostic which requires a potentially different options type.Helper function to use when no hints can be provided. Currently this function can be used to construct plain  and add hints to them, but once #18516 will be fully executed, the main usage of this function would be in the implementation of the ʁ9 typeclass method, to report the fact that a particular Ɓ has no hints.Create an error  holding just a single  Create a % from a list of bulleted SDocs and a Create an error  from a list of bulleted SDocs Shows an . Only use this for debugging.Make an error message with location info, specifying whether to show warning groups (if applicable).Returns M if this is, intrinsically, a failure. See Note [Intrinsic And Extrinsic Failures].5Are there any hard errors here? -Werror warnings are not; detected. If you want to check for -Werror warnings, use .Returns M if the envelope contains a message that will stop compilation: either an intrinsic error or a fatal (-Werror) warning.Are there any errors or -Werror warnings here?Partitions the Ё and returns a tuple which first element are the warnings, and the second the errors.:Wrap the link in terminal escape codes specified by OSC 8.8create a link to the HF error index given an error code.What kind of message?locationmessage%Print warning groups (if applicable)?What kind of message?locationmessageׁ߁ӁځՁށہԁ܁ց݁ف؁zzzzzzz΁ρƁǁˁʁȁɁҁ́́ЁсÁāŁzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzЁԁсӁՁցׁ؁فځƁǁˁʁȁɁāŁҁҁ́́߁Ázzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz΁ρہ܁݁ށ  3 # % -   . #    0 & - 1  # &$&1!#.  None Y Logger flagsFlush the trace buffer= to the given valueUpdate LogFlags Set LogFlags‚Set the trace flushing functionThe currently set trace flushing function is passed to the updating functionÂ!Calls the trace flushing function.Default trace flushing function (flush stderr)ł Log something Log a JsonDocƂDump somethingǂTrace somethingȂPush a log hookɂPop a log hookʂPush a json log hook̂Push a dump hook͂Pop a dump hook΂Push a trace hookςPop a trace hookЂMake the logger thread-safeӂLike Ԃ but appends an extra newline.ԂThe boolean arguments let's the pretty printer know if it can optimize indent by writing ascii ' ' characters without going through decoding.ՂDefault action for  dumpAction hookWrite out a dump.If --dump-to-file is set then this goes to a file. otherwise emit to stdout (via the LogAction parameter).When hdr is empty, we print in a more compact format (no separators and blank lines)ւ#Run an action with the handle of a  , if we are outputting to a file, otherwise K.>Choose where to put a dump file based on LogFlags and DumpFlagׂDefault action for  traceAction hook؂ Log somethingڂDump somethingۂLog a trace message܂$Log a dump message (not a dump file)݂!Dump if the given DumpFlag is setނ!Dump if the given DumpFlag is setUnlike ݂, has a NamePprCtx argument߂9Ensure that a dump file is created even if it stays emptyՂ҂ӂԂтׂĂڂ܂ق؂ۂ‚Ђ͂˂ɂς̂ʂȂ΂Ƃ݂ނłǂ߂ւĂɂȂ˂ʂ͂̂ς΂Ђł҂тӂԂ؂ق܂ՂƂ݂ނւ߂ڂׂǂ‚ÂۂNone){Monomorphic version of  Validity' specialised for s.Everything is fine%A problem, and some indication of whyError printing contextMax reported error countReverse error reporting orderTreat warnings as errorsFatal custom warning categories!Enabled custom warning categoriesFatal warningsEnabled warnings Computes the right  for the input & out of the 'DiagOpts. This function has to be called when a diagnostic is constructed, i.e. with a 'DiagOpts "snapshot" taken as close as possible to where a particular diagnostic message is built, otherwise the computed 9 might not be correct, due to the mutable nature of the DynFlags in GHC.Make a  for a given , consulting the . Varation of  which can be used when we are sure the input  is ! and there is no diagnostic code.Wrap a Ɓ in a ,, recording its location. If you know your Ɓ is an error, consider using ), which does not require looking at the Wrap a Ɓ in a , recording its location. Precondition: the diagnostic is, in fact, an error. That is, (diagnosticReason msg == ErrorWithoutFlag.= 2 or -ddump-timings).See Note [withTiming] for more. Worker for  and .Like  but with  SevOutput rather then SevInfo+Trace a command (when verbosity level >= 3)Record in the eventlog when the given tool command starts and finishes, prepending the given : with "systool:", to easily be able to collect and process all the systool events.For those events to show up in the eventlog, you need to run GHC with -v2 or -ddump-timings.The name of the phase.A function to force the result (often either const () or rnf)!The body of the phase to be timedThe name of the phase.A function to force the result (often either const () or rnf)!The body of the phase to be timedThe name of the phase.A function to force the result (often either const () or rnf)Whether to print the timings!The body of the phase to be timedӁՁہԁ؁΁ρƁǁˁʁȁɁЁƁǁˁʁȁɁ΁ρЁԁ؁ՁӁہ  NoneUsed when a temp file is created. This determines which component Set of PathsToClean will get the temp fileA file with lifetime TFL_CurrentModule will be cleaned up at the end of upweep_modA file with lifetime TFL_GhcSession will be cleaned up at the end of runGhc(T) do ...The tmpDir: will be a new subdirectory of the given directory, e.g.  src/sdist.342.Directory name template. See  openTempFile.#Callback that can use the directory)Temp directory to create the directory inDirectory name template. See  openTempFile.#Callback that can use the directory None )ڴ,check for Advanced Vector 512-bit Extensions۴&check for Advanced Vector Extensions 2ܴ$check for Advanced Vector ExtensionsݴError (if any) to raise when vector instructions are used, see #StgToCmm.Prim.checkVecCompatibility޴Save a foreign call target to a Cmm local, see Note [Saving foreign call target to local] for detailsߴ+Disable use of precomputed standard thunks.#Allowed to generate FMA instruction(Allowed to generate WordMul2 instruction'Allowed to generate IntMul2 instruction2Allowed to generate AddWordC, SubWordC, Add2, etc.Allowed to generate QuotRem(Allowed to generate QuotRem instructions*Allowed to emit 64-bit division operations,Allowed to emit 64-bit arithmetic operationsEnable deterministic code generation (more precisely, the deterministic unique-renaming pass in StgToCmm)!Verify tag inference predictions.>decides whether to check array bounds in StgToCmm.Prim or nottrue if -fexternal-dynamic-refs>, meaning generate code for linking against dynamic librariestrue if -fPIEtrue if -fPIC=true means don't generate interface programs (implied by -O0);true means omit heap checks when no allocation is performedNo output should be created, like in Interpreter or NoBackend.%says where to put the pipeline output its extension!basename of original input source!basename of original input sourceStop just after this phaseLift a f action into an m action.33NoneJEnable process jobs support on Windows if it can be expected to work (e.g. process >= 1.6.9.0). Version of &System.Process.readProcessWithExitCode> that takes a key-value tuple to insert into the environment.Run a command, placing the arguments in an external response file.This command is used in order to avoid overlong command line arguments on Windows. The command line arguments are first written to an external, temporary response file, and then passed to the linker via @filepath. response files for passing them in. See: 'https://gcc.gnu.org/wiki/Response_Files /https://gitlab.haskell.org/ghc/ghc/issues/10777Break a line of an error message into a filename and the rest of the line, taking care to ignore colons in Windows drive letters (as noted in #17786). For instance, "hi.c: ABCD" is mapped to Just ("hi.c", "ABCD")"C:\hi.c: ABCD" is mapped to Just ("C:\hi.c", "ABCD")stdout program path program argsaddition to the environment(exit_code, stdout, stderr)None A sectionContent of the sectionName of the section Description of the section table DynFlags -> IO [String]Ã-No additional command-line options are neededăReturn command-line options that tell GHC about the LLVM version.ŃNames a function that tells the driver what should happen after assembly code is written. This might include running a C compiler, running LLVM, running an assembler, or various similar activities. The function named normally has this type:  TPipelineClass TPhase m => PipeEnv -> HscEnv -> Maybe ModLocation -> FilePath -> m (Maybe FilePath)&The functions so named are defined in GHC.Driver.Pipeline.ʃ0After code generation, nothing else need happen.˃Names a function that generates code and writes the results to a file, of this type:  Logger -> DynFlags -> Module -- ^ module being compiled -> ModLocation -> FilePath -- ^ Where to write output -> Set UnitId -- ^ dependencies -> Stream IO RawCmmGroup a -- results from `StgToCmm` -> IO a&The functions so named are defined in GHC.Driver.CodeOutput.We expect one function per back end@or more precisely, one function for each back end that writes code to a file. (The interpreter does not write to files; its output lives only in memory.)ЃThis enumeration type specifies how the back end wishes GHC's primitives to be implemented. (Module GHC.StgToCmm.Prim provides a generic implementation of every primitive, but some primitives, like  IntQuotRemOp, can be implemented more efficiently by certain back ends on certain platforms. For example, by using a machine instruction that simultaneously computes quotient and remainder.).For the meaning of each alternative, consult GHC.StgToCmm.Config. (In a perfect world, type Ѓ would be defined there, in the module that determines its meaning. But I could not figure out how to do it without mutual recursion across module boundaries.)уPrimitives supported by LLVM҃1Primitives supported by the native code generatorӃ"Primitives supported by JS backendԃ%Primitives supported by all back endsՃAvalue of type Backend represents one of GHC's back ends. The set of back ends cannot be extended except by modifying the definition of Backend in this module.The Backend type is abstract; thatis, its value constructors are not exported. It's crucial that they not be exported, because a value of type Backend carries only the back end's name', not its behavior or properties. If Backend were not abstract, then code elsewhere in the compiler could depend directly on the name, not on the semantics, which would make it challenging to create a new back end. Because Backend is abstract, all the obligations of a new back end are enumerated in this module, in the form of functions that take Backend as an argument.The issue of abstraction is discussed at great length in #20927 and !7442.׃7Is the platform supported by the Native Code Generator?,Is the platform supported by the JS backend?؃The native code generator. Compiles Cmm code into textual assembler, then relies on an external assembler toolchain to produce machine code.4Only supports a few platforms (X86, PowerPC, SPARC).See  GHC.CmmToAsm.كThe LLVM backend.Compiles Cmm code into LLVM textual IR, then relies on LLVM toolchain to produce machine code.It relies on LLVM support for the calling convention used by the NCG backend to produce code objects ABI compatible with it (see "cc 10" or "ghccc" calling convention in  7https://llvm.org/docs/LangRef.html#calling-conventions).4Supports a few platforms (X86, AArch64, s390x, ARM).See  GHC.CmmToLlvmڃThe JavaScript Backend See documentation in GHC.StgToJSۃ!Via-C ("unregisterised") backend.Compiles Cmm code into C code, then relies on a C compiler to produce machine code."It produces code objects that are not> ABI compatible with those produced by NCG and LLVM backends.Produced code is expected to be less efficient than the one produced by NCG and LLVM backends because STG registers are not pinned into real registers. On the other hand, it supports more target platforms (those having a valid C toolchain).See  GHC.CmmToC܃The ByteCode interpreter.#Produce ByteCode objects (BCO, see  GHC.ByteCode/) that can be interpreted. It is used by GHCi.?Currently some extensions are not supported (foreign primops).See GHC.StgToByteCode݃(A dummy back end that generates no code.Use this back end to disable code generation. It is particularly useful when GHC is used as a library for other purpose than generating code (e.g. to generate documentation with Haddock) or when the user requested it (via `-fno-code`) for some reason.ރAn informal description of the back end, for use in issuing warning messages only. If code depends on what's in the string, you deserve what happens to you.߃This flag tells the compiler driver whether the back end will write files: interface files and object files. It is typically true for "real" back ends that generate code into the filesystem. (That means, not the interpreter.)When the back end does write files, this value tells the compiler in what manner of file the output should go: temporary, persistent, or specific.This flag tells the driver whether the back end can reuse code (bytecode or object code) that has been loaded dynamically. Likely true only of the interpreter.'It is is true of every back end except  -fno-code that it "generates code." Surprisingly, this property influences the driver in a ton of ways. Some examples:If the back end does not generate code, then the driver needs to turn on code generation for Template Haskell (because that code needs to be generated and run at compile time).If the back end does not generate code, then the driver does not need to deal with an output file.If the back end does/ generated code, then the driver supports  HscRecomp. If not, recompilation does not need a linkable (and is automatically up to date).When set, this flag turns on interface writing for Backpack. It should probably be the same as , but it is kept distinct for reasons described in Note [-fno-code mode].When preparing code for this back end, the type checker should pay attention to SPECIALISE pragmas. If this flag is J, then the type checker ignores SPECIALISE pragmas (for imported things?).This back end wants the  mi_top_env field of a ModIface to be populated (with the top-level bindings of the original source). Only true for the interpreter.3The back end targets a technology that implements switch natively. (For example, LLVM or C.) Therefore it is not necessary for GHC to ccompile a Cmm Switch< form into a decision tree with jump tables at the leaves.#As noted in the documentation for Ѓ, certain primitives have multiple implementations, depending on the capabilities of the back end. This field signals to module GHC.StgToCmm.Prim1 what implementations to use with this back end.When this value is , the back end is compatible with vector instructions. When it is /, it carries a message that is shown to users.This flag says whether the back end supports large binary blobs. See Note [Embedding large binary blobs] in GHC.CmmToAsm.Ppr.This flag tells the compiler driver that the back end does not support every target platform; it supports only platforms that claim NCG support. (It's set only for the native code generator.) Crufty. If the driver tries to use the native code generator without platform support, the driver fails over to the LLVM back end.This flag is set if the back end can generate code for proc points. If the flag is not set, then a Cmm pass needs to split proc points (that is, turn each proc point into a standalone procedure).This flag guides the driver in resolving issues about API support on the target platform. If the flag is set, then these things are true:"When the target platform supports only an unregisterised API, this backend can be replaced with compilation via C.When the target does not support an unregisterised API, this back end can replace compilation via C.This flag is true if the back end works *only* with the unregisterised ABI.8This flag is set if the back end generates C code in a .hc file. The flag lets the compiler driver know if the command-line flag -C is meaningful.This flag says whether SPT (static pointer table) entries will be inserted dynamically if needed. If this flag is J, then GHC.Iface.Tidy6 should emit C stubs that initialize the SPT entries.8If this flag is unset, then the driver ignores the flag -fbreak-points, since backends other than the interpreter tend to panic on breakpoints.If this flag is set, then the driver forces the optimization level to 0, issuing a warning message if the command line requested a higher optimization level.I don't understand exactly how this works. But if this flag is set *and* another condition is met, then  ghc/Main.hs will alter the DynFlags so that all the  hostFullWays4 are asked for. It is set only for the interpreter.This flag is also special for the interpreter: if a message about a module needs to be shown, do we know anything special about where the module came from? The Boolean argument is a recomp flag.This flag says whether the back end supports Haskell Program Coverage (HPC). If not, the compiler driver will ignore the `-fhpc` option (and will issue a warning message if it is used).This flag says whether the back end supports foreign import of C functions. (Supports means "does not barf on," so  -fno-code supports foreign C imports.)This flag says whether the back end supports foreign export of Haskell functions to C.When using this back end, it may be necessary or advisable to pass some `-D` options to a C compiler. This (defunctionalized) function produces those options, if any. An IO action may be necessary in order to interrogate external tools about what version they are, for example.The function's type is % Logger -> DynFlags -> IO [String]  This field is usually defaulted.This (defunctionalized) function generates code and writes it to a file. The type of the function is  Logger -> DynFlags -> Module -- ^ module being compiled -> ModLocation -> FilePath -- ^ Where to write output -> Set UnitId -- ^ dependencies -> Stream IO RawCmmGroup a -- results from `StgToCmm` -> IO aThis (defunctionalized) function tells the compiler driver what else has to be run after code output. The type of the function is  TPipelineClass TPhase m => PipeEnv -> HscEnv -> Maybe ModLocation -> FilePath -> m (Maybe FilePath)Somewhere in the compiler driver, when compiling Haskell source (as opposed to a boot file or a sig file), it needs to know what to do with the code that the  writes to a file. This J value gives instructions like "run the C compiler", "run the assembler," or "run the LLVM Optimizer."Name of the back end, if any. Used to migrate legacy clients of the GHC API. Code within the GHC source tree should not refer to a back end's name.A list of all back ends. They are ordered as we wish them to appear when they are enumerated in error messages.When foreign C import or export is invalid, the carried value enumerates the valid back ends.When foreign C import or export is invalid, the carried value enumerates the valid back ends."The Show instance is for messages only. If code depends on what's in the string, you deserve what happens to you.ރ߃܃ڃك؃݃փ׃ۃՃƒăÃ˃σ΃̃̓ŃɃȃƃʃǃЃԃӃу҃Ճ؃كڃۃ܃݃ЃԃӃу҃˃σ΃̃̓ŃɃȃƃʃǃƒăÃރ߃փ׃  None+ A FlatSwitchPlan is a list of SwitchPlans, with an integer in between every two entries, dividing the range. So if we have (abusing list syntax) [plan1,n,plan2], then we use plan1 if the expression is < n, and plan2 otherwise.A SwitchPlan abstractly describes how a Switch statement ought to be implemented. See Note [createSwitchPlan]>A value of type SwitchTargets contains the alternatives for a  CmmSwitch value, and knows whether the value is signed, the possible range, an optional default value and a map from values to jump labels.Number of consecutive default values allowed in a jump table. If there are more of them, the jump tables are split.Currently 7, as it costs 7 words of additional code when a jump table is split (at least on x64, determined experimentally).Minimum size of a jump table. If the number is smaller, the switch is implemented using conditionals. Currently 5, because an if-then-else tree of 4 values is nice and compact.Minimum non-zero offset for a jump table. See Note [Jump Table Offset].The smart constructor mkSwitchTargets normalises the map a bit: * No entries outside the range * No entries equal to the default * No default if all elements have explicit values7Changes all labels mentioned in the SwitchTargets value7Changes all labels mentioned in the SwitchTargets valueReturns the list of non-default branches of the SwitchTargets value3Return the default label of the SwitchTargets value+Return the range of the SwitchTargets value.Return whether this is used for a signed valueswitchTargetsToTable creates a dense jump table, usable for code generation.Also returns an offset to add to the value; the list is 0-based on the result of that addition.The conversion from Integer to Int is a bit of a wart, as the actual scrutinee might be an unsigned word, but it just works, due to wrap-around arithmetic (as verified by the CmmSwitchTest test case).ū ƫ ǫȫ ɫʫ"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone}A thread is in one of 4 statesThe thread is runningThe thread is blockedThe thread is doneThe thread has diedA Closure is one of six typesThe closure is a THUNKThe closure is a Function$The closure is a Partial ApplicationThe closure is a ConstructorThe closure is a BlackholeThe closure is a stack frameA Primop result is either an inlining of some JS payload, or a primitive call to a JS function defined in Shim files in base.-primop is inline, result is assigned directlyprimop is async call, primop returns the next function to run. result returned to stack top in registersTyped expressionTypes of FFI values%one toplevel block in the object file raw JS codethe codestatic closure dataµ,closure information of all closures in blockõ"toplevel symbols (stored in index)ĵ5data used to generate one ObjBlock in our object fileǵalways link this unitȵ7symbols not from a haskell id that this unit depends onɵ2pseudo-id identifiers this unit depends on (fixme)ʵ identifiers this unit depends on˵ other exports̵'exported names from haskell identifiers͵serializable unit infoε#A foreign reference to some JS codeֵA Static literal valueݵ?is function pointer, label (also used for string / binary init)޵Static Arguments. Static Arguments are things that are statically allocated, i.e., they exist at program startup. These are static heap objects or literals or things that have been floated to the top level binding by ghc.ߵreference to a heap objectliteralunfloated constructorheap object for functionheap object for CAF (field is Nothing when thunk is initialized in an alternative way, like string thunks through h$str)+unboxed constructor (Bool, Int, Double etc)regular datacon app%list initializer (with optional tail)optional CCS namestatic initialization global objectA Stack Slot is either known or unknown. We avoid maybe here for more strictness.The global Identifier Cache The identifier cache indexed on  local to a moduleSome other symbol-Keys to differentiate Ident's in the ID CacheThe type of identifiers. These determine the suffix of generated functions in JS Land. For example, the entry function for the L constructor is a  which compiles to:  function h$ghczminternalZCGHCziInternalziMaybeziJust_con_e() { return h$rs() };  which just returns whatever the stack point is pointing to. Whereas the entry function to L is an % and does the work. It compiles to:  function h$ghczminternalZCGHCziInternalziMaybeziJust_e() { var h$$baseZCGHCziMaybezieta_8KXnScrCjF5 = h$r2; h$r1 = h$c1(h$ghczminternalZCGHCziInternalziMaybeziJust_con_e, h$$ghczminternalZCGHCziInternalziMaybezieta_8KXnScrCjF5); return h$rs(); };  Which loads some payload from register 2, and applies the Constructor Entry function for the Just to the payload, returns the result in register 1 and returns whatever is on top of the stack.A plain identifier for values, no suffix added$An entry function, suffix = "_e" in 3A Constructor entry function, suffix = "_con_e" in JS primitive representationspointer = reference to heap object (closure object), lifted or not. Can also be some RTS object (e.g. TVar#, MVar#, MutVar#, Weak#) no fieldsA Double: one field$An Int (32bit because JS): one fieldA Long: two fields one for the upper 32bits, one for the lower (NB: JS is little endian)4a pointer not to the heap: two fields, array + indexsome JS object, user supplied, be careful around these, can be anything boxed array)Static references that must be kept alive The type of The closure is a THUNKThe closure is a Constructor$The closure is a Partial ApplicationThe closure is a black holeThe closure is a stack frame number of registers for the argsfunction arityClosure Information, , layout=layout stored in object itself, first position from the start?fixed size, but content unknown (for example stack apply frame)whole layout known0closure size in array positions, including entryThe list of JSReps to layoutClosure information,  , registers/A value witnessing a state of unknown registersargs)unused registers before actual args startClosure info table static references of this object2type of the object, with extra info where requiredheap/stack layout of the objectfriendly name for printing,size of the payload (in number of JS values)entry code identifier: infotable fields are stored as properties of this function-The Configuration record for the StgToJS passEmscripten linker#Enable runtime assertions settingsProfiling enabledThe JS code generator state relevant for the current binding groupextra dependencies for the linkable unit that contains this groupcurrent stack depth¶%stack info for the current expressionö&static (CAF) data in our binding groupĶ4closure metadata (info tables) for the binding groupŶ/extra toplevel statements for the binding groupƶThe JS code generator stateȶglobal (per module) statements (gets included when anything else from the module is used)ɶ#state for the current binding groupʶunfloated arguments˶*hash consing for identifiers from a Unique̶"unique number for the id generatorͶcurrent moduleζcodegen settings, read-only϶2A State monad over IO holding the generator state.жConvert  to an IntӶConvert  to a StringԶ3Convert the status of a thread in JS land to an Intն5convert the status of a thread in JS land to a stringֶstatic refs: array = references, null = nothing to report note: only works after all top-level objects have been createdѶҶӶжնԶεϵѵҵԵеӵյ϶ͶöŶƶǶȶɶ̶˶ͶζʶĵŵƵʵ̵͵ȵ˵ɵǵµõ޵ߵֵܵ׵ڵصݵٵ۵϶ƶǶȶɶ̶˶ͶζʶͶöŶ޵ߵֵܵ׵ڵصݵٵ۵εϵѵҵԵеӵյĵŵƵʵ̵͵ȵ˵ɵǵµõжѶҶӶԶնֶ ׶ ض ٶ ڶ ۶ ܶ ݶ ޶ ߶ ")  ")+-            ")+/ &(, "(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone#`Given a JStgExpr, ex, inject a trace statement on ex in the compiled JS programSyntactic sugar. Given a JStgExpr, ex4 which is assumed to be a predicate, and a message m, assert that 'not ex' is True, if not throw an exception in JS land with message m.name of the closure cType name of the closure cPerform the computation ', on the range of registers bounded by start and end.assign frame size to thisstack frame header function#size of the frame, including header"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Sylvain Henry Jeffrey Young Luite Stegeman Josh Meredith experimental Serialization/deserialization of binary .o files for the JavaScript backendNone#) :)Options obtained from pragmas in JS files*Arguments for `-sEXPORTED_RUNTIME_METHODS`$Arguments for `-sEXPORTED_FUNCTIONS`,Pass additional options to emcc at link timeEnable CPP on the JS file&Offset of the block in the object fileSymbols exported by a blockSerialized block indexes and their exported symbols (the first block is module-global)Exported Functions The function"The module containing the functiondependencies on exported symbols in other objects , blockForeignExported :: [ExpFun] , blockForeignImported :: [ForeignRef]%dependencies on blocks in this objectA BlockRef is a pair of a module and the index of the block in the object fileBlock index in the object fileModuleWhere are the blocksIn an object file at pathIn a Ar file at path In memoryBlock informationWhere to find the blocks)Information about blocks (linkable units)dependencies of each block#exported Haskell functions -> blockblocks that always need to be linked when this object is loaded (e.g. everything that contains initializer code or foreign exports)·Module they were generated fromŷA HS object fileǷBlock index: symbols per block and block offset in the object fileȷInformation about blocksɷOffset of the payload (units)ʷ0BinHandle that can be used to read the ObjBlocks˷name of the module̷:Different kinds of object (.o) supported by the JS backendͷ"JavaScript source embedded in a .oη"JS backend object for Haskell codeϷ&Wasm module object as produced by emccз%Get the kind of a file object, if anyѷ8Get the kind of an object stored in a bytestring, if anyҷwe use the convention that the first block (0) is a module-global block that's always included when something from the module is loaded. everything in a module implicitly depends on the global block. The global block itself can't have dependenciesWrite an ObjBlock, except for the top level symbols which are stored in the indexRead an ObjBlock and associate it to the given symbols (that must have been read from the index)ӷ4Given a handle to a Binary payload, add the module, mod_name, its dependencies, deps(, and its linkable units to the payload.ԷParse object headerշParse object body. Must be called after a successful getObjectHeaderַ Parse object׷Read object from file9The object is still in memory after this (see objHandle).ط3Reads only the part necessary to get the block infoٷGet blocks in the object file, using the given filtering functionڷRead blocks in the object file, using the given filtering functionHelper to convert Int to Int32Helper to convert Int32 to Int(Get the JS option pragmas from .js filesܷParse option pragma in JS fileݷ2Write a JS object (embed some handwritten JS code)޷Read a JS object from BinHandle߷ Read a JS object from ByteStringRead a JS object from fileӷmodule block infos linkable units and their symbolsܷ Input fileParsed options.۷ַٷշԷзѷܷҷ޷߷ӷ׷طڷݷķ÷·ŷƷȷʷǷ˷ɷ̷Ϸηͷ̷Ϸηͷзѷ۷ܷݷ޷߷ӷԷշַ׷ٷڷطҷŷƷȷʷǷ˷ɷ·ķ÷'                             "     "(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone# Cc objects to linkJS objects to linkArchives to load JS and Cc sources from (JS code corresponding to Haskell code is handled with blocks above)Blocks to linkBlock informationLink C sources (compiled to JS/Wasm) with Haskell code compiled to JS. This implies the use of the Emscripten RTS to load this code.Force the link with the emcc rts. Use this if you plan to dynamically load wasm modules made from C files (e.g. in iserv).(Generate all.js (combined js) + wrappers&Dump .frefs (foreign references) filesDisable .stats file generationDon't dump the generated RTS!Don't generate Haskell main entryDont' build JS executables None#Closure infotable field name Closure first payload field name!Closure second payload field name¸Closure meta field nameøClosure cost-center field nameInfotable type field nameInfotable tag field nameInfotable arity field nameŸClosure type from infotableƸFunction arity from infotableԸGet closure infotableոGet closure metadataָGet closure cost-center׸Get closure extra field 1ظGet closure extra field 2ٸNumber of arguments (arity & 0xff = arguments, arity >> 8 = number of registers)۸ heap objectreference to infotable, if you have one already (saves a c.f lookup twice)8arity tag (tag >> 8 = registers, tag & 0xff = arguments)ָø׸ظԸո¸ǸҸӸٸ۸ŸƸ˸иѸ̸͸ȸθϸɸʸĸڸǸŸƸȸɸʸ˸̸͸θϸиѸҸӸԸո׸ظָٸڸ۸¸øĸ"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNoneݸ-Context into which an expression is evaluated޸Cache the length of ߸߸Contents of current LNE frame&Variables and their index on the stack,LNE bindings with their expected stack size.The Int is the size of the stack when the LNE binding was defined. We need to shrink the stack back to this size when we enter one of the associated binder rhs: it expects its free variables at certain offsets in the stack.Source location-Target variables for the evaluated expressionTop-level binding IdInitialize an expression context in the context of the given top-level binding Id Set targetSet top-level binding IdSet source locationUpdate let-no-escape frame.Remove information about the current LNE frame>Predicate: do we know for sure that the given Id is evaluated?-Does the given Id correspond to a LNE binding;Does the given Id correspond to a LNE live var on the stackReturn the LNE stack size associated to the given Id. Return Nothing when the Id doesn't correspond to a LNE binding.&Shrink the LNE stack to the given sizeݸ޸߸ݸ߸޸None# %Number of slots occupied by a PrimRepAssign first expr only (if it exists), performing coercions between some PrimReps (e.g. StablePtr# and Addr#).&Assign p2 to p1 with optional coercion;can we unbox C x to x, only if x is represented as a Numberone-constructor types with one primitive field represented as a JS Number can be unboxedReturn SlotCount as an Int8Number of slots occupied by a value with the given JSRepAssociate the given values to each RrimRep in the given order, taking into account the number of slots per PrimRepAssociate the given values to the Id's PrimReps, taking into account the number of slots per PrimRepAssociate the given JExpr to the Id's PrimReps, taking into account the number of slots per PrimRepcollect Ids that this binding refers to (does not include the bindees themselves) first argument is Id -> StgExpr map for unfloated arguments3returns True if the expression is definitely inline!!  None#&' Ź5Used to pass arguments to newClosure with some safetyɹPayload field 2ʹPayload field 1˹InfoTable object̹Generate statements to set infotable field values for the given ClosureInfoDepending on debug flag, it generates h$setObjInfo(...) or h$o(...). The latter form doesn't store the pretty-printed name in the closure to save space.͹:Special case of closures that do not need to generate any fresh namesCache "dXXX" field namesData names are used in the AST, and logging has determined that 255 is the maximum number we see.ӹWe use this in the RTS to determine the number of generated closures. These closures use the names cached here, so we bind them to the same number.Cache "h$dXXX" namesCache "h$cXXX" namesCache "xXXX" namesdebug: output symbol namesthe object namethings in registerslayout of the object closure typeobject name, for printinga) argument, depends on type (arity, conid) static refs debug: output all symbol namesthe thing to modify closure typeobject name, for printinglist of item types in the object, if known (free variables, datacon fields)extra a( parameter, for constructor tag or arity,object size, -1 (number of vars) for unknownthings in registers static refs͹object being info'd see ciVarrhsعֹй͹̹׹ιѹԹչӹҹϹٹŹƹǹʹɹ˹ȹ¹ùĹ̹͹ιŹƹǹʹɹ˹ȹϹй¹ùĹѹҹֹعչ׹ԹٹӹNonet(Unfloat some top-level unexported thingsGHC floats constants to the top level. This is fine in native code, but with JS they occupy some global variable name. We can unfloat some unexported things:global constructors, as long as they're referenced only once by another global constructor and are not in a recursive binding groupliterals (small literals may also be sunk if they are used more than once)always sinkable, values that may be duplicated in the generated code (e.g. small literals)5once sinkable: may be sunk, but duplication is not okcollect all idents used only once in an argument at the top level and never anywhere elsefold over all id in StgArg used at the top level in an StgRhsCon%fold over all Id in StgArg in the ASTsince we have sequential initialization, topsort the non-recursive constructor bindingsthe module, since we treat definitions from the current module differently the bindingsa map with sunken replacements for nodes, for where the replacement does not fit in the  AST and the new bindingsNone#9emit a global (for the current module) toplevel statement Luite Stegeman Sylvain Henry Josh Meredith 2experimental Module to deal with JS identifiersNoneGet fresh unique number=Get fresh module-local Ident of the form: h$$unit:module_uniq2Generate unique Ident for the given ID (uncached!)"The ident has the following forms:global Id: h$unit:module.name[_num][_type_suffix] local Id: h$$unit:module.name[_num][_type_suffix]_uniqRetrieve default variable name for the given Id with sub index)Retrieve all the JS vars for the given Id-Retrieve entry variable name for the given Id5Retrieve datacon entry variable name for the given IdRetrieve datacon worker entry variable name for the given dataconRetrieve datacon worker entry variable name for the given dataconDeclare all js vars for the id"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone# Run the action, m, with no stack inforun the action, m, with current stack info, but don't let modifications propagate͈Set stack depthΈGet stack depthψModify stack depthoverwrite our stack knowledge$retrieve our current stack knowledgeЈModify stack slotsadd % unknown slots to our stack knowledge#add knowledge about the stack slotsdrop  slots from our stack knowledgeGrow the stack pointer by  without modifying the stack depth. The stack is just a JS array so we add to grow (instead of the traditional subtract)Shrink the stack pointer by '. The stack grows downward so substract(Wrapper which adjusts the stack pointer and& modifies the stack depth tracked in ϶ . See also 5 which actually does the stack pointer manipulation.Shrink the stack and stack pointer. NB: This function is unsafe when the input *, is negative. This function wraps around # which actually performs the work.A constant array that holds global function symbols which do N pushes onto the stack. For example:  function h$p1(x1) { ++h$sp; h$stack[(h$sp - 0)] = x1; }; function h$p2(x1, x2) { h$sp += 2; h$stack[(h$sp - 1)] = x1; h$stack[(h$sp - 0)] = x2; }; and so on up to 32. Convert all function symbols in  to global top-level functions. This is a hack which converts the function symbols to variables. This hack is caught in & to turn these into global functions.Partial Push functions. Like 8 except these push functions skip slots. For example,  function h$pp33(x1, x2) { h$sp += 6; h$stack[(h$sp - 5)] = x1; h$stack[(h$sp - 0)] = x2; }; The 33rd entry skips slots 1-4 to bind the top of the stack and the 6th slot. See  and  for use cases.Like # but for the partial push functionsoptimized push that reuses existing values on stack automatically chooses an optimized partial push (h$ppN) function when possible.)push a let-no-escape frame onto the stack0Pop things, don't update the stack knowledge in ϶Load 'length (xs :: [JStgExpr])' things from the stack at offset 'n :: Int'. This function does no stack pointer manipulation, it merely indexes into the stack and loads payloads into xs."Pop but preserve the first N slotsш Just like  but operate on s rather than Blindly pop N slots?Generate statements to update the current node with a blackholeWrapper around =, performs the stack manipulation before updating the Thunk.Update a thunk by checking . If the config inlines black holes then update inline, else make an explicit call to the black hole handler.:contents of the slots, True if same value is already therenumber of slots to skip!assign stack slot values to theseNone#)*%Generate JS expressions for a LiteralLiterals represented with 2 values: * Addr# (Null and Strings): array and offset * 64-bit values: high 32-bit, low 32-bit * labels: call to h$mkFunctionPtr and 0, or function name and 0-generate a literal for the static init tables"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone҈4Unique Id -> ExportedFun (only to other modules)ӈUnique Module -> UnitGenerate module dependency dataGenerate the object's dependency data, taking care that package and module names are only stored once"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith 4experimental Code generation of data constructorsNone#ڹGenerate a data constructor. Special handling for unboxed tuples۹Allocate a data constructor. Allocate in this context means bind the data constructor to toܹAllocate an unboxed data constructor. If we have a bool we calculate the right value. If not then we expect a singleton list and unbox by converting ''C x' to x. NB. This function may panic.ݹ Allocate an entry function. See  for the object layout.޹Allocate a dynamic objectݹ csInlineAlloc from StgToJSConfig۹޹ݹܹڹڹ۹ܹݹ޹"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith 8experimental Code generation of application argumentsNone) Ԉ%Generate JS code for static arguments߹Generate JS code for an StgArgGenerate a Var as JStgExprGenerate an Id as an Ident&Generate IDs for stack arguments. See  for use caseAllocate Static ConstructorsAllocate unboxed constructorsAllocate Static list.Generate JS code corresponding to a static arg7Generate JS code corresponding to a list of static args ߹ ߹None#Ոgenerate the actual callՈ6catch exception and convert them to haskell exceptions/async (only valid with javascript calling conv)#using javascript calling conventionֈasyncusing JavaScript calling conv׈)Nothing for sync, Just callback for async"javascript calling convention usedpattern called return type5expressions to return in (may be more than necessary) arguments"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone#/ ؈Apply specificationو0number of JavaScript variables for the argumentsڈnumber of Haskell argumentsۈCalling convention܈(Calling convention for an apply function݈&Fast calling convention: use registersވ&Slow calling convention: use the stackPre-generated functions for fast Apply. These are bundled with the RTS..Generate an application of some args to an Id.The case where args is null is common as it's used to generate the evaluation code for an Id.߈Try to use a specialized pre-generated application function. If there is none, use h$ap_gen_fast instead"Name of the generic apply function"Expr of the generic apply functionReturn the name of the specialized apply function for the given number of args, number of arg variables, and calling convention.Return the expression of the specialized apply function for the given number of args, number of arg variables, and calling convention.Warning: the returned function may not be generated! Use specApplyExprMaybe if you want to ensure that it exists.Return the expression of the specialized apply function for the given number of args, number of arg variables, and calling convention. Return Nothing if it isn't generated.Make an ApplySpec from a calling convention, a list of Haskell args, and a list of corresponding JS variables7Find a specialized application function if there is one,List of specialized apply function templates&Generate a tag for the given ApplySpec=Warning: tag doesn't take into account the calling convention1Generate a tag expression for the given ApplySpec.Build arrays to quickly lookup apply functionsh$apply[r << 8 | n] = function application for r regs, n args h$paps[r] = partial application for r registers (number of args is in the object) Push a continuation on the stackFirst push the given args, then push an apply function (specialized if possible, otherwise the generic h$ap_gen function).Generic stack apply function (h$ap_gen) that can do everything, but less efficiently than other more specialized functions.Stack layout: -3: ... -2: args -1: tag (number of arg slots << 8 | number of args)Regs: R1 = applied closureGeneric fast apply function (h$ap_gen_fast) that can do everything, but less efficiently than other more specialized functions.3Signature tag in argument. Tag: (regs << 8 | arity) Regs: R1 = closure to apply to7Make specialized apply function for the given ApplySpec=Make specialized apply function with Stack calling conventionthe function to call (Left for generic, Right for specialized)id of the pap object0the function that's called (can be a second pap)number of arguments in pap!values for the supplied arguments  "(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone#/0;The garbageCollector resets registers and result variables.Reset the register r in JS Land. Note that this "resets" by setting the register to a dummy variable called "null", not by setting to JS's nil value.Reset the return variable r in JS Land. Note that this "resets" by setting the register to a dummy variable called "null", not by setting to JS's nil value.Define closures based on size, these functions are syntactic sugar. Each Closure constructor follows the naming convention h$cN, where N is a natural number. For example, h$c (with the nat omitted) is a JS Land Constructor for a closure which has a single entry function , and no fields; identical to h$c0. h$c1 is a for a closure with an entry function , and a single field x1, 'Just foo' is an example of this kind of closure. h$c2 is a constructor for a closure with an entry function and two data fields: x1 and x2. And so on. Note that this has JIT performance implications; you should use h$c1, h$c2, h$c3, ... h$c24 instead of making objects manually so layouts and fields can be changed more easily and so the JIT can optimize better.3JS Payload to perform stack manipulation in the RTS#JS payload to declare the registers:JS payload to define getters and setters on the registers.;JS payload that defines the functions to load each registerAssign registers R1 ... Rn in descending order, that is assign Rn first. This function uses the 7 array to construct functions which set the registers.JS payload which defines an array of function symbols that set N registers from M parameters. For example, h$l4 compiles to:  function h$l4(x1, x2, x3, x4) { h$r4 = x1; h$r3 = x2; h$r2 = x3; h$r1 = x4; }; 'JS payload to declare return variables.'JS payload defining the types closures.'JS payload declaring the RTS functions.Generated RTS code*JS Payload which defines the embedded RTS.None 34Extract the default case alternative findDefaultStg :: [Alt b] -> ([Alt b], Maybe (Expr b))ӫ3Strip ticks of a given type from an STG expression.ԫStrip ticks of a given type from an STG expression returning only the expression.ի0Do we allow the given top-level (static) ConApp? իΫЫѫϫҫ̫ͫ˫ӫԫ ͫΫϫЫѫӫԫҫ̫˫իNone֫֫׫2 2ث22None ۫Is it a RHS for a join-point?ܫ:RHS type (only used in the JS backend: layering violation)ݫRHS expressionޫEmpty for thunks4Try to make a non top-level StgRhsCon if appropriate0Try to make a top-level StgRhsCon if appropriate ߫٫ګޫݫ۫ܫ ٫ګޫݫ۫ܫ߫None have we run the unariser yet?Top-level bindings can't inherit the cost centre stack from their (static) allocation site.extra vars in scope from GHCimodule being compiledhave we run Unarise yet?who produced the STG?  None +3Simple convert env to a env of the 'InferTaggedBinders pass with no other changes.Look up a sig in the given envLook up a sig in the env or derive it from information in the arg itself. 000000000007 7None LocalFVs: set of variable that are: (a) bound locally (by a lambda, non-top-level let, or case); that is, it appears in the  field of 1 (b) appear free in the expression It is a  deterministic set because it is used to annotate closures with their free variables, and we want closure layout to be deterministic.4Invariant: the LocalFVs returned is a subset of the  field of Env*ImpFVs: set of variables that are importedIt is a non-deterministic set because we use it only to perform module dependency analysis.TopFVs: set of variables that are: (a) bound at the top level of this module, and (b) appear free in the expression It is a non-deterministic set because we use it only to perform dependency analysis on the top-level bindings.Set of locally-bound, not-top-level binders in scope. That is, variables bound by a let (but not let-no-escape), a lambda (in a StgRhsClsoure), a case binder, or a case alternative. These are the variables that must be captured in a function closure, if they are free in the RHS. Example f = x. let g = y. x+1 let h = z. g z + 1 in h x In the body of h we have locals = {x, g, z}. Note that f is top level and does not appear in locals.Dependency sort a STG program, and annotate it with free variables The returned bindings: * Are in dependency order * Each StgRhsClosure is correctly annotated (in its extension field) with the free variables needed in the closure * Each StgCase is correctly annotated (in its extension field) with the variables that must be saved across the case!Dependency analysis on STG terms.Dependencies of a binding are just free variables in the binding. This includes imported ids and ids in the current module. For recursive groups we just return one set of free variables which is just the union of dependencies of all bindings in the group.Implementation: pass bound variables (NestedIds) to recursive calls, get free variables (TopFVs) back. We ignore imported TopFVs as they do not change the ordering but it improves performance (see nameIsExternalFrom call in vars_fvs).None  .The CSE environment. See Note [CseEnv Example]The third component is an in-scope set, to rename away any shadowing bindersIf we come across a case expression case x as b of @ with a trivial binder, we add b C x to this. This map is *only* used when looking something up in the ce_conAppMap. See Note [Trivial case scrutinee]This substitution is applied to the code as we traverse it. Entries have one of two reasons:The input might have shadowing (see Note [Shadowing in Core]), so we have to rename some binders as we traverse the tree.If we remove `let x = Con z` because `let y = Con z` is in scope, we note this here as x C y.The main component of the environment is the trie that maps data constructor applications (with their - arguments) to an in-scope name that can be used instead. This name is always either a let-bound variable or a case binder.Note [CseEnv Example] ~~~~~~~~~~~~~~~~~~~~~ The following tables shows how the CseEnvironment changes as code is traversed, as well as the changes to that code.InExpr OutExpr conAppMap subst in_scope JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ -- empty {} {} case @ as a of {Con x y -> case @ as a of {Con x y -> -- Con x y C a {} {a,x,y} let b = Con x y (removed) -- Con x y C a bCa {a,x,y,b} let c = Bar a let c = Bar a -- Con x y C a, Bar a C c bCa {a,x,y,b,c} let c = some expression let c' = some expression -- Con x y C a, Bar a C c bCa, cCc', {a,x,y,b,c,c'} let d = Bar b (removed) -- Con x y C a, Bar a C c bCa, cCc', dCc {a,x,y,b,c,c',d} (a, b, c d) (a, a, c' c);This function short-cuts let-bindings that are now obsolete    None4M+pRecover the type of a well-typed Core expression. Fails when applied to the actual A7 expression as it cannot really be said to have a typep4Returns the type of the alternatives right hand sidepReturns the type of the first alternative, which should be the same as for all alternativespMakes a (->) type or an implicit forall type, depending on whether it is given a type variable or a term variable. This is used, for example, when producing the type of a lambda.pp% for multiple type or value argumentspDetermines the type resulting from applying an expression with given typepWrap the given expression in the coercion safely, dropping identity coercions and coalescing nested coercionspWraps the given expression in the source annotation, dropping the annotation if possible.p b }&depending on whether we have to use a case or let" binding for the expression (see p). It's used by the desugarer to avoid building bindings that give Core Lint a heart attack, although actually the simplifier deals with them perfectly well. See also pp tests whether we have to use a case rather than let7 binding for this expression as per the invariants of : see  GHC.Core#let_can_float_invariant* (needsCaseBinding ty rhs) requires that ty has a well-defined levity, else `typeLevity ty` will fail; but that should be the case because p- is only called once typechecking is completepThis guy constructs the value that the scrutinee must have given that you are in one particular branch of a casep$Extract the default case alternativepFind the case alternative corresponding to a particular constructor: panics if no such constructor existspMerge alternatives preserving order; alternatives in the first argument shadow ones in the secondpGiven: )case (C a b x y) of C b x y -> ...We want to drop the leading type argument of the scrutinee leaving the arguments to match against the patternp$Refine the default alternative to a _, if there is a unique way to do so. See Note [Refine DEFAULT case alternatives]qThe worker function for Note [exprIsTrivial] and Note [getIdFromTrivialExpr] This is meant to have the code of both functions in one place and make it easy to derive custom predicates.(trivial_expr_fold k_id k_triv k_not_triv e) * returns (k_id x) if e is a variable x1 (with trivial wrapping) * returns (k_lit x) if e is a trivial literal l. (with trivial wrapping) * returns k_triv if e is a literal, type, or coercion (with trivial wrapping) * returns k_not_triv otherwisewhere "trivial wrapping" is * Type application or abstraction * Ticks other than V * `case e of {}` an empty caseqTo a first approximation, q( returns True of an expression that is:Safe to evaluate even if normal order eval might not evaluate the expression at all, andSafe not- to evaluate even if normal order would do soMore specifically, this means that: * A: Evaluation of the expression reaches weak-head-normal-form, * B: soon, * C: without causing a write side effect (e.g. writing a mutable variable).In particular, an expression that may * throw a synchronous Haskell exception, or * risk an unchecked runtime exception (e.g. array out of bounds, divide by zero) is not= considered OK-for-speculation, as these violate condition A.For q, condition A is weakened to allow expressions that might risk an unchecked runtime exception but must otherwise reach weak-head-normal-form. (Note that q implies q)But in fact both functions are a bit more conservative than the above, in at least the following ways:W1: We do not take advantage of already-evaluated lifted variables. As a result, q DOES NOT imply q ; if y' is a case-binder of lifted type, then  exprIsHNF y is M, while exprOkForSpeculation y is J. See Note [exprOkForSpeculation and evaluated variables] for why.W2: Read-effects on mutable variables are currently also included. See Note [Classifying primop effects] GHC.Builtin.PrimOps.W3: Currently, q always returns J for let-expressions. Lets can be stacked deeply, so we just give up. In any case, the argument of q is usually in a strict context, so any lets will have been floated away.;As an example of the considerations in this test, consider: -let x = case y# +# 1# of { r# -> I# r# } in Ebeing translated to: 3case y# +# 1# of { r# -> let x = I# r# in E }We can only do this if the y# +# 1# is ok for speculation: it has no side effects, and can't diverge or raise an exception..See also Note [Classifying primop effects] in GHC.Builtin.PrimOps8 and Note [Transformations affected by primop effects].q is used to define Core's let-can-float invariant. (See Note [Core let-can-float invariant] in GHC.Core.) It is therefore frequently called on arguments of unlifted type, especially via p. But it is sometimes called on expressions of lifted type as well. For example, see Note [Speculative evaluation] in GHC.CoreToStg.Prep.qTo a first approximation, q( returns True of an expression that is:Safe to evaluate even if normal order eval might not evaluate the expression at all, andSafe not- to evaluate even if normal order would do soMore specifically, this means that: * A: Evaluation of the expression reaches weak-head-normal-form, * B: soon, * C: without causing a write side effect (e.g. writing a mutable variable).In particular, an expression that may * throw a synchronous Haskell exception, or * risk an unchecked runtime exception (e.g. array out of bounds, divide by zero) is not= considered OK-for-speculation, as these violate condition A.For q, condition A is weakened to allow expressions that might risk an unchecked runtime exception but must otherwise reach weak-head-normal-form. (Note that q implies q)But in fact both functions are a bit more conservative than the above, in at least the following ways:W1: We do not take advantage of already-evaluated lifted variables. As a result, q DOES NOT imply q ; if y' is a case-binder of lifted type, then  exprIsHNF y is M, while exprOkForSpeculation y is J. See Note [exprOkForSpeculation and evaluated variables] for why.W2: Read-effects on mutable variables are currently also included. See Note [Classifying primop effects] GHC.Builtin.PrimOps.W3: Currently, q always returns J for let-expressions. Lets can be stacked deeply, so we just give up. In any case, the argument of q is usually in a strict context, so any lets will have been floated away.;As an example of the considerations in this test, consider: -let x = case y# +# 1# of { r# -> I# r# } in Ebeing translated to: 3case y# +# 1# of { r# -> let x = I# r# in E }We can only do this if the y# +# 1# is ok for speculation: it has no side effects, and can't diverge or raise an exception..See also Note [Classifying primop effects] in GHC.Builtin.PrimOps8 and Note [Transformations affected by primop effects].q is used to define Core's let-can-float invariant. (See Note [Core let-can-float invariant] in GHC.Core.) It is therefore frequently called on arguments of unlifted type, especially via p. But it is sometimes called on expressions of lifted type as well. For example, see Note [Speculative evaluation] in GHC.CoreToStg.Prep.qA special version of q used during Note [Speculative evaluation]. When the predicate arg fun_ok returns False for b, then b! is never considered ok-for-spec.qShould we look past this tick when eta-expanding the given function?See Note [Ticks and mandatory eta expansion] Takes the function we are applying as argument.q:exprIsHNF returns true for expressions that are certainly already evaluated to head normal form. This is used to decide whether it's ok to perform case-to-let for lifted expressions, which changes: case x of x' { _ -> e }into: let x' = x in e'and in so doing makes the binding lazy. So, it does not treat variables as evaluated, unless they say they are. However, it does treat partial applications and constructor applications as values, even if their arguments are non-trivial, provided the argument type is lifted. For example, both of these are values: &(:) (f x) (map f xs) map (...redex...)because & on such things completes immediately.3For unlifted argument types, we have to be careful: C (f x :: Int#)Suppose f x diverges; then C (f x) is not a value. We check for this using needsCaseBinding belowq Similar to q but includes CONLIKE functions as well as data constructors. Conlike arguments are considered interesting by the inliner.Returns true for values or value-like expressions. These are lambdas, constructors / CONLIKE functions (as determined by the function argument) or PAPs.qCan we bind this  at the top level?qCheck if the expression is zero or more Ticks wrapped around a literal string.qExtract a literal string from an expression that is zero or more Ticks wrapped around a literal string. Returns Nothing if the expression has a different shape. Used to "look through" Ticks in places that need to handle literal strings.qA cheap equality test which bales out fast! If it returns True the arguments are definitely equal, otherwise, they may or may not be equal.q9Cheap expression equality test, can ignore ticks by type.q-Finds differences between core bindings, see diffExpr.The main problem here is that while we expect the binds to have the same order in both lists, this is not guaranteed. To do this properly we'd either have to do some sort of unification or check all possible mappings, which would be seriously expensive. So instead we simply match single bindings as far as we can. This leaves us just with mutually recursive and/or mismatching bindings, which we then speculatively match by ordering them. It's by no means perfect, but gets the job done well enough.%Only used in GHC.Core.Lint.lintAnnotsFinds differences between core expressions, modulo alpha and renaming. Setting top means that the IdInfo6 of bindings will be checked for differences as well.Find differences in IdInfo. We will especially check whether the unfoldings match, if present (see  diffUnfold).Find differences in unfoldings. Note that we will not check for differences of IdInfo in unfoldings, as this is generally redundant, and can lead to an exponential blow-up in complexity.)Add location information to diff messagesqTrue if the type has no non-bottom elements, e.g. when it is an empty datatype, or a GADT with non-satisfiable type parameters, e.g. Int :~: Bool. See Note [Bottoming expressions]See Note [No alternatives lint check] for another use of this function.qIf 1normSplitTyConApp_maybe _ ty = Just (tc, tys, co) then ty |> co = tc tys. It's .#, but looks through coercions via p. Hence the "norm" prefix.q-collectMakeStaticArgs (makeStatic t srcLoc e) yields Just (makeStatic, t, srcLoc, e).Returns Nothing for every other expression.qDoes this binding bind a join point (or a recursive group of join points)?qDo we expect there to be any benefit if we make this var strict in order for it to get treated as as cbv argument? See Note [Which Ids should be strictified] See Note [CBV Function Ids] for more background.pCase alternative constructor!Things bound by the pattern match*The type arguments to the case alternativepType constructor of scrutinee's type (used to prune possibilities)And its type arguments imposs_cons: constructors known to be impossible due to the form of the scrutinee Alternativesp$Uniques for constructing new binders.Multiplicity annotation of the case expression$Type constructor of scrutinee's type"Type arguments of scrutinee's type3Constructors that cannot match the DEFAULT (if any)M', if a default alt was replaced with a _`RpqppqqqpppqqqqqqqqqqqqqqqqqqqpqqpppqqqpqqqpqppppppqppppqpppppqppqqpppppppqppppppppppppppppppppppppppppppRqqqqqqqqpqqqqqqqqpqqqqqqqq`pqqqqpppppqqqqqqqqqqNone -The analysis monad consists of the following  components:: Reader-like context. Contains a substitution, info about how how lifted identifiers are to be expanded into applications and configuration options. .: Writer output for the resulting STG program.No pure state componentBut wrapping around 2 for generating fresh lifted binders. (The uniqAway approach could give the same name to two different lifted binders, so this is necessary.)We need to detect when we are lifting something out of the RHS of a recursive binding (c.f. GHC.Stg.Lift.Monad#floats), in which case that binding needs to be added to the same top-level recursive group. This requires we detect a certain nesting structure, which is encoded by  and . Although  will only ever care if the current binding to be lifted (through ) will occur inside such a binding group or not, e.g. doesn't care about the nesting level as long as its greater than 0.)Environment threaded around in a scoped, Reader-like fashion.Lifted s don't occur as free variables in any closure anymore, because they are bound at the top-level. Every occurrence must supply the formerly free variables of the lifted , so they in turn become free variables of the call sites. This environment tracks this expansion from lifted s to their free variables.-s to -s. Invariant: /s not present in this map won't be substituted.(We need to track the renamings of local -s to their lifted -, because shadowing might make a closure's free variables unavailable at its call sites. Consider: * let f y = x + y in let x = 4 in f x  Here, f9 can't be lifted to top-level, because its free variable x# isn't available at its call site. Read-only. uncurry  .  = idFlattens an expression in [] into an STG program, see GHC.Stg.Lift.Monad#floats4. Important pre-conditions: The nesting of opening StartBindinGroups and closing EndBindinGroups is balanced. Also, it is crucial that every binding group has at least one recursive binding inside. Otherwise there's no point in announcing the binding group in the first place and an ASSERT will trigger.Omitting this makes for strange closure allocation schemes that crash the GC.Writes a plain  to the output.&Starts a recursive binding group. See GHC.Stg.Lift.Monad#floats and .$Ends a recursive binding group. See GHC.Stg.Lift.Monad#floats and .Lifts a binding to top-level. Depending on whether it's declared inside a recursive RHS (see GHC.Stg.Lift.Monad#floats and ), this might be added to an existing recursive top-level binding group.Takes a binder and a continuation which is called with the substituted binder. The continuation will be evaluated in a  context in which that binder is deemed in scope. Think of it as a  computation: After the continuation finishes, the new binding won't be in scope anymore.See . Similarly to , this function takes a set of variables to abstract over, the binder to lift (and generate a fresh, substituted name for) and a continuation in which that fresh, lifted binder is in scope.It takes care of all the details involved with copying and adjusting the binder and fresh name generation.See .Substitutes a binder  occurrence), which was brought in scope earlier by  / .:Whether the given binding was decided to be lambda lifted.Returns an empty list for a binding that was not lifted and the list of all local variables the binding abstracts over (so, exactly the additional arguments at adjusted call sites) otherwise. Creates an expander function for the current set of lifted binders. This expander function will replace any - by their corresponding - and, in addition, will expand any lifted binders by the former free variables it abstracts over.   !#(NoneFor a binding we: * Look at the args * Mark any argument as call-by-value if: - It's argument to a worker and demanded strictly - Unless it's an unlifted type already * Update the id See Note [CBV Function Ids] See Note [Attaching CBV Marks to ids]ͪʪ˪̪˪̪ʪͪNone qAdd a substitution for an  to the Q: you must ensure that the in-scope set is such that TyCoSubst Note [The substitution invariant] holds after extending the substitution like thisqAdds multiple  substitutions to the Q : see also qqAdd a substitution appropriate to the thing being substituted (whether an expression, type, or coercion). See also q, Q, QqAdd a substitution as appropriate to each of the terms being substituted (whether expressions, types, or coercions). See also q.qFind the substitution for an  in the Q The Id should not be a CoVarqSimultaneously substitute for a bunch of variables No left-right shadowing ie the substitution for (x y. e) a1 a2 so neither x nor y scope over a1 a2q.substExpr applies a substitution to an entire 1. Remember, you may only apply the substitution once/: See Note [Substitutions apply only once] in GHC.Core.TyCo.SubstDo *not* attempt to short-cut in the case of an empty substitution! See Note [Extending the IdSubstEnv]q"Apply a substitution to an entire _$, additionally returning an updated Q2 that should be used by subsequent substitutions.q"Apply a substitution to an entire _$, additionally returning an updated Q2 that should be used by subsequent substitutions.qDe-shadowing the program is sometimes a useful pre-pass. It can be done simply by running over the bindings with an empty substitution, because substitution returns a result that has no-shadowing guaranteed.(Actually, within a single type* there might still be shadowing, because substTy is a no-op for the empty substitution, but that's probably OK.) Aug 09This function is not used in GHC at the moment, but seems so short and simple that I'm going to leave it hereqSubstitutes a " for another one according to the Q- given, returning the result and an updated Q3 that should be used by subsequent substitutions.  is preserved by this process, although it is substituted into appropriately.qApplies q to a number of s, accumulating a new Q left-to-rightq,Substitute in a mutually recursive group of sqVery similar to q , but it always allocates a new  for each variable in its output. It substitutes the IdInfo though. Discards non-Stable unfoldingsqApplies q to a number of s, accumulating a final substitution from left to right Discards non-Stable unfoldingsq$Clone a mutually recursive group of sqSubstitute into some ! with regard to the supplied new .. Discards unfoldings, unless they are StableqSubstitutes for the *s within an unfolding NB: substUnfolding discards any unfolding without without a Stable source. This is usually what we want, but it may be a bit unexpectedqSubstitutes for the *s within an unfolding NB: substUnfolding discards any unfolding without without a Stable source. This is usually what we want, but it may be a bit unexpectedqSubstitutes for the  s within the b given the new function qDrop free vars from the breakpoint if they have a non-variable substitution."Substitution to use for the IdInfo Substitution and Id to transform-Transformed pair NB: unfolding may be zapped9qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqQQQQQQQQQQQQQQQQQQQQQQQ/9QQQQ/qqqQQqqqqqqqqqqqqqQQQqQqqQQqqqqQQQQQQQQqqQqqqQQqqqqqNoneNone2State Monad used inside exitify8Traverses the AST, simply to find all joinrecs and call exitify8 on them. The really interesting function is exitifyRecGiven a recursive group of a joinrec, identifies @exit paths@ and binds them as join-points outside the joinrec.NoneGiven a binding of in_id to in_rhs , and a fresh name to refer to in_id (out_id>, created from addBinder or addRecBinders), first try to CSE in_rhs>, and then add the resulting (possibly CSE'd) binding to the , so that we attempt to CSE any expressions which are equal to out_rhs. We use a different env for cse on the rhs and for extendCSEnvWithBinding for reasons explain in See Note [Separate envs for let rhs and body]Given a binder `let x = e`, this function determines whether we should add `e -> x` to the cs_map Runs CSE on a single expression.This entry point is not used in the compiler itself, but is provided as a convenient entry point for users of the GHC API.extendCSEnv env e triv_expr will replace any occurrence of e with  triv_expr going forward.Add clones to the substitution to deal with shadowing. See Note [Shadowing in CSE] for more details. You should call this whenever you go under a binder.Noneq;The analysis lattice of arity analysis. It is isomorphic to  data ArityType' = AEnd Divergence | ALam OneShotInfo ArityType' 1Which is easier to display the Hasse diagram for:  ALam OneShotLam at | AEnd topDiv | ALam NoOneShotInfo at | AEnd exnDiv | AEnd botDiv  where the at fields of ALam6 are inductively subject to the same order. That is, ALam os at1 < ALam os at2 iff  at1 < at2.Why the strange Top element? See Note [Combining case branches: optimistic one-shot-ness]We rely on this lattice structure for fixed-point iteration in q. For the semantics of q, see Note [ArityType].`AT oss div` is an abstraction of the expression, which describes its lambdas, and how much work appears where. See Note [ArityType] for more informationIf r is dead-ending (]), then application to `length os` arguments will surely diverge, similar to the situation with ].qmanifestArity sees how many leading value lambdas there are, after looking through castsq6(typeArity ty) says how many arrows GHC can expose in ty, after looking through newtypes. More generally, (typeOneShots ty) returns ty's [OneShotInfo], based only on the type itself, using typeOneShot on the argument type to access the "state hack".Like d, but taking the Horrible State Hack in to account See Note [The state-transformer hack] in GHC.Core.Opt.Arityq/Returns whether the lambda associated with the  is certainly applied at most once This one is the "business end", called externally. It works on type variables as well as Ids, returning True Its main purpose is to encapsulate the Horrible State Hack See Note [The state-transformer hack] in GHC.Core.Opt.Arityq+The number of value args for the arity typeAssuming this ArityType is all we know, find the arity of the function, and trim the argument info (and Divergence) to match that arity. See Note [SafeArityType]Trim an arity type so that it has at most the given arity. Any excess &s are truncated to ], even if they end in ABot. See Note [Arity trimming]qThe Arity returned is the number of value args the expression can be applied to without doing much workLeast upper bound in the q lattice. See the haddocks on q for the lattice.Used for branches of a case.The ArityEnv used by q.8Whether the analysis should be pedantic about bottoms. q always is. A version of q that considers results from arity analysis and optionally the expression's type. Under q, no expressions are cheap. A version of q that considers results from arity analysis. See Note [Arity analysis] for what's in the signature environment and why it's important.q(An approximate, even faster, version of q Roughly exprArity e = arityTypeArity (cheapArityType e) But it's a bit less clever about bottomsWe do not guarantee that exprArity e <= typeArity e You may need to do arity trimming after calling exprArity See Note [Arity trimming] Reason: if we do arity trimming here we have take exprType and that can be expensive if there is a large castr etaExpand n e1 returns an expression with the same meaning as e, but with arity n.Given: e' = etaExpand n eWe should have that: ty = exprType e = exprType e'mkEtaWW n _ fvs ty will compute the , necessary for eta-expanding an expression e :: ty to take n value arguments, where fvs are the free variables of e.Note that this function is entirely unconcerned about cost centres and other semantically-irrelevant source annotations, so call sites must take care to preserve that info. See Note [Eta expansion and SCCs].r`tryEtaReduce [x,y,z] e sd` returns `Just e'` if `x y z -> e` is evaluated according to sd1 and can soundly and gainfully be eta-reduced to e'. See Note [Eta reduction soundness] and Note [Eta reduction makes sense] when that is the case.Can we eta-reduce the given function See Note [Eta reduction soundness], criteria (B), (J), and (W).rIf 'pushCoValArg co = Just (co_arg, co_res), then (\x.body) |> co = (\y. let { x = y |> co_arg } in body) |> co_res)or, equivalently 3(fun |> co) arg = (fun (arg |> co_arg)) |> co_resIf the LHS is well-typed, then so is the RHS. In particular, the argument  arg |> co_arg is guaranteed to have a fixed  RuntimeRep, in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.rSplit an expression into the given number of binders and a body, eta-expanding if necessary. Counts value *and* type binders.r(This is the BNF of the generated output:  @ We format AT [o1,..,on] topDiv as o1..on.T and AT [o1,..,on] botDiv as o1..on.E", respectively. More concretely, AT [NOI,OS,OS] topDiv is formatted as ?11.T6. If the one-shot info is empty, we omit the leading .@.;Info about one lambda in an ArityType See Note [ArityType]&How many value arguments to eta-expand5The pretty-printed original expression, for warnings.=A super-set of the free vars of the expression to eta-expand.The variables in  are fresh wrt. to the incoming /. The outgoing / extends the incoming / with the fresh variables in .#qqqrrrrrqqqrqqqqqqqrrrrrrrqqqqqqqqq#qqqqqqqqqqrrrqqqqrqqqqqqqqrrrrrrrrrr r r r r"(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith .experimental Code generation of ExpressionsNone#)OA  represents a possible branching path of an Stg case statement, i.e., a possible code path from an Evaluate an expression in the given expression context (continuation))regular let binding: allocate heap objectGenerate let-no-escape entryLet-no-escape entries live on the stack. There is no heap object associated with them.A let-no-escape entry is called like a normal stack frame, although as an optimization, [] is not set when making the call. This is done later if the thread needs to be suspended.)Updatable let-no-escape binders have one private slot in the stack frame. This slot is initially set to null, changed to h$blackhole when the thunk is being evaluated./Generate the entry function for a local closureGenerate the entry function types for identifiers. Note that this only returns either  or .Generate the body of an objectFind the result type after applying the function to the arguments$It's trickier than it looks because: we don't have the Arity of the Id. The following functions return different values in some cases: - idArity - typeArity . idType - idFunRepArity - typeArity . unwrapType . idType Moreover the number of args may be different than all of these aritiessometimes the type is Any, perhaps after some unwrapping. For example HappyAbsSyn is a newtype around HappyAny which is Any or (forall a. a).Se we're left to use the applied arguments to peel the type (unwrapped) one arg at a time. But passed args are args after unarisation so we need to unarise every argument type that we peel (using typePrimRep) to get the number of passed args consumed by each type arg.In case of failure to determine the type, we default to LiftedRep as it's probably what it is.-Ensure that the set of identifiers has valid L's. This function returns a no-op when  in  is False.Given a set of  s, bind each  to the appropriate data fields in N registers. This assumes these data fields have already been populated in the registers. For the empty, singleton, and binary case use register 1, for any more use as many registers as necessary.'Pop a let-no-escape frame off the stackGenerate an updated given an Blackhole single entryOverwrite a single entry object with a special thunk that behaves like a black hole (throws a JS exception when entered) but pretends to be a thunk. Useful for making sure that the object is not accidentally entered multiple timesReorder the things we need to push to reuse existing stack values as much as possible True if already on the stack at that locationAllocate local closuresConsume Stg case statement and generate a case statement. See also Consume an Stg case alternative and generate the corresponding alternative in JS land. If one alternative is a continuation then we must normalize the other alternatives. See  and .If  is set, then generate an assertion that asserts the pattern match is valid, e.g., the match is attempted on a Boolean, a Data Constructor, or some number.If one branch ends in a continuation but another is inline, we need to adjust the inline branch to use the continuation conventionLoad an unboxed tuple. Loading means getting all Idents from the input ID's, declaring them as variables in JS land and binding them, in order, to es.4Switch for pattern matching on constructors or primsif/else for pattern matching on things that js cannot switch on the list of branches is expected to have the default alternative first, if it exists.Wrapper to construct sequences of (===), e.g., mkEq [l0,l1,l2] [r0,r1,r2] = (l0 === r0) && (l1 === r1) && (l2 === r2)"Generate a primitive If-expression‰ Load parameters from constructorÉDetermine if a branch will end in a continuation or not. If not the inline branch must be normalized. See  NB. not a Monoidĉ*Push return arguments onto the stack. The 9 tracks whether the value is already on the stack or not, used in .ʼn2Load the return arguments then pop the stack frameƉ8allocate multiple, possibly mutually recursive, closuresljGenerate a primop. This function wraps around the real generator , handling the ݸ1 and all arguments before generating the primop.A list of stack slots. -- Id: stored on the slot -- Int: the part of the value that is stored -- Bool: True when the slot already contains a value"lhs to assign expression result toid being matchedtypethe alternativesȉtoplevel id for the resultdatacon to matchmatch alternative with binders None)  ɉ1TailUsageDetails captures the result of applying ʉ to a function `xyz.body`. The TailUsageDetails pairs together * the number of lambdas (including type lambdas: a JoinArity) * UsageDetails for the body of the lambda, unadjusted by ˉ. If the binding turns out to be a join point with the indicated join arity, this unadjusted usage details is just what we need; otherwise we need to discard tail calls. That's what ˉ does.rSee bBinderSwaOk.̉Condensed variant of ͉ needed during loop breaking.Ή (#22336) See Note [Boxing constructors] in GHC.Builtin.TypesrLifts a "small" constructor into a "big" constructor by recursive decompositionrSplit a list into lists that are small enough to have a corresponding tuple arity. The sub-lists of the result all have length <=  But there may be more than  sub-listsrBuilds a selector which scrutinises the given expression and extracts the one name from the list given. If you want the no-shadowing rule to apply, the caller is responsible for making sure that none of these names are in scope.If there is just one 7 in the tuple, then the selector is just the identity.0If necessary, we pattern match on a "big" tuple.A tuple selector is not linear in its argument. Consequently, the case expression built by r must consume its scrutinee Many? times. And all the argument variables must have multiplicity Many.r is like r but one-tuples are NOT flattened (see Note [Flattening one-tuples])rBuilds a selector which scrutinises the given expression and extracts the one name from the list given. If you want the no-shadowing rule to apply, the caller is responsible for making sure that none of these names are in scope.If there is just one 7 in the tuple, then the selector is just the identity.0If necessary, we pattern match on a "big" tuple.A tuple selector is not linear in its argument. Consequently, the case expression built by r must consume its scrutinee Many? times. And all the argument variables must have multiplicity Many.ىى is like r, but for tuples that are guaranteed never to be "big". Also does not unwrap boxed types. mkSmallTupleSelector [x] x v e = [| e |] mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]ډ is like ى but one-tuples are NOT flattened (see Note [Flattening one-tuples])ډى is like r, but for tuples that are guaranteed never to be "big". Also does not unwrap boxed types. mkSmallTupleSelector [x] x v e = [| e |] mkSmallTupleSelector [x,y,z] x v e = [| case e of v { (x,y,z) -> x } |]rA generalization of r?, allowing the body of the case to be an arbitrary expression.;To avoid shadowing, we use uniques to invent new variables./If necessary we pattern match on a "big" tuple.ۉAs r, but for a tuple that is small enough to be guaranteed not to need nesting.r/Applies the floats from right to left. That is wrapFloats [b1, b2, @, bn] u = let b1 in let b2 in @ in let bn in ur Makes a list [] for lists of the specified typer Makes a list (:) for lists of the specified typerMake a list containing the given expressions, where the list has the given typerMake a fully applied  expressionrMake a build6 expression applied to a locally-bound worker functionr&Makes a Nothing for the specified typer/Makes a Just from a value of the specified type܉!Exception with type "forall a. a"Any exceptions added via this function needs to be added to the RTS's initBuiltinGcRoots() function.݉An  for an Id, such as މ, that throws an (imprecise) exception after being supplied one value arg for every argument ]9 in the list. The demands end up in the demand signature. 8Sets the demand signature to unleash the given arg dmds ]Sets the arity info so that it matches the length of arg demands/Sets a bottoming CPR sig with the correct arityIt's important that all 3 agree on the arity, which is what this defn ensures. rfunction argumentsrfunctionargumentr scrutineeres_tyaltsrguardthenelser5"Small" constructor function, of maximum input arity /Possible "big" list of things to construct from:Constructed thing made possible by recursive decompositionrThe $s to pattern match the tuple againstThe  to select,A variable of the same type as the scrutinee ScrutineeSelector expressionrThe $s to pattern match the tuple againstThe  to select,A variable of the same type as the scrutinee ScrutineeSelector expressionrThe tuple identifiers to pattern match on; Bring these into scope in the bodyBody of the case ScrutineeۉThe tuple argsBody of the case,A variable of the same type as the scrutinee ScrutineerElement type of the listFold result typeCons! function expression for the foldNil expression for the fold#List expression being folded acressr!Type of list elements to be built+Function that, given information about the s of the binders for the build worker function, returns the body of that workerrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrprrrrrrrrrrrrrrrrprrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr #Generic helpers for the HsSyn type.((c) The University of Glasgow, 1992-2023None  &')+3-All binders corresponding to a single implicit record field pattern.'See Note [Collecting implicit binders].The binders of the RHS of the record field pattern (in practice, always a singleton: see Note [Collecting implicit binders])The  of the record field߉A bijection between record fields of a datatype and integers, used to implement Note [Collecting record fields in data declarations]. An integer i such that no integer i' >= i appears in the .3Look up the index of a field label in the previous .Look up a field from its index.3A mapping from constructors to all of their fields.9See Note [Collecting record fields in data declarations].This class specifies how to collect variable identifiers from extension patterns in the given pass. Consumers of the GHC API that define their own passes should feel free to implement instances in order to make use of functions which depend on it.In particular, Haddock already makes use of this, with an instance for its DocNameI pass so that it can reuse the code in GHC for collecting binders.Indicate if evidence binders and type variable binders have to be collected.This type enumerates the modes of collecting bound variables | evidence | type | term | ghc | | binders | variables | variables | pass | -------------------------------------------- CollNoDictBinders | no | no | yes | any | CollWithDictBinders | yes | no | yes | GhcTc | CollVarTyVarBinders | no | yes | yes | GhcRn |*See Note [Dictionary binders in ConPatOut]Don't collect evidence bindersCollect evidence bindersCollect variable and type variable binders, but no evidence binders e => (e)A simple case alternative with a single pattern, no binds, no guards; pre-typecheckingWrap in parens if ~ appPrec says it needs them So f x becomes (f x), but 3 stays as 3.A useful function for building OpApps. The operator is always a variable, and we don't know the fixity yet. NB: Only for % .΀ Wildcard pattern - after parsingπ!Wildcard pattern - after renaming4The Big equivalents for the source tuple expressions1The Big equivalents for the source tuple patterns Convert an 7 to an 6. Convert an 7 to an 6.Convert 7 to 7. The former is what is parsed, but the latter is what we need in class/instance declarationsType ascription: (e :: ty)8Not infix, with place holders for coercion and free vars!In Name-land, with empty bind_fvsIf any of the matches in the 7 are infix, the 7 is considered infix. Return the 0 encompassing the contents of any enclosed bindsConvenience function using . This is for generated bindings only, do not use for user-written code.#Make a prefix, non-strict function TShould we treat this as an unlifted bind? This will be true for any bind that binds an unlifted variable, but we must be careful around AbsBinds. See Note [isUnliftedHsBind]. For usage information, see Note [Strict binds checks] is GHC.HsToCore.Binds.5Is a binding a strict variable or pattern bind (e.g. !x = ...)?Collect  binders only, or "s + pattern synonyms, respectively Collect both s and pattern-synonym bindersSame as #, but works over a list of bindingsCollect s, or /s + pattern synonyms, depending on boolean flagUsed exclusively for the bindings of an instance decl which are all FunBindsReturns all the binding names of the decl. The first one is guaranteed to be the name of the decl. The first component represents all binding names except record fields; the second represents field occurrences. For record fields mentioned in multiple constructors, the SrcLoc will be from the first occurrence.3Each returned (Located name) has a SrcSpan for the whole- declaration. See Note [SrcSpan for binders]See Note [SrcSpan for binders]Collects record pattern-synonym selectors only; the pattern synonym names are collected by .the < returned are for the whole declarations, not just the namesthe < returned are for the whole declarations, not just the names:Collect all record wild card binders in the given pattern.These are all the variables bound in all (possibly nested) record wildcard patterns appearing inside the pattern.'See Note [Collecting implicit binders].yy݀ހʀˀǀȀÀ܀׀ŀՀЀـԀҀрӀڀĀۀ؀ƀɀր€̀߀̀΀πÀŀĀƀЀрҀӀԀՀր݀ހ€ǀȀʀˀɀ̀̀΀π߀yy׀܀؀ـڀۀ -None 3extra source files (e.g. from #includes). The lexer collects these from '#  file  line' pragmas, which the C preprocessor leaves behind. These files and their timestamps are stored in the .hi file, so that we can force recompilation if any of them change (#3589)"End of file and end of prior tokenComments before start of top decl, used in exact printing only#Semis before the start of top decls,Haskell Module extension point: GHC specific-Haddock module info and description, unparsed9reason/explanation for warning/deprecation of this moduleLayout info for the module. For incomplete modules (e.g. the output of parseHeader), it is EpNoLayout.{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{|||||||||}|||||||}|||||}||||}|||||55555~~~~~~~~~~~~~~~~~~~~~~~~VVV~~VVV~~~~~~~~~~~~555EEEDDEEDDEEEEDzzzzzzz|||{||||||||||||T{yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy݀ހʀˀǀȀÀ܀׀ŀՀЀـԀҀрӀڀĀۀ؀ƀɀր€̀߀̀΀π111111111211111111111111111111111111111211111111111111111877878777;;;;;;;;;;;;;;;;;;;;;UUUUUUUUU TTTTTTT77777777%77\\\\\\{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{z{{{{{{zzzzz{|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||555555555555555555555555555555~~~~~~~~~~~~~~~~~~~~~~~~}}}}}}~~~~~~~}}}}}}}}}}}}}}}~~~}}}}}~~~~~~~~~~~~}}}}~~~~~~}}~~~~~~~~}~~~~UVVVV~~}}}}}}}}}~~}}}}}}V~~~~~~~~~~V}}}}}}}}}}}}}}}}}}}}~~~~~~}~}~~~}~~55555555555555555DDDDDDDDDDDDDDzzzzzzzzz{{{{{{{{{{{{{{{{{{{{xxxxxxyyxxxxyyyyxyyyyxxxxxxxxxxx0000000100000000001110000000000000000000000001111101111111111111111111111111001110011111111111111100000000000000000000000000000111111111111111111111VVVVVVVV 777777777777777777777777777777777777777777777777777777777777777777777777777777777778888888999999999999999::::::::::::::::::999999999::::99999999999999999999999999::::::::::::::::::::9999999999999999:::99999:::::::::;;;;;;;;;;;;;;;;:::::::9:::::::;:::;;;::::9999999999989:99:999::9;:::98999:::99989:::8889999999999999999999::::::::::::::::::::::::::::::::::::::::999999988888898999TTTTTTTUUUUUTTTUUTTT%TTTTTTTTTUUUTTTTUUUUUUUUUUUUUU%TTTTT%UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUTTTTTTTTTTTTTTTTTTUUUTTTTTTTTUTTTTTTUUUU%TTTUTUU%UUUUUUUUUUUTTTTUUUUU%UUUUTTTUUTTTTTTTTTTTTTTTTTTTTTTTTTT%TTT 88888888888888888888888888888888888888888SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS%%SSSTTSSTTTSSTTSSSSSTTTTSSSSS7666666655555566566666666666666666666666777777777667666666666666666666666666666666666666666666666666666666666666666666666666666676577777776667756%%%56666666656556666 VVVVVVVV  % (Nonez ..., we are checking the type a because it's the type of a term variable bound in a lambda, so we use ̋.5What context requires a fixed runtime representation?)What type are we checking? For example, a[tau] in a[tau] :: TYPE rr[tau].The context in which a representation-polymorphism check was performed.Does not include the type on which the check was performed; see  for that. stores the origin of a skolem type variable, so that we can display this information to the user in case of a type error.The  field allows us to report all skolem type variables bound in the same place in a single report. stores the origin of a skolem type variable (e.g. bound by a user-written forall, the header of a data declaration, a deriving clause, ...).This information is displayed when reporting an error message, such as "Couldn't match k with l" C [a] where ... When typechecking the instance decl itself, including producing evidence for the superclasses of C, the superclasses of (Foo a) and (Bar a) will have  origin. is used only for the Wanted constraints for the superclasses of an instance declaration.Testing whether the constraint associated with an instance declaration in a signature file is satisfied upon instantiation.Test cases: backpack should_failbkpfail{11,43}.bkpIs at least one of the three elements above visible? (Errors from the polymorphic subsumption check are considered visible.) Only used for prioritizing error messages. The thing that has type "actual""Some kind of type variable binder.Used for reporting errors, in  and TcSolverReportMsg.Some thing which has a type.This datatype is used when we want to report to the user that something has an unexpected type.Report Redundant Constraints.Œ"Don't report redundant constraintsÌReport redundant constraints The SrcSpan is for the constraints E.g. f :: (Eq a, Ord b) => blah The span is for the (Eq a, Ord b) We need to record the span here because we have long since discarded the HsType in favour of a TypeČUserTypeCtxt describes the origin of the polymorphic type in the places where we need an expression to have that type8Wrap up the origin of a skolem type variable with a new 8, so that we can common up skolem type variables whose  shares a certain .Did a constraint arise from expanding a Wanted constraint to look at superclasses?)Extract a suitable CtOrigin from a HsExpr-Extract a suitable CtOrigin from a MatchGroup-Extract a suitable CtOrigin from guarded RHSs7Extract a suitable CtOrigin from a list of guarded RHSsShort one-linersPrint the context for a FixedRuntimeRep# representation-polymorphism check.6Note that this function does not include the specific L4 which is not fixed. That information is stored in  and is reported separately. rebindable syntax operator!function used in the view patternfunctionargumentname of the function equations!the entire lambda-case expressionۋargument position (1-indexed)Just like GivenOriginThe number of superclass selections necessary to get this constraint; see Note [Replacement vs keeping] in GHC.Tc.Solver.DictTrue => "blocked": cannot use this to solve naked superclass Wanteds i.e. ones with (ScOrigin _ NakedSc) False => can use this to solve all Wanted constraints See Note [Solving superclass constraints] in GHC.Tc.TyCl.Instance)Module in which the instance was declaredThe declared typeclass instanceThe Unique is used to common up skolem variables bound at the same location (only used in pprSkols)IsGroupClosed describes a group of mutually-recursive bindingsЍ+IdBindingInfo describes how an Id is bound.?It is used for the following purposes: a) for static forms in  and b) to figure out when a nested binding can be generalised, in .ԍ?A typecheckable thing available in a local context. Could be Ս 1, but also lexically scoped variables, etc. See GHC.Tc.Utils.Env for how to retrieve a  given a .#No signature or a partial signatureMatches on either a global  or a f.̍ЍҍӍэ΍ύ͍܍ݍߍލԍՍٍ֍؍׍ۍڍ܍ݍߍލԍՍٍ֍؍׍ۍڍЍҍӍэ΍ύ͍̍    " !       " NoneA stripped down version of TcM' which is sufficient for zonking types.Information needed by the , monad, which is a slimmed down version of TcM* with just enough information for zonking.Same as traceTc, but for the  monad.     NoneAdditional context to include in an error message, e.g. "In the type signature ...", "In the ambiguity check for ...", etc.None /Local typechecker environment for a constraint.Used to restore the environment of a constraint when reporting errors, see  setCtLocM. See also  TcLclCtxt.See Note [SubGoalDepth]+Take a CtLoc and moves it to the kind level+ȎÎӎŽĎŎƎΎώ͎̎ˎҎЎɎюǎʎ+ŎŽĎƎÎȎ̎Ɏʎˎǎ͎ΎҎюώЎӎԎ Վ֎ None(׎Whether or not one  can rewrite another is determined by its flavour and its equality relation. See also Note [Flavours with roles] in GHC.Tc.Solver.InertSetێStores a set of CoercionHoles that have been used to rewrite a constraint. See Note [Wanteds rewrite Wanteds].?A place for type-checking evidence to go after it is generated.Wanted equalities use HoleDest,other Wanteds use EvVarDest.bind this var to the evidence EvVarDest is always used for non-type-equalities e.g. class constraintsfill in this hole with the evidence HoleDest is always used for type-equalities See Note [Coercion holes] in GHC.Core.TyCo.RepAn  individual# problem that might be logged in a A set? of problems in checking the validity of a type equality. See  checkTypeEq.Used to indicate extra information about why a CIrredCan is irreducible0This constraint has a non-canonical shape (e.g. c Int, for a variable c)8An equality where some invariant other than (TyEq:H) of Ï is not satisfied; the  states exactly whyAn equality that cannot be decomposed because it is representational. Example:  a b ~R# Int. These might still be solved later. INVARIANT: The constraint is a representational equality constraintA nominal equality that relates two wholly different types, like  Int ~# Bool or a b ~# 3=. INVARIANT: The constraint is a nominal equality constraintAn equality like T a b c ~ Q d e where either T or Q is an abstract type constructor. See Note [Skolem abstract data] in GHC.Core.TyCon. INVARIANT: The constraint is an equality constraint between two TyConAppsA typechecker plugin returned this in the pluginBadCts field of TcPluginProgress/Why did we decide that a type was not concrete?The type contains a TyConApp of a non-concrete .3See Note [Concrete types] in GHC.Tc.Utils.Concrete.The type contains a type variable that could not be made concrete (e.g. a skolem type variable).The type contains a cast.The type contains a forall.The type contains a  CoercionTy.3Why did we require that a certain type be concrete?Concreteness was required by a representation-polymorphism check.;See Note [The Concrete mechanism] in GHC.Tc.Utils.Concrete.Why did the check fail?7Which representation-polymorphism check did we perform? Where did this check take place?,Used to indicate which sort of hole we have.Either an out-of-scope variable or a "true" hole in an expression (TypedHoles). The HoleExprRef says where to write the the erroring expression for -fdefer-type-errors.(A hole in a type (PartialTypeSignatures)A hole in a constraint, like @f :: (_, Eq a) => ... Differentiated from TypeHole because a ConstraintHole is simplified differently. See Note [Do not simplify ConstraintHoles] in GHC.Tc.Solver.A hole stores the information needed to report diagnostics about holes in terms (unbound identifiers or underscores) or in types (also called wildcards, as used in partial type signatures). See Note [Holes].Where hole was writtenType to be printed to the user For expression holes: type of expr For type holes: the missing typeThe name of this holeWhat flavour of hole is this?A delayed error, to be reported after constraint solving, in order to benefit from deferred unifications. A hole (in a type or in a term).See Note [Holes].+A type could not be ensured to be concrete.;See Note [The Concrete mechanism] in GHC.Tc.Utils.Concrete.A  is a type that can appear on the left of a canonical equality: a type variable or exactly-saturated type family application.ƏSays how many layers of superclasses can we expand. Invariant: ExpansionFuel should always be >= 0 see Note [Expanding Recursive Superclasses and ExpansionFuel]ȏA ȏ-type is one that has been fully rewritten with respect to the inert set; that is, it has been rewritten by the algorithm in GHC.Tc.Solver.Rewrite. (Historical note: ȏ, for years and years, meant that a type was type-family-free. It does *not* mean this any more.)ɏ&Do not expand superclasses any furtherʏ4Consumes one unit of fuel. Precondition: fuel > 0ˏ>Returns True if we have any fuel left for superclass expansion̏asserts if fuel is non-negative͏*asserts if fuel is strictly greater than 0֏?Are we sure that more solving will never solve this constraint?׏8No problems in checking the validity of a type equality.؏Check whether a  is marked successful.Check whether a  has a Check whether a  has one  and no otherMark a  as not having an insoluble occurs-check: any occurs check under a type family or in a representation equality is soluble.Retain only information about occurs-check failures, because only that matters after recurring into a kind.Returns the evidence  for the argument  when this  is a ڎ.Returns K otherwise.Makes a new equality predicate with the same role as the given evidence.Get the flavour of the given (Get the equality relation for the given Is a type a canonical LHS? That is, is it a tyvar or an exactly-saturated type family application? Does not look through type synonyms. Convert a  back into a Retrieve the kind of a Are two s equal?Returns free variables of constraints as a non-deterministic setReturns free variables of constraints as a non-deterministic setReturns free variables of constraints as a deterministically ordered list. See Note [Deterministic FV] in GHC.Utils.FV.Returns free variables of constraints as a deterministically ordered list. See Note [Deterministic FV] in GHC.Utils.FV.Returns free variables of constraints as a composable FV computation. See Note [Deterministic FV] in  GHC.Utils.FV.Returns free variables of constraints as a composable FV computation. See Note [Deterministic FV] in GHC.Utils.FV.Returns free variables of a bag of constraints as a non-deterministic set. See Note [Deterministic FV] in  GHC.Utils.FV.Returns free variables of a bag of constraints as a deterministically ordered list. See Note [Deterministic FV] in  GHC.Utils.FV.Returns free variables of a bag of constraints as a deterministically ordered list. See Note [Deterministic FV] in GHC.Utils.FV.Returns free variables of a bag of constraints as a composable FV computation. See Note [Deterministic FV] in  GHC.Utils.FV.Returns free variables of a bag of constraints as a composable FV computation. See Note [Deterministic FV] in GHC.Utils.FV.Returns free variables of WantedConstraints as a non-deterministic set. See Note [Deterministic FV] in  GHC.Utils.FV.Returns free variables of WantedConstraints as a deterministically ordered list. See Note [Deterministic FV] in  GHC.Utils.FV.Returns free variables of WantedConstraints as a composable FV computation. See Note [Deterministic FV] in  GHC.Utils.FV.Returns free variables of Implication as a composable FV computation. See Note [Deterministic FV] in  GHC.Utils.FV.A constraint is considered to be a custom type error, if it contains custom type errors anywhere in it. See Note [Custom type errors in constraints]9Is this an user error message type, i.e. either the form  TypeError err or Unsatisfiable err?3Does this constraint contain an user error message?(That is, the type is either of the form Unsatisfiable err%, or it contains a type of the form  TypeError msg5, either at the top level or nested inside the type.Is this type an unsatisfiable constraint? If so, return the error message.True if taking superclasses of givens, or of wanteds (to perhaps expose more equalities or functional dependencies) might help to solve this constraint. See Note [When superclasses help]Checks whether a the given wanted constraints are solved, i.e. that there are no simple constraints left and all the implications are solved.#Gather all the type variables from  that it would be unhelpful to default. For the moment, these are only f metavariables participating in a nominal equality whose other side is not concrete; it's usually better to report those as errors instead of defaulting.Returns True of constraints that are definitely insoluble, as well as TypeError constraints. Can return M for Given constraints, unlike .&The function is tuned for application after constraint solving i.e. assuming canonicalisation has been done That's why it looks only for IrredCt; all insoluble constraints are put into CIrredCanDoes this hole represent an "out of scope" error? See Note [Insoluble holes])Get the equality relation relevant for a ݎ$Get the rewrite-role relevant for a ݎ- See Note [The rewrite-role of a constraint]Return the rewrite-role of an abitrary CtEvidence See Note [The rewrite-role of a constraint] We return ReprEq for (a ~R# b) and NomEq for all other predsĐ$Extract the set of rewriters from a ݎ See Note [Wanteds rewrite Wanteds] If the provided CtEvidence is not for a Wanted, just return an empty set.ːSet the type of CtEvidence.-This function ensures that the invariants on ݎ hold, by updating the evidence and the ctev_pred in sync with each other. See Note [CtEvidence invariants].Ր-Extract the flavour, role, and boxity from a ݎ֐$Extract the flavour and role from a א$Extract the flavour and role from a TyCon of the family Arguments, exactly saturating the familyҐ̏͏ʏƐǐŐԐՐĐÐȐאՏݏޏُۏ׏ߏ܏ڏ؏ΏϏɏΐِؐЏ֐яӏԏѐ͐֏̐ҏˏӐʐːɐАϐӎΎώҎЎÏŏďݎގߎ؎َڎ׎ǏƏێ܎ȏȏϏŏďǏЏяΏϏӏҏՏԏƏɏʏˏ̏͏֏׏ُڏݏۏ܏ޏߏ؏ҎЎΎώӎݎގߎ̐͐ŐÐƐǐĐȐɐːʐێ܎ΐѐҐϐАӐ؎َڎԐ׎Րא֐ِؐڐ ې ܐ ݐ %ސ !ߐ $   # " %  !            &  !*,2 None None HoleFit is the type we use for valid hole fits. It contains the element that was checked, the Id of that element as found by tcLookup, and the refinement level of the fit, which is the number of extra argument holes that this fit uses (e.g. if hfRefLvl is 2, the fit is for `Id _ _`).A fit that is just displayed as is. Here so thatHoleFitPlugins can inject any fit they want.,Documentation of this HoleFit, if available.;What the refinement variables got matched with, if anythingThe wrapper for the match. The number of holes in this fit.$The type of the id, possibly zonked.The candidate that was checked.The elements id in the TcMHoleFitCandidates are passed to hole fit plugins and then checked whether they fit a given typed-hole.The hole itself, if available.The nested implications of the hole with the innermost implication first.Any relevant Cts to the hole ! !  %< <%4 4%. .   None+в²ʲƲ̲ѲòDzȲɲͲβ˲ŲϲIJƲɲȲ˲Dzʲ̲Ͳϲβ²òIJŲѲвNone߲See Note [Safe Haskell Overlapping Instances Implementation] in GHC.Tc.SolverReturns True iff there are no Given constraints that might, potentially, match the given class constraint. This is used when checking to see if a Given might overlap with an instance. See Note [Instance and Given overlap] in GHC.Tc.Solver.Dict+Is it (potentially) loopy to use the first ct1 to solve ct2?Necessary (but not sufficient) conditions for this function to return True:ct1 and ct2& both arise from superclass expansion,ct1 is a Given and ct2 is a Wanted.See Note [Solving superclass constraints] in GHC.Tc.TyCl.Instance, (sc2). don't solve itcbv, must be a CycleBreakerTv'type family application the cbv maps to(cbv,expansion) pairsڲ۲ݲܲ޲߲ٲزҲӲԲղײֲڲ۲ݲܲ޲߲ٲزղײֲҲӲԲ     #  None)6&)Represents the head of a match against a b or literal. Really similar to A.Undecidable semantic equality result. See Note [Undecidable Equality for PmAltCons]Literals (simple and overloaded ones) for pattern match checking.-See Note [Undecidable Equality for PmAltCons] A data type that caches for the ij of x the results of querying dsGetCompleteMatches* and then striking out all occurrences of K for which we already know x D K from these sets.For motivation, see Section 5.3 in Lower Your Guards. See also Note [Implementation of COMPLETE pragmas]The residual sets for all COMPLETE sets from pragmas that are visible when compiling this module. Querying that set with dsGetCompleteMatches requires DsM, so we initialise it with K until first needed in a DsM context.The residual set for the vanilla COMPLETE set from the data defn. Tracked separately from , because it might only be known much later (when we have enough type information to see the ? of the match), or not at all even. Until that happens, it is K.See dz.ijInformation about an . Stores positive (ɳ) facts, like  x ~ Just 42, and negative (ȳ5) facts, like "x is not (:)". Also caches the type (vi_ty), the  of a COMPLETE set (Ƴ).+Subject to Note [The Pos/Neg invariant] in GHC.HsToCore.Pmc.Solver.ƳA cache of the associated COMPLETE sets. At any time a superset of possible constructors of each COMPLETE set. So, if it's not in here, we can't possibly match on it. Complementary to ȳ. We still need it to recognise completion of a COMPLETE set efficiently for large enums.dz8Can this variable be E? Models (mutually contradicting) x ~ E and x D E constraints. E.g. * : Don't know; Neither x ~ E nor x D E. * : x ~ E * : x D EȳNegative info: A list of *s that it cannot match. Example, assuming 0 data T = Leaf Int | Branch T T | Node Int T then x D [Leaf, Node] means that x cannot match a Leaf or Node, and hence can only match Branch!. Is orthogonal to anything from ɳ, in the sense that  returns PossiblyOverlap for any pairing between ɳ and ȳ.ɳPositive info:  apps it is (i.e. x ~ [Just y, PatSyn z]), all at the same time (i.e. conjunctive). We need a list because of nested pattern matches involving pattern synonym case x of { Just y -> case x of PatSyn z -> ... } However, no more than one RealDataCon in the list, otherwise contradiction because of generativity.ʳThe  in question. Important for adding new constraints relative to this ij when we don't easily have the  available.˳The term oracle state. Stores ij for encountered s. These entries are possibly shared when we figure out that two variables must be equal, thus represent the same set of values.!See Note [TmState invariants] in GHC.HsToCore.Pmc.Solver.ͳWhich ij needs to be checked for inhabitants because of new negative constraints (e.g. x D E or x D K).γAn environment for looking up whether we already encountered semantically equivalent expressions that we want to represent by the same  representative.ϳFacts about term variables. Deterministic env, so that we generate deterministic error messages.гThe type oracle state. An  that we incrementally add local type constraints to, together with a sequence number that counts the number of times we extended it with new facts.ԳA disjunctive bag of ֳ"s, representing a refinement type.ֳA normalised refinement type D ("nabla"), comprised of an inert set of canonical (i.e. mutually compatible) term and type constraints that form the refinement type's predicate.س"Term oracle; things like x~NothingٳType oracle; things like a~Int+An initial nabla that is always satisfiable!Initial state of the term oracle.޳Like lookupVarInfo ts x, but lookupVarInfo ts x = (y, vi)3 also looks through newtype constructors. We have x ~ N1 (... (Nk y)) such that the returned y doesn't have a positive newtype constructor constraint associated with it (yet). The ij returned is that of y's representative.Careful, this means that idType x might be different to idType y", even modulo type normalisation!See also Note [Coverage checking Newtype matches] in GHC.HsToCore.Pmc.Solver.When  can be decided. True  = Equal, False  = Disjoint./Undecidable equality for values represented by 1s. See Note [Undecidable Equality for PmAltCons] Just True ==> Surely equal Just False. ==> Surely different (non-overlapping, even!)Nothing" ==> Equality relation undecidable Type of a /Undecidable equality for values represented by b4s. See Note [Undecidable Equality for PmAltCons]. bs aren't enforced to be generative, so two syntactically different bs might match the exact same values. Without looking into and reasoning about the pattern synonym's definition, we can't decide if their sets of matched values is different. Just True ==> Surely equal Just False. ==> Surely different (non-overlapping, even!)Nothing" ==> Equality relation undecidableWhether there is a  in the  that compares  to the given  according to .'We can't in general decide whether two ?s match the same set of values. In addition to the reasons in  and , a 2 might or might not represent the same value as a 1. See Note [Undecidable Equality for PmAltCons]. Just True ==> Surely equal Just False. ==> Surely different (non-overlapping, even!)Nothing" ==> Equality relation undecidable.Examples (omitting some constructor wrapping):/eqPmAltCon (LitInt 42) (LitInt 1) == Just False: Lit equality is decidable0eqPmAltCon (DataCon A) (DataCon B) == Just False": DataCon equality is decidable4eqPmAltCon (LitOverInt 42) (LitOverInt 1) == Nothing$: OverLit equality is undecidable-eqPmAltCon (PatSyn PA) (PatSyn PB) == Nothing#: PatSyn equality is undecidable-eqPmAltCon (DataCon I#) (LitInt 1) == Nothing: DataCon to Lit comparisons are undecidable without reasoning about the wrapped Int#5eqPmAltCon (LitOverInt 1) (LitOverInt 1) == Just True2: We assume reflexivity for overloaded literals/eqPmAltCon (PatSyn PA) (PatSyn PA) == Just True/: We assume reflexivity for Pattern Synonyms Type of a Is a match on this constructor forcing the match variable? True of data constructors, literals and pattern synonyms (#17357), but not of newtypes. See Note [Coverage checking Newtype matches] in GHC.HsToCore.Pmc.Solver.Not user-facing.Syntactic equality.Syntactic equality.Not user-facing.Not user-facing.۳ڳܳݳ޳ֳ߳׳سٳԳճó³˳̳ͳϳγгѳҳӳijųdzʳȳɳƳó³ijųdzʳȳɳƳ˳̳ͳϳγгѳҳӳֳ׳سٳԳճڳݳ޳߳۳ܳ   ,                  None)Used as tree payload post-checking. The redundancy info we elaborated.;Used as tree payload pre-checking. The LYG guards to check.#Pattern-match coverage check result&A flag saying whether we ran into the maxPmCheckModels limit for the purpose of suggesting to crank it up in the warning message. Writer state.The set of uncovered values falling out at the bottom. (for -Wincomplete-patterns, but also important state for the algorithm),A hole for redundancy info and covered sets.Redundancy sets, used to determine redundancy of RHSs and bang patterns (later digested into a CIRB).If any of the Գ is empty, the corresponding  pin-points a bang pattern in source that is redundant. See Note [Dead bang patterns].The  Diverging set; empty if no match can lead to divergence. If it wasn't empty, we have to turn redundancy warnings into inaccessibility warnings for any subclauses.The Covered= set; the set of values reaching a particular program point.(A guard tree denoting a pattern binding.%A guard tree denoting an -XEmptyCase.A guard tree denoting GRHS&: A payload describing the grds and a / useful for printing out in warnings messages.A guard tree denoting GRHSs : A bunch of % guards for local bindings from the GRHSss where clauses and the actual list of GRHS=. See Note [Long-distance information for HsLocalBinds] in GHC.HsToCore.Pmc.Desugar.A guard tree denoting Match5: A payload describing the pats and a bunch of GRHS.A guard tree denoting  MatchGroup.A series-parallel graph of ?s, so very nearly a guard tree, if it weren't for or-patterns/! The implicit "source" corresponds to "before the match" and the implicit "sink" corresponds to "after a successful match". is a  that always matches. is a  that matches iff its  matches. g1 g2 corresponds to matching guards g1 and then g2 if matching g1, succeeded. Example: The Haskell guard | x > 1, x < 10 = ... will test x > 1 before x < 10, failing if either test fails. g1 g2 is far less common than 0 and corresponds to matching an or-pattern (LT; EQ)0, succeeding if the match variable matches either P or Q. See Note [Implementation of OrPatterns] for a larger example.Means by which we identify a source construct for later pretty-printing in a warning message.  for the equation to show,  for the location.A very simple language for pattern guards. Let bindings, bang patterns, and matching variables against flat constructor patterns. The LYG guard language.PmCon x K dicts args corresponds to a K dicts args <- x guard. The args" are bound in this construct, the x0 is just a use. For the arguments' meaning see .PmBang x corresponds to a  seq x True guard. If the extra  is present, the bang guard came from a source bang pattern, in which case we might want to report it as redundant. See Note [Dead bang patterns] in GHC.HsToCore.Pmc.Check. PmLet x expr corresponds to a  let x = expr guard. This actually binds x.Sequentially compose a list of  s into a .Sequentially compose a list of s.Sequentially compose a  in front of a .Sequentially compose two s. A smart constructor for  that eliminates s.´"Parallel composition of a list of s. Needs a non-empty list as ! does not have a neutral element.Format a LYG sequence (e.g. Matches of a  MatchGroup or GRHSs) as {  firstalt; ...;  lastalt }ĴShould not be user-facing.ŴFormat LYG guards as | True <- x, let x = 42, !z۳ڳܳݳ޳߳´ֳ׳سٳԳճó³˳̳ͳϳγгѳҳӳijųdzʳȳɳƳ>´ô Ĵ Ŵ ƴ /Ǵ 0ȴ 0ɴ 5ʴ  ˴ 2̴ ʹ "δ ϴ д 4ѴҴ ӴNoneThe result of .ԴPretty-print the guts of an uncovered value vector abstraction, i.e., its components and refutable shapes associated to any mentioned variables. Example for )([Just p, q], [p :-> [3,4], q :-> [0,5]]): (Just p) q where p is not one of {3, 4} q is not one of {0, 5} When the set of refutable shapes contains more than 3 elements, the additional elements are indicated by "...".5Output refutable shapes of a variable in the form of "var is not one of {2, Nothing, 3}. Will never print more than 3 refutable shapes, the tail is indicated by an ellipsis.Extract and assigns pretty names to constraint variables with refutable shapes.*Allocates a new, clean name for the given ! if it doesn't already have one.Pretty print a variable, but remember to prettify the names of the variables that refer to neg-literals. The ones that cannot be shown are printed as underscores.Extract a list of s out of a sequence of cons cells, optionally terminated by a wildcard variable instead of []. Some examples:pmExprAsList (1:2:[]) == Just ( [1,2]), a regular, [].-terminated list. Should be pretty-printed as [1,2].pmExprAsList (1:2:x) == Just ( [1,2] x), a list prefix ending in a wildcard variable x (of list type). Should be pretty-printed as (1:2:_). pmExprAsList [] == Just ( [])ԴԴNone 3&j"`where'3 clause at the same depth as implicit layout block""`|'- at the same depth as implicit layout block")Errors from the Cmm parserUnknown Cmm primitive Unknown macroUnknown calling conventionUnrecognised safetyUnrecognised hint Lexical errorUnknown pragmaLexical error in pragma$Numeric escape sequence out of rangeUnterminated `{-'Unterminated OPTIONS pragmaUnterminated quasiquotation End of inputUTF-8 decoding errorError at given characterNegative application pattern?*The list of type arguments for the patternExtra information for the expression GHC is currently inspecting/parsing. It can be used to generate more informative parser diagnostics and hints.9Did the parser likely fail due to an incomplete do block?If L8, this is an infix pattern with the bound operator name Is the parsed pattern recursive?Extra details about a parse error, which helps us in determining which should be the hints to suggest.!Did we parse a "pattern" keyword?Is PatternSynonyms enabled? Is there an mdo in the last 100 characters? Is there a 'do' in the last 100 characters?An "unknown" message from the parser. This type constructor allows arbitrary messages to be embedded. The typical use case would be GHC plugins willing to emit custom diagnostics.&A group of parser messages emitted in 5. See Note [Messages from GHC.Parser.Header].PsWarnBidirectionalFormatChars is a warning (controlled by the -Wwarn-bidirectional-format-characters flag) that occurs when unicode bi-directional format characters are found within in a fileThe  contains the exact position in the buffer the character occurred, and the string contains a description of the character.PsWarnTab is a warning (controlled by the -Wwarn-tabs flag) that occurs when tabulations (tabs) are found within a file.Test case(s): parser should_fail"T12610 parsershould_compile"T9723b parsershould_compile"T9723a parsershould_compile#read043 parser should_fail$T16270 warningsshould_compileT9230PsWarnTransitionalLayout is a warning (controlled by the -Walternative-layout-rule-transitional flag) that occurs when pipes ('|' ) or 'where'3 are at the same depth of an implicit layout block. Example(s):f :: IO () f | True = do let x = () y = () return () | True = return ()Test case(s): layout/layout006 layout/layout003 layout/layout001Unrecognised pragma. First field is the actual pragma name which might be empty. Second field is the set of valid candidate pragmas. Invalid Haddock comment position,Multiple Haddock comment for the same entity;Found binding occurrence of "*" while StarIsType is enabledUsing "*" for Type without StarIsType enabledPre qualified import with WarnPrepositiveQualifiedModule enabledPsWarnViewPatternSignatures is a warning triggered by view patterns whose RHS is an unparenthesised pattern signature. It warns on code that is highly likely to break when the precedence of view patterns relative to pattern signatures is changed per GHC Proposal #281. The suggested fix is to add parentheses.3Example: f1 (isJust -> True :: Bool) = ();Suggested fix: f1 (isJust -> (True :: Bool)) = ()$Test cases: T24159_viewpat4LambdaCase syntax used without the extension enabled(A lambda requires at least one parameter5Underscores in literals without the extension enabled%Invalid character in primitive string Missing block Lexer errorSuffix occurrence of @ Parse errorsCmm lexer error#Unsupported boxed sum in expression Unsupported boxed sum in pattern Unexpected qualified constructor Tuple section in pattern context*Bang-pattern without BangPattterns enabled%Operator applied to too few arguments Import: multiple occurrences of  qualifiedPost qualified import without ImportQualifiedPost#Explicit namespace keyword without ExplicitNamespaces1Expecting a type constructor but found a variable.Illegal export form allowed by PatternSynonymsMalformed entity stringDots used in record updatePrecedence out of range!Invalid use of record dot syntax .OverloadedRecordUpdate is not enabled.Can't use qualified fields when OverloadedRecordUpdate is enabled.;Cannot parse data constructor in a data/newtype declaration;Cannot parse data constructor in a data/newtype declarationIllegal DataKinds quote mark in data/newtype constructor declaration$UNPACK applied to a data constructor7Unexpected kind application in data/newtype declarationNot a record constructor)Illegal unboxed string literal in pattern3Illegal primitive floating point literal in patternDo-notation in patternIf-then-else syntax in pattern Lambda or Lambda-case in patterncase..of in patternlet-syntax in pattern"Arrow expression-syntax in patternArrow command-syntax in pattern"Arrow command-syntax in expressionOr-pattern in expression&Type-application without space before @Lazy-pattern (~) without space after itBang-pattern (!) without space after it#Pragma not allowed in this positionQualified do block in command.Invalid infix hole, expected an infix operator0Unexpected semi-colons in conditional expression-Unexpected semi-colons in conditional command @-operator in a pattern position/Unexpected case command in function application stuff)߄-what kind of {-# SCC #-} to add automatically8GHCi scripts specified by -ghci-script, in reverse orderUnfolding control See Note [Discounts and thresholds] in GHC.Core.UnfoldSafe Haskell modeFilepath to the package environment file (if overriding default)The -trust and  -distrust flags. In *reverse* order that they're specified on the command line.The -plugin-package-id flags from command line. In *reverse* order that they're specified on the command line.The -package and  -hide-package flags from the command-line. In *reverse* order that they're specified on the command line.The -ignore-package flags from the command line. In *reverse* order that they're specified on the command line.The  -package-db flags given on the command line, In *reverse* order that they're specified on the command line. This is intended to be applied with the list of "initial" package databases derived from GHC_PACKAGE_PATH; see  getUnitDbRefs.-External plugins loaded from shared librariesthe -ffrontend-opt flags given on the command line, in *reverse* order that they're specified on the command line.the -fplugin flags given on the command line, in *reverse* order that they're specified on the command line.Path to store the .mix files Override the  set by   or 'ghc.GHCi.UI.runStmt' . Set by -ddump-file-prefix1This defaults to 'non-module'. It can be set by   or 'ghc.GHCi.UI.runStmt'% based on where its output is going.Indicate if we are now generating dynamic output because of -dynamic-too. This predicate is used to query the appropriate fields (outputFile/dynOutputFile, ways, etc.)&Target way flags from the command line8What the package is called, use with multiple home unitsModule instantiationsId of the unit to instantiateTarget home unit-idNumber of layers of superclass expansion for quantified constraints Should be < givensFuel See Note [Expanding Recursive Superclasses and ExpansionFuel]Number of layers of superclass expansion for wanteds Should be < givensFuel See Note [Expanding Recursive Superclasses and ExpansionFuel]Number of layers of superclass expansion for givens Should be < solverIterations See Note [Expanding Recursive Superclasses and ExpansionFuel]Number of iterations in the constraints solver Typically only 1 is neededTypechecker maximum stack depth…Simplification history sizeÅ4Align Cmm functions at this boundary or use default.ąLambda lift even when this turns a known call into an unknown call.ŅMaximum number of arguments after lambda lifting a non-recursive function.ƅMaximum number of arguments after lambda lifting a recursive function.Dž%Arg count for lambda floating See  ȅThreshold for LiberateCaseɅBinary literals (e.g. strings) whose size is above this threshold will be dumped in a binary file by the assembler code generator. 0 and Nothing disables this feature. See  .ʅMax number of specialisations for recursive types Not optional; otherwise ForceSpecConstr can diverge.˅2Max number of specialisations for any one function̅Threshold for SpecConstr΅Whether DmdAnal should optimistically put an Unboxed demand on returned products with at most this number of fieldsυMultiplier for simplifier ticksЅSoft limit on the number of models the pattern match checker checks a pattern against. A safe guard against exponential blow-up.хMaximum number of unmatched patterns to show in non-exhaustiveness warnings҅Maximum level of refinement for refinement hole fits in typed hole error messagesӅMaximum number of refinement hole fits to show in typed hole error messagesԅMaximum number of hole fits to show in typed hole error messagesՅMaximum number of bindings from the type envt to show in type error messagesօThe heap size to set.ׅEnable RTS timing statistics?؅The number of modules to compile in parallel If unspecified, compile with a single job.مAdditional demand analysisۅMax simplifier iterations܅Number of simplifier phases݅%How much debug information to produceޅ,Verbosity level: see Note [Verbosity levels]߅LLVM optimisation levelThe backend to use (if any).7Whenever you change the backend, also make sure to set  to something sensible. NoBackend can be used to avoid generating any output, however, note that:If a program uses Template Haskell the typechecker may need to run code from an imported module. To facilitate this, code generation is enabled for modules imported by modules that use template haskell, using the default backend for the platform. See Note [-fno-code mode].Used by   to partially initialize a new ʄ value The normal ʄ. Note that they are not suitable for use in this form and must be fully initialized by   first.Are we building with -fPIE or -fPIC enabled?Append to the list of includes a path that shall be included using `-I` when the C compiler is called. These paths override system search paths.Append to the list of includes a path that shall be included using `-iquote` when the C compiler is called. These paths only apply when quoted includes are used. e.g. #include "foo.h"These includes are not considered while fingerprinting the flags for iface | See Note [Implicit include paths]Concatenate and flatten the list of global and quoted includes returning just a flat list of paths.Test whether a   is setSet a  Unset a  Test whether a  is set Note that  (i.e., dynamic objects built with `-dynamic-too`) always implicitly enables Opt_PIC, Opt_ExternalDynamicRefs, and disables Opt_SplitSections.Set a Unset a Test whether a  is setSet a Unset a Test whether a  is set as fatalMark a  as fatal (do not set the flag)Mark a  as not fatal%Enable all custom warning categories.&Disable all custom warning categories.Mark all custom warning categories as fatal (do not set the flags).0Mark all custom warning categories as non-fatal. Set a custom 8Unset a custom 8Mark a custom 8 as fatal (do not set the flag)Mark a custom 8 as not fatal0Are there any custom warning categories enabled?Test whether a    is setSet a   Unset a   Set or unset a   7, unless it has been explicitly set or unset before.These are the default settings for the display and sorting of valid hole fits in typed-hole error messages. See Note [Valid hole fits include ...] in the GHC.Tc.Errors.Hole module.The language extensions implied by the various language variants. When updating this be sure to update the flag documentation in docs users_guideexts.Get target profileThe directory for this version of ghc in the user's app directory The appdir used to be in ~/.ghc but to respect the XDG specification we want to move it under $XDG_DATA_HOME/ However, old tooling (like cabal) might still write package environments to the old directory, so we prefer that if a subdirectory of ~/.ghc with the correct target and GHC version suffix exists. i.e. if ~.ghc$UNIQUE_SUBDIR exists we use that otherwise we use $XDG_DATA_HOME/$UNIQUE_SUBDIRUNIQUE_SUBDIR is typically a combination of the target platform and GHC version&Initialize the pretty-printing optionsInitialize the pretty-printing options using the default user style!!!ƄDŽʄ˄ڄل؄ׄքՄɅۄބ̄Å݅΅ׅDžԄօ…ͅ΄݄ȅąŅƅ߅τӄ҄фЅӅՅۅхԅ؅߄҅Єڅ܅υ˅ʅ̅܄م̈́ޅńÄĄȄɄ„ !!!!!!!!!!! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                                   !!!!!!ҁ !!!!!!!!!!! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                                   ҁҁ!!!!!ńÄĄ„ʄ˄ڄل؄ׄքՄɅۄބ̄Å݅΅ׅDžԄօ…ͅ΄݄ȅąŅƅ߅τӄ҄фЅӅՅۅхԅ؅߄҅Єڅ܅υ˅ʅ̅܄م̈́ޅȄɄƄDŽ!!!!  .            %  ?  <  ?         † Æ Ć  ņ  Ɔ  dž  Ȇ  Ɇ ʆ  ˆ ̆  ͆ Ά  φ  І None<цSubstitution on module variables, mapping module names to module identifiers.ن!The result of performing a lookupچ-Found the module uniquely, nothing else to doۆ,Multiple modules with the same name in scope܆No modules found, but there were some hidden ones with an exact name match. First is due to package hidden, second is due to module being hidden݆No modules found, but there were some unusable ones with an exact name matchކ6Nothing found, here are some suggested different namesFor each unit, a mapping from uid -> i indicates that this unit was brought into GHC by the ith  -package-db flag on the command line. We use this mapping to make sure we prefer units that were defined later on the command line, if there is an ambiguity.'A reverse dependency index, mapping an  to the  s which have a dependency on it.߆"The reason why a unit is unusable.We ignored it explicitly using -ignore-package.This unit transitively depends on a unit that was never present in any of the provided databases.This unit transitively depends on a unit involved in a cycle. Note that the list of  reports the direct dependencies of this unit that (transitively) depended on the cycle, and not the actual cycle itself (which we report separately at high verbosity.);This unit transitively depends on a unit which was ignored.This unit transitively depends on a unit which was shadowed by an ABI-incompatible unit. Unit database0Indicate if we can instantiate units on-the-fly.This should only be true when we are type-checking an indefinite unit. See Note [About units] in GHC.Unit.A map saying, for each requirement, what interfaces must be merged together when we use them. For example, if our dependencies are p[A=] and q[A=,B=r[C=]:B]*, then the interfaces to merge for A are  p[A=]:A, q[A=,B=r[C=]:B]:A and  r[C=]:C.?There's an entry in this map for each hole in our home library. A map, like $, but controlling plugin visibility.This is a full map from  to all modules which may possibly be providing it. These providers may be hidden (but we'll still want to report them in error messages), or it may be an ambiguous import.Units which we explicitly depend on (from a command line flag). We'll use this to generate version macros and the unused packages warning. The original flag which was used to bring the unit into scope is recorded for the -Wunused-packages warning.The units we're going to link in eagerly. This list should be in reverse dependency order; that is, a unit is always mentioned before the units it depends on.A mapping from wired in unit ids to unit keys from the database.7A mapping from database unit keys to wired in unit ids. A mapping of J to . If several units have the same package name (e.g. different instantiations), then we return one of them... This is used when users refer to packages in Backpack includes. And also to resolve package qualifiers with the PackageImports extension.The set of transitively reachable units according to the explicitly provided command line arguments. A fully instantiated VirtUnit may only be replaced by a RealUnit from this set. See Note [VirtUnit to RealUnit improvement] A mapping of  to J>. This list is adjusted so that only valid units are here. J5 reflects what was stored *on disk*, except for the trusted flag, which is adjusted at runtime. (In particular, some units in this map may have the exposed flag be J.) Map from & to a set of module providers (i.e. a  and its ).NB: the set is in fact a 'Map Module ModuleOrigin', probably to keep only one origin for a given Unit configurationPlugins exposed units Trusted units Ignored units Exposed unitsUnit databases flagsCache of databases to use, in the order they were specified on the command line (later databases shadow earlier ones). If Nothing, databases will be found using .!Hide all plugins units by defaultHide all units by defaultDistrust all units by default,Units to link automatically (e.g. base, rts)$User DB name (e.g. "package.conf.d")%Main GHC dir: contains settings, etc.Path to global DBName of the compiler (e.g. GHC, GHCJS). Used to fetch environment variables such as "GHC[JS]_PACKAGE_PATH".Allow virtual units ^ Do we allow the use of virtual units instantiated on-the-fly (see Note [About units] in GHC.Unit). This should only be true when we are type-checking an indefinite unit (not producing any code). Ways to usePlatform arch and OS< records the various aspects of visibility of a particular .Whether or not this unit was explicitly brought into scope, as opposed to implicitly via the exposed' fields in the package database (when -hide-all-packages is not passed.)The signatures which are contributed to the requirements context from this unit ID.%The package name associated with the 4. This is used to implement legacy behavior where -package foo-0.1& implicitly hides any packages named foo-Any custom renamings that should bring extra s into scope. map from  to a .A unusable unit module originIs the "module" a reexport?Reason Unusable unitGiven a module name, there may be multiple ways it came into scope, possibly simultaneously. This data type tracks all the possible ways it could have come into scope. Warning: don't use the record functions, they're partial!Module is hidden, and thus never will be available for import. (But maybe the user didn't realize), so we'll still keep track of these modules.)3Module is unavailable because the unit is unusable.7Module is public, and could have come from some places.Did the module export come from a package flag? (ToDo: track more information.]:B maps to  p[A=q():A]:B with A=q():A; similarly,  maps to q():A.Substitutes holes in a , suitable for renaming when an include occurs; see Note [Representation of module/name variables].p[A=] maps to p[A=] with A=.Like , but requires only ClosureUnitInfoMap so it can be used by GHC.Unit.State.(Like 'renameHoleUnit, but requires only ClosureUnitInfoMap so it can be used by GHC.Unit.State. Injects an " to  (see also .9Print unit-ids with UnitInfo found in the given UnitState Home unit idHome unit instance ofHome unit instantiationsJJJJJJJJJJJJJJJJJJJJJنچ܆ۆކ݆ֆ؆׆ц҆ӆԆՆ߆""҆ӆԆՆنچ܆ۆކ݆ֆ؆׆߆ц     "  #  5 '       !  None& summarises what was imported from where, irrespective of whether the imported things are actually used or not. It is used: when processing the export list,4when constructing usage info for the interface file,to identify the list of directly imported modules for initialisation purposes and for optimised overlap checking of family instances,/when figuring out what things are really unusedFamily instance modules below us in the import tree (and maybe including us for imported modules)Orphan modules below us in the import tree (and maybe including us for imported modules) Signature modules below this oneDomain is all modules which have hs-boot files, and whether we should import the boot version of interface file. Only used in one-shot mode to populate eps_is_boot.This records the packages the current module needs to trust for Safe Haskell compilation to succeed. A package is required to be trusted if we are dependent on a trustworthy module in that package. See Note [Tracking Trust Transitively] in GHC.Rename.NamesDo we require that our own package is trusted? This is to handle efficiently the case where a Safe module imports a Trustworthy module that resides in the same package as it. See Note [Trust Own Package] in GHC.Rename.Names5Packages directly needed by the module being compiledHome-package modules directly imported by the module being compiled.‡'Domain is all directly-imported modules-See the documentation on ImportedModsVal in GHC.Unit.Module.Imported for the meaning of the fields.We need a full ModuleEnv rather than a ModuleNameEnv here, because we might be importing modules of the same name from different packages. (currently not the case, but might be in the future).ÇRecords modules for which changes may force recompilation of this module See wiki: https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/recompilation-avoidanceThis differs from Dependencies. A module X may be in the dep_mods of this module (via an import chain) but if we don't use anything from X it won't appear in our UsagećModule from another packageŇModule from the current packageƇA file upon which the module depends, e.g. a CPP #include, or using TH's addDependentFileȇ-A requirement which was merged into this one.ɇ)Was this module imported as a safe importʇ:Cached module ABI fingerprint (corresponds to mi_mod_hash)ˇ#External package module depended oṅFingerprint for the export list of this module, if we directly imported it (and hence we depend on its export list)͇Entities we depend on, sorted by occurrence name and fingerprinted. NB: usages are for parent names only, e.g. type constructors but not the associated data constructors.·)UnitId of the HomeUnit the module is fromχName of the moduleЇAn optional string which is used in recompilation messages if file in question has changed.ч of the file contents.҇External file dependency. From a CPP #include or TH addDependentFile. Should be absolute.ӇThe *interface* hash of the module, not the ABI hash. This changes when anything about the interface (and hence the module) has changed.ԇDependency information about ALL modules and packages below this one in the import hierarchy. This is the serialisable version of .(Invariant: the dependencies of a module M never includes M.0Invariant: none of the lists contain duplicates.Invariant: lists are ordered canonically (e.g. using stableModuleCmp)1See Note [Transitive Information in Dependencies]ՇTransitive closure of depended upon modules which contain family instances (whether home or external). This is used by checkFamInstConsistency%. This does NOT include us, unlike 9. See Note [The type family instance consistency story].ևTransitive closure of orphan modules (whether home or external pkg).(Possible optimization: don't include family instance orphans as they are anyway included in Շ. But then be careful about code which relies on dep_orphs having the complete list!) This does NOT include us, unlike .ׇAll modules which have boot files below this one, and whether we should use the boot file or not. This information is only used to populate the eps_is_boot field. See Note [Structure of dep_boot_mods]ه4Transitive closure of hsig files in the home packageڇAll units needed for pluginsۇAll packages directly imported by this module I.e. packages to which this module's direct imports belong. Does not include other home units when using multiple home units. Modules from these units will go in ܇܇All home-package modules which are directly imported by this one. This may include modules from other units when using multiple home units݇Extract information from the rename and typecheck phases to produce a dependencies information for the module being compiled.0The fourth argument is a list of plugin modules.އUpdate module dependencies containing orphans (used by Backpack)߇Update module dependencies containing family instances (used by Backpack)Pretty-print unit dependencies*߇އ݇ԇׇ܇ۇՇևڇه؇‡ÇƇŇLJȇć͇̇чЇ҇Ӈˇʇχɇ·*ԇ݇܇ۇه؇ևڇՇׇއ߇ÇƇŇLJȇć͇̇чЇ҇Ӈˇʇχɇ·‡       None%%$$$$$$$$$$$$$$%%$$%%$JJJJJJJJJJJJJ$$$$$$$$$$#$$##$#$$$##$$######$$#$$$##$$####$$$#####$#$$##$$#$########%%%%##"####"###""""""""#"""####""####"##"##$$$$JJJJJJJJ$$$$####################نچ܆ۆކ݆ֆ؆׆ц҆ӆԆՆ߆""""""""""""""""""""""""""""""""""""None"A module name: search for the fileA filename: preprocess & parse it to find the module name. If specified, the Phase indicates how to compile this file (which phase to start from). Nothing indicates the starting phase should be determined from the suffix of the filename.A compilation target.A target may be supplied with the actual text of the module. If so, use this instead of the file contents (this is for use in an IDE where the file hasn't been saved by the user yet).7These fields are strict because Targets are long lived.Optional in-memory buffer containing the source code GHC should use for this target instead of reading it from disk.Since GHC version 8.10 modules which require preprocessors such as Literate Haskell or CPP to run are also supported.If a corresponding source file does not exist on disk this will result in a  SourceError exception if targetId = TargetModule _! is used. However together with targetId = TargetFile _/ GHC will not complain about the file missing.%id of the unit this target is part ofobject code allowed?module or filename    = = 4 4None Reasons why we need ticks, For profilingFor Haskell Program Coverage%For ByteCode interpreter break pointsFor source notesŠWhether the number of times functions are entered should be counted.ÊWhere to insert ticksĊfor HpcŊfor GHCiƊfor -prof-auto-allNJfor -prof-auto-topȊfor -prof-auto-exportedɊfor stack tracingLabel for the tick counterIdentifiers being boundPath to the declarationTick source spanConfiguration for compilation pass to add tick for instrumentation to binding sites.)Whether to count the entries to functionsRequires extra synchronization which can vastly degrade performance.-What kind of {-# SCC #-} to add automatically"What purposes do we need ticks forʊ1Decide whether to add a tick to a binding or not.Strip CoreTicks from an HsExprˊA let body is treated differently from addTickLHsExprEvalInner above with TickForBreakPoints, because for breakpoints we always want to tick the body, even if it is not a redex. See test break012. This gives the user the opportunity to inspect the values of the let-bound variables.̊Tickishs that only make sense when their source code location refers to the current file. This might not always be true due to LINE pragmas in the code - which would confuse at least HPC.͊:Get the next HPC cost centre index for a given centre namelocation of the current moduleExported Ids. When we call addTicksToBinds, isExportedId doesn't work yet (the desugarer hasn't set it), so we have to work from this set. Type constructors in this moduleʊ top level? exported?simple pat bind?INLINE pragma?         None+ Pass to a  DriverMessage the information whether or not the '-fbuilding-cabal-package' flag is set.Whether to show files we tried to look for or not when printing loader errors((  8 8    NoneData for a module node in a  ModuleGraph/. Module nodes of the module graph are one of:A regular Haskell source moduleA hi-boot source module-The actual preprocessed source, if we have itCached flags from OPTIONS, INCLUDE and LANGUAGE$ pragmas in the modules source code$Filename of preprocessed source fileThe parsed, nonrenamed source, if we have it. This is also used to support "inline module syntax" in Backpack files.;Whether the special module GHC.Prim was imported explicitly7Non-source imports of the module from the module *text*Source imports of the module%Timestamp of hie file, if we have oneTimestamp of hi file, if we have one See Note [When source is considered modified] and #9243+Timestamp of dynamic object, if we have one#Timestamp of object, if we have oneContent hash of source file5Location of the various files belonging to the module8The module source either plain Haskell, hs-boot, or hsigIdentity of the module Int conv x = fromIntegral x Here calling conv is essentially the identity function, and therefore can be omitted.Test case(s): deSugarshould_compileT4488DsIncompleteRecordSelector is a warning triggered when we are not certain whether a record selector application will be successful. Currently, this means that the warning is triggered when there is a record selector of a data type that does not have that field in all its constructors.Example(s): data T = T1 | T2 {x :: Bool} f :: T -> Bool f a = x aTest cases: DsIncompleteRecSel1 DsIncompleteRecSel2 DsIncompleteRecSel3The list of unbound bindersThe original bindersThe original LHSThe optimised LHS  Noneu3Show a SDoc as a String with the default user style.Allows caller to specify the NamePprCtx to useNoneNone.!Initialize LogFlags from DynFlagsNone.!Initialize RuleOpts from DynFlagsNoneNone NonebϊLike +, but doesn't catch asynchronous exceptionsAtomically update the reference. Does not force the evaluation of the new variable contents. For strict update, use .Strict variant of .2Perform a computation with a different environment1Perform a computation with an altered environment94"w v!2    !  5  5 3 9         # %. 08NonerSame as r# but simplifies the unfolding firstr0Used for things that absolutely must be unfoldedrMake an INLINE unfolding that may be used unsaturated (ug_unsat_ok = unSaturatedOk) and that is reported as having its manifest arity (the number of outer lambdas applications will resolve before doing any work).rMake an INLINE unfolding that will be used once the RHS has been saturated to the given arity.rSees if the unfolding is pretty certain to inline. If so, return a *stable* unfolding for it, that will always inline. The CoreExpr is the WW'd and simplified RHS. In contrast, the unfolding template might not have been WW'd yet.`rrrrrrrrrrrrrrrr`rrrrrrrrrrrrrrrrNone* `Simple optimiser optionsЊFast OutVarSet tracking which recursive RHSs we are analysing. See Note [Eta reduction in recursive RHSs]ъ+Deals with cloning; includes the InScopeSetҊDeals with preInlineUnconditionally; things that occur exactly once and are inlined without having first been simplifiedӊSimplifier optionsrEta reduction on?rCoercion optimiser optionsrUnfolding optionsr)Default options for the Simple optimiser.rReturns Just (bndr,rhs) if the binding is a join point: If it's a JoinId, just return it If it's not yet a JoinId but is always tail-called, make it into a JoinId and return it. In the latter case, eta-expand the RHS if necessary, to make the lambdas explicit, as is required for join pointsPrecondition: the InBndr has been occurrence-analysed, so its OccInfo is validrReturns 'Just ([b1..bp], dc, [t1..tk], [x1..xn]) if the argument expression is a *saturated* constructor application of the form *let b1 in .. let bp in dc t1..tk x1 .. xn>, where t1..tk are the *universally-quantified* type args of dc. Floats can also be (and most likely are) single-alternative case expressions. Why does r return floats? We may have to look through lets and cases to detect that we are in the presence of a data constructor wrapper. In this case, we need to return the lets and cases that we traversed. See Note [exprIsConApp_maybe on data constructors with wrappers]. Data constructor wrappers are unfolded late, but we really want to trigger case-of-known-constructor as early as possible. See also Note [Activation for data constructor wrappers] in GHC.Types.Id.Make.We also return the incoming InScopeSet, augmented with the binders from any [FloatBind] that we returnrrsrrr`rr`rrrr`rrrrrr`rrrrrss  !None3h KData Constructor BoxerUnbox small strict fieldsUnbox strict fields?Disable automatic field unboxing (e.g. if we aren't optimising)Strict fields by defaultUsed for imported data constructors See Note [Bangs on imported data constructors]ԊConjure a fresh local binder.Պ/Unpack/Strictness decisions from source module.This function should only ever be invoked for data constructor fields, and never on the field of a newtype constructor. See Note [HsImplBangs for newtypes].֊Wrappers+Workers and representation following UnpackStrictness decisions׊Every alternative of an unboxed sum has exactly one field, and we use unboxed tuples when we need more than one field. This generates an unboxed tuple when necessary, to be used in unboxed sum alts.Directly specify which outer forall'd type variables of a representation-polymorphic 7 such become concrete metavariables when instantiated.Ԋ%a string which will form part of the 's namethe type of the ((ty, pos), tv) ty is the type on which the representation-polymorphism check is done tv is the type variable we are checking for concreteness (usually the kind of ty) pos is the position of ty in the type of the  of the rep-poly ,CKKK,KKKCNoneNoneNone9Initialise coercion optimiser configuration from DynFlags7Initialise Simple optimiser configuration from DynFlags+Extract GHCi options from DynFlags and stepNone)!؊8What part (2) of Note [Worker/wrapper for CPR] collects. A ي2 capturing whether the split does anything useful.-The list of transit variables (see the Note).The result builder expression for the wrapper. The original case binder if not useful.0The result unpacking expression for the worker. ڊ if not useful. Returned by 9. See also Note [Detecting recursive data constructors].The algorithm detected a loopThe algorithm detected no loop, went out of fuel or hit an .hs-boot fileي'Is the worker/wrapper split profitable?Describes the outer shape of an argument to be unboxed or left as-is Depending on how s is instantiated (e.g., ] or ^)./We ran out of strictness info. Leave untouched.The argument is used strictly or the returned product was constructed, so unbox it.'The argument/field was absent. Drop it.The information needed to build a pattern for a DataCon to be unboxed. The pattern can be generated from  and  via  . The coercion  is for newtype wrappers. If we get DataConPatContext dc tys co for some type ty and *dataConRepInstPat ... dc tys = (exs, flds), thendc exs flds :: T tys@ co :: T tys ~ tys will be ] or ^.Generate workers even if the only effect is some args get passed unlifted. See Note [WW for calling convention]&Used for absent argument error messageWhether to enable "Constructed Product Result" analysis. (Originally from DOI: 10.1017/S0956796803004751)"Options for the "Simple optimiser")Environment of type/data family instancesGiven a function definition data T = MkT Int Bool Char f :: (a, b) -> Int -> T f = \x y -> E mkWwBodies _ f7 ['x::(a,b)','y::Int'] '(a,b)' ['1P(L,L)', '1P(L)'] '1' returnsThe wrapper body context for the call to the worker function, lacking only the  for the worker function: W[_] :: Id -> CoreExpr W[work_fn] = \x y -> -- args of the wrapper (cloned_arg_vars) case x of (a, b) -> -- unbox wrapper args (wrap_fn_str) case y of I# n -> -- case a b n of -- call to the worker fun (call_work) (# i, b, c #) -> MkT i b c -- rebox result (wrap_fn_cpr)The worker body context that wraps around its hole reboxing defns for x and y, as well as returning CPR transit variables of the unboxed MkT result in an unboxed tuple: w[_] :: CoreExpr -> CoreExpr w[fn_rhs] = \a b n -> -- args of the worker (work_lam_args) let { y = I# n; x = (a, b) } in -- reboxing wrapper args (work_fn_str) case x y of -- call to the original RHS (call_rhs) MkT i b c -> (# i, b, c #) -- return CPR transit vars (work_fn_cpr)NB: The wrap_rhs hole is to be filled with the original wrapper RHS x y -> E". This is so that we can also use w to transform stable unfoldings, the lambda args of which may be different than x and y.Id details for the worker function like demands on arguments and its join arity.All without looking at E (except for beta reduction, see Note [Join points and beta-redexes]), which allows us to apply the same split to function body and its unfolding(s) alike.ۊ Version of A  that does beta reduction on-the-fly. PRECONDITION: The arg expressions are not free in any of the lambdas binders.'Whether the worker needs an additional `Void#` arg as per Note [Protecting the last value argument] or Note [Preserving float barriers].܊ Inserts a `Void#` arg as the last argument. Why last? See Note [Worker/wrapper needs to add void arg last]݊0Do we want to create workers just for unlifting?WW split not profitableWW split profitable Unwraps the   decision encoded in the given ] and returns a - as well the nested demands on fields of the ( to unbox.ފ*Unboxing strategy for constructed results.Tries to find a suitable absent filler to bind the given absent identifier to. See Note [Absent fillers].If mkAbsentFiller _ id == Just e, then e, is an absent filler with the same type as id/. Otherwise, no suitable filler could be found.Exactly \3, but lacks the (ASSERT'ed) precondition that the ( may not have existentials. The lack of cloning the existentials this function "dubious"; only use it where type variables aren't substituted for! Why may the data con bind existentials? See Note [Which types are unboxed?]isRecDataCon _ fuel dc, where tc = dataConTyCon dc returnsDefinitelyRecursive if the analysis found that tc" is reachable through one of dc's arg_tys.NonRecursiveOrUnsure if the analysis found that tc& is not reachable through one of dc$'s fields (so surely non-recursive).NonRecursiveOrUnsure when fuel /= Infinity and fuel expansions of nested data TyCons were not enough to prove non-recursiveness, nor arrive at an occurrence of tc thus proving recursiveness. (So not sure if non-recursive.)NonRecursiveOrUnsure when we hit an abstract TyCon (one without visible DataCons), such as those imported from .hs-boot files. Similarly for stuck type and data families.If fuel = Infinity and there are no boot files involved, then the result is never Nothing. and the analysis is a depth-first search. If fuel = > f, then the analysis behaves like a depth-limited DFS and returns Nothing! if the search was inconclusive.See Note [Detecting recursive data constructors] for which recursive DataCons we want to flag.ߊEntrypoint to CPR WW. See Note [Worker!wrapper for CPR] for an overview.*Part (1) of Note [Worker/wrapper for CPR].3See if we want to unbox the result and hand off to .Implements the main bits of part (2) of Note [Worker/wrapper for CPR]5Implements part (3) of Note [Worker/wrapper for CPR].8If `move_transit_vars [a,b] = (unbox, tup)` then * a and b are the *transit vars* to be returned from the worker to the wrapper * `unbox scrut alt = (case  scrut of (# a, b #) ->  alt)` * `tup = (# a, b #)` There is a special case for when there's 1 transit var, see Note [No unboxed tuple for single, unlifted transit var].The multiplicity of a case binder unboxing a constructed result. See Note [Linear types and CPR]The original functionWorker/wrapper arity"Manifest args of original functionResult type of the original function, after being stripped of argsStrictness of original functionInfo about function resultType of the argumentHow the arg was used!!  9 '   None HAn environment storing ^$s for local Ids. Puts binders with ^ in a space-saving IntSet+. See Note [Efficient Top sigs in SigEnv].#Ids that have something other than ^.All these Ids have ^ . Like a VarSet, but more efficient.Memoised result of  Needed when expanding type families and synonyms of product types.True only on every first iteration in a fixed-point iteration. See Note [Initialising strictness] in GHC.Core.Opt.DmdAnal1Current approximation of signatures for local idsThe abstract semantic function O_O : Expr -> Env -> A from "Constructed Product Result Analysis for Haskell"The abstract semantic function O_O : Expr -> Env -> A from "Constructed Product Result Analysis for Haskell"5Precise, hand-written CPR transformers for select IdsGet a (possibly nested) ^ for an application of a (& worker, given a saturated number of ^s for its field expressions. Implements the Nested part of Note [Nested CPR].$See Note [Trimming to mAX_CPR_SIZE].Process the RHS of the binding for a sensible arity, add the CPR signature to the Id, and augment the environment with the signature as well.Returns an expandable unfolding (See Note [exprIsExpandable] in GHC.Core.Utils8) that has So effectively is a constructor application.2Extend an environment with the (Id, CPR sig) pairs;Extend an environment with the CPR sigs attached to the ids7Extend an environment with the same CPR sig for all ids A version of  for a binder of which we don't see the RHS needed to compute a ^ (e.g. lambdas and DataAlt field binders). In this case, we can still look at their demand to attach CPR signatures anticipating the unboxing done by worker/wrapper. See Note [CPR for binders that will be unboxed]. Produces a ^? according to how a strict argument will be unboxed. Examples:A head-strict demand 1!L would translate to 1A product demand  1!P(1!L,L) would translate to 1(1,)A product demand  1!P(1L,L) would translate to 1(,)3, because the first field will not be unboxed.expression to be denoted by a ^the updated expression and its ^expression to be denoted by a ^the updated expression and its ^CPR type of the scrutineecurrent alternativeThe analysis environment The functioninfo about incoming value arguments"The demand type of the applicationմմִ  ״  NoneSee Note [Thunk splitting].splitThunk converts the *non-recursive* binding x = e into x = let x' = e in case x' of I# y -> let x' = I# y in x' See comments above. Is it not beautifully short? Moreover, it works just as well when there are several binders, and if the binders are lifted E.g. x = e --> x = let x' = e in case x' of (a,b) -> let x' = (a,b) in x' Here, x' is a localised version of x, in case x is a top-level Id with an External Name, because Lint rejects local binders with External Names; see Note [About the NameSorts] in GHC.Types.Name.How can we do thunk-splitting on a top-level binder? See Note [Thunk splitting for top-level binders].NoneNone%Memoised result of  True on first iteration only. See Note [Initialising strictness]Analysis options:An environment in which all demands are weak according to ]2. See Note [Lazy and unleashable free variables].Options for the demand analysisValue of `-fmax-worker-args`. Don't unbox anything if we end up with more than this many args.Value of `-fdmd-unbox-width`. See Note [Unboxed demand on function bodies returning small products]Governs whether the analysis should update boxity signatures. See Note [Don't change boxity without worker/wrapper].Value of `-fdicts-strict` (on by default). When set, all functons are implicitly strict in dictionary args.Outputs a new copy of the Core program in which binders have been annotated with demand and strictness information. Note: use seqBinds on the result to avoid leaks due to laziness (cf Note [Stamp out space leaks in demand analysis])We attach useful (e.g. not ]) c3 to top-level bindings that satisfy this function.Basically, we want to know how top-level *functions* are *used* (e.g. called). The information will always be lazy. Any other top-level bindings are boring.;See also Note [Why care for top-level demand annotations?].Analyse a binding group and its "body", e.g. where it is in scope.It calls a function that knows how to analyse this "body" given an  with updated demand signatures for the binding group (reflecting their  idDmdSigInfo) and expects to receive a ] in return, which it uses to annotate the binding group with their c.-Annotates uninteresting top level functions () with ]!, the rest with the given demand.Update the demand signature, but be careful not to change boxity info if  is True or if the signature is bottom. See Note [Don't change boxity without worker/wrapper] and Note [Boxity for bottoming functions].Let bindings can be processed in two ways: Down (RHS before body) or Up (body before RHS). This function handles the up variant.It is very simple. For let x = rhs in body * Demand-analyse body2 in the current environment * Find the demand, rhs_dmd placed on x by body * Demand-analyse rhs in rhs_dmdThis is used for a non-recursive local let without manifest lambdas (see ).This is the LetUp rule in the paper @Higher-Order Cardinality Analysis@.Let bindings can be processed in two ways: Down (RHS before body) or Up (body before RHS). This function handles the down variant.,It computes a demand signature (by means of +) and uses that at call sites in the body.It is used for toplevel definitions, recursive definitions and local non-recursive definitions that have manifest lambdas (cf. ). Local non-recursive definitions without a lambda are handled with LetUp.This is the LetDown rule in the paper @Higher-Order Cardinality Analysis@.Mimic the effect of  , turning non-trivial argument expressions/RHSs into a proper let-bound thunk (lifted) or a case (with unlifted scrutinee).A simple, syntactic analysis of whether an expression MAY throw a precise exception when evaluated. It's always sound to return M<. See Note [Which scrutinees may throw precise exceptions]. Recognises types that are * State# RealWorld * Unboxed tuples with a State# RealWorld+ field modulo coercions. This will detect D actions (even post Nested CPR! See T13380e) and user-written variants thereof by their type. dmdAnalRhsSig analyses the given RHS to compute a demand signature for the LetDown rule. It works as follows:0assuming the weakest possible body sub-demand, Llooking at the definition"determining a strictness signatureSince it assumed a body sub-demand of L, the resulting signature is applicable at any call site.The result type after applying c many arguments. Returns K% when the type doesn't have exactly c many arrows..If given the (local, non-recursive) let-bound ,  determines whether we should process the binding up (body before rhs) or down (rhs before body).We use LetDown if there is a chance to get a useful strictness signature to unleash at call sites. LetDown is generally more precise than LetUp if we can correctly guess how it will be used in the body, that is, for which incoming demand the strictness signature should be computed, which allows us to unleash higher-order demands on arguments at call sites. This is mostly the case whenThe binding takes any arguments before performing meaningful work (cf. c;), in which case we are interested to see how it uses them.The binding is a join point, hence acting like a function, not a value. As a big plus, we know *precisely* how it will be used in the body; since it's always tail-called, we can directly unleash the incoming demand of the let binding on its RHS when computing a strictness signature. See [Demand analysis for join points].Thus, if the binding is not a join point and its arity is 0, we have a thunk and use LetUp, implying that we have no usable demand signature available when we analyse the let body.;Since thunk evaluation is memoised, we want to unleash its ] of free vars at most once, regardless of how many times it was forced in the body. This makes a real difference wrt. usage demands. The other reason is being able to unleash a more precise product demand on its RHS once we know how the thunk was used in the let body.=Characteristic examples, always assuming a single evaluation:let x = 2*y in x + x => LetUp. Compared to LetDown, we find out that the expression uses y at most once.let x = (a,b) in fst x6 => LetUp. Compared to LetDown, we find out that b is absent.let f x = x*2 in f y => LetDown. Compared to LetUp, we find out that the expression uses y strictly, because we have f4's demand signature available at the call site.>join exit = 2*y in if a then exit else if b then exit else 3*y => LetDown. Compared to LetUp, we find out that the expression uses y' strictly, because we can unleash exit's signature at each call site.For a more convincing example with join points, see Note [Demand analysis for join points].9How many registers does this type take after unarisation? Unset the  flag if any of the given bindings is a DFun binding. Part of the mechanism that detects Note [Do not strictify a DFun's parameter dictionaries].Extend an environment with the strictness sigs attached to the Ids7Demand put on the "body" (important for join points)How to analyse the "body", e.g. where the binding is in scopeThe analysis environment The variable!The evaluation context of the varThe demand type unleashed by the variable in this context. The returned DmdEnv includes the demand on this function plus demand on its free variables See Note [DmdSig: demand signatures, and demand-sig arity] in GHC.Types.DemandType of the let-bound IdHow the Id is used  None*++< is an abstract type that supports the following operations:Pretty printingIn a C file, does it need to be declared before use? (i.e. is it guaranteed to be already in scope in the places we need to refer to it?)If it needs to be declared, what type (code or data) should it be declared to have?.Is it visible outside this object file or not?#Is it "dynamic" (see details below)Eq and Ord, so that we can make sets of CLabels (currently only used in outputting C as far as I can tell, to avoid generating more than one declaration for any given label).3Converting an info table label into an entry label.CLabel usage is a bit messy in GHC as they are used in a number of different contexts:!By the C-- AST to identify labelsBy the unregisterised C code generator ("PprC") for naming functions (hence the name +)9By the native and LLVM code generators to identify labelsFor extra fun, each of these uses a slightly different subset of constructors (e.g.  and / are used only in the NCG and LLVM backends).In general, we use  to represent Haskell things early in the pipeline. However, later optimization passes will often represent blocks they create with  where there is no obvious  to hang off the label.n This type encodes the subset of + that occurs in C stubs of foreign declarations for the purpose of serializing to interface files.0See Note [Foreign stubs and TH bytecode linking]nStyle of label pretty-printing.When we produce C sources or headers, we have to take into account that C compilers transform C labels when they convert them into symbols. For example, they can add prefixes (e.g., "_" on Darwin). So we provide two ways to pretty-print CLabels: C style or Asm style.n+C label style (used by C and LLVM backends)n%Asm label style (used by NCG backend)nInfo Table Provenance Entry See Note [Mapping Info Tables to Source Positions]What type of Cmm label we're dealing with. Determines the suffix appended to the name when a CLabel.CmmLabel is pretty printed.'misc rts info tables, suffix _info(misc rts entry points, suffix _entry'misc rts ret info tables, suffix _info&misc rts return points, suffix _ret'misc rts data bits, eg CHARLIKE_closure misc rts codeclosures eg CHARLIKE_closure)a prim call to some hand written Cmm codeSelector thunks AP thunks_fast versions of generic applyn=Which module is the info table from, and which number was it.Label for closure*Info tables for closures; always read-only Entry pointSlow entry point)Like InfoTable but not externally visible%Like Entry but not externally visible7Label of place to keep Ticky-ticky hit info for this IdConstructor entry point, when `-fdistinct-info-tables` is enabled then each usage of a constructor will be given a unique number and a fresh info table will be created in the module where the constructor is used. The argument is used to keep track of which info table a usage of a constructor should use. When the argument is K then it uses the info table which is defined in the module where the datatype is declared, this is the usual case. When it is (Just (m, k)) it will use the kth info table defined in module m. The point of this inefficiency is so that you can work out where allocations of data constructors are coming from when you are debugging.Corresponding info table!Table of closures for Enum tycons5Content of a string literal. See Note [Bytes label].Like LocalInfoTable but for a proc-point block instead of a closure entry-point. See Note [Proc-point local block entry-points].Used for dynamic allocations,Used to track dynamic hits of tag inference.n'Record where a foreign label is stored.nLabel is in a named packagenLabel is in some external, system package that doesn't also contain compiled Haskell code, and is not associated with any .hi files. We don't have to worry about Haskell code being inlined from external packages. It is safe to treat the RTS package as "external".nLabel is in the package currently being compiled. This is only used for creating hacky tmp labels during code generation. Don't use it in any code that might be inlined across a package boundary (ie, core code) else the information will be wrong relative to the destination module.n Indicate if  GHC.CmmToC has to generate an extern declaration for the label (e.g. "extern StgWordArray(foo)"). The type is fixed to StgWordArray.Symbols from the RTS don't need "extern" declarations because they are exposed via "rtsinclude&Stg.h" with the appropriate type. See o.The fixed StgWordArray type led to "conflicting types" issues with user provided Cmm files (not in the RTS) that declare data of another type (#15467 and test for #17920). Hence the Cmm parser considers that labels in data sections don't need the "extern" declaration (just add one explicitly if you need it).See  https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary/compiler/backends/ppr-c#prototypes/ for why extern declaration are needed at all.A label related to the definition of a particular Id or Con in a .hs file.A label from a .cmm file that is not associated with a .hs level Id.A label with a baked-in / algorithmically generated name that definitely comes from the RTS. The code for it must compile into libHSrts.a / libHSrts.so If it doesn't have an algorithmically generated name then use a CmmLabel instead and give it an appropriate UnitId argument.A label associated with a block. These aren't visible outside of the compilation unit in which they are defined. These are generally used to name blocks produced by Cmm-to-Cmm passes and the native code generator, where we don't have a 4 to associate the label to and therefore can't use .A C (or otherwise foreign) label.Local temporary label used for native (or LLVM) code generation; must not appear outside of these contexts. Use primarily for debug informationA label "derived" from another + by the addition of a suffix. Must not occur outside of the NCG or LLVM code generators.A per-module metadata label.These labels are generated and used inside the NCG only. They are special variants of a label used for dynamic linking see module GHC.CmmToAsm.PIC for details.This label is generated and used inside the NCG only. It is used as a base for PIC calculations on some platforms. It takes the form of a local numeric assembler label '1'; and is pretty-printed as 1b, referring to the previous definition of 1: in the assembler source file.A label before an info table to prevent excessive dead-stripping on darwin"Per-module table of tick locationsStatic reference table"A bitmap (function or case return)nFor debugging problems with the CLabel representation. We can't make a Show instance for CLabel because lots of its components don't have instances. The regular Outputable instance only shows the label name, and not its other info.nDecides between external and local labels based on the names externality.nMake a foreign labeln+Whether label is a top-level string literaln8Whether label is a non-haskell label (defined in C code)nWhether label is a static closure label (can come from haskell or cmm)n Whether label is a .rodata labeln2Whether label is points to some kind of info tableo4Whether label points to an info table defined in Cmmo1Whether label is points to constructor info tableoA standard string unpacking thunk. See Note [unpack_cstring closures] in StgStdThunks.cmm.oA standard string unpacking thunk. See Note [unpack_cstring closures] in StgStdThunks.cmm.o*A label indicating the end of a procedure.oConstruct a label for a DWARF Debug Information Entity (DIE) describing another symbol.o?Generate a CmmProc delimiter label from the actual entry label.This delimiter label might be the entry label itself, except when the entry label is a LocalBlockLabel. If we reused the entry label to delimit the proc, we would generate redundant labels (see #22792)o7If a label is a local block label then return just its  , otherwise K.oCheck whether a label corresponds to a C function that has a prototype in a system header somewhere, or is built-in to the C compiler. For these labels we avoid generating our own C prototypes.oIs a CLabel visible outside this object file or not? From the point of view of the code generator, a name is externally visible if it has to be declared as exported in the .o file's symbol table; that is, made non-static.Work out the general type of data at the address of this label whether it be code, data, or static GC object.oIs a +. defined in the current module being compiled?Sometimes we can optimise references within a compilation unit in ways that we couldn't for inter-module references. This provides a conservative estimate of whether a + lives in the current module.oDoes a + need dynamic linkage?When referring to data in code, we need to know whether that data resides in a DLL or not. [Win32 only.]  labelDynamic returns True if the label is located in a DLL, be it a data reference or not.o;Generate a label for a procedure internal to a module (if Opt_ExposeAllSymbols/ is enabled). See Note [Internal proc labels].oProject the constructor  out of +' if it is an initializer or finalizer.o Inject a n into a + as a .oA utility for renaming uniques in CLabels to produce deterministic object. Note that not all Uniques are mapped over. Only those that can be safely alpha renamed, e.g. uniques of local symbols, but not of external ones. See Note [Renaming uniques deterministically].oDon't depend on this if you need determinism. No determinism in the ncg backend, so we use the unique for Ord. Even if it pains me slightly.encodes the suffix of the label"what package the label belongs to..does the label need an "extern .." declaration)identifier giving the prefix of the labelencodes the suffix of the labelname of the imported label.%what package the foreign label is in.suffixothe current modulethe internal proc labeloooonooonooononnoonnnoooonnnooooonnonnnoonnnnnnnnnnononoonoonnoonnnnnnnnnnonnonnooonnnnnnnonnnooo+nooooo+nnnnnnnnnnnnnnnnnnnnnnnnnnnnn+nnnnnnnnnnnnnnnnnnnnnnnnnnnnooooooooooonnnnnnnnnnnnnnnnnnnnnnooonnnnnnnnnnonnooonnnnnnnoooooooooooooonoonnoonnnnooooonnnn+ooonnnnnoooo 'o  o   o  )o   o %o  *o  o  o  o *,o .1o  o  o o  o o  o o  o o )+o -0o  o o o o o o o None&' 0A source file added from Template Haskell using qAddForeignFilePath, for storage in interfaces.0See Note [Foreign stubs and TH bytecode linking]The extension used by the user is preserved, to avoid confusing external tools with an unexpected .c file or similar.The contents of the file, which will be written to a temporary file when loaded from an interface.&The language is specified by the user.Simplified encoding of   for interface serialization.0See Note [Foreign stubs and TH bytecode linking]%Wrapper for avoiding a dependency on  and  in +.The location where the sources reside. | Stubs for foreign declarations and files added via  .%The module which the bindings are for serialised tidied core bindings.  for .  for .Convert foreign stubs and foreign files to a format suitable for writing to interfaces.0See Note [Foreign stubs and TH bytecode linking]2Decode serialized foreign stubs and foreign files.0See Note [Foreign stubs and TH bytecode linking]                 !  !  %      !None  !3 A>)Does this module define family instances? summarises everything we know about a compiled module. The ʑ is the stuff *before* linking, and can be written out to an interface file. The 'ModDetails is after linking and can be completely recovered from just the ʑ.4When we read an interface file, we also construct a ʑ. from it, except that we explicitly make the ב and a few other fields empty; as when reading we consolidate the declarations etc. into a number of indexed maps and environments in the ExternalPackageState.See Note [Strictness in ModIface] to learn about why some fields are strict and others are not.See Note [Private fields in ModIface] to learn why we don't export any of the fields.&A serialised in-memory buffer of this ʑ9. If this handle is given, we can avoid serialising the ʑ when writing this ʑ to disk, and write this buffer to disk instead. See Note [Sharing of ModIface].8Hash of the .hs source, used for recompilation checking.Additional optional fields, where the Map key represents the field name, resulting in a (size, serialized data) pair. Because the data is intended to be serialized through the internal 3 class (increasing compatibility with types using  and  FastString,, such as HIE), this format is chosen over  ByteStrings.Either () or % for a fully instantiated interface.:Docstrings and related data for use by haddock, the ghci :doc command, and other tools.Just _  = the module was built with -haddock.Do we require the package this module resides in be trusted to trust this module? This is used for the situation where a module is Safe (so doesn't require the package be trusted itself) but imports some trustworthy modules from its own package (which does require its own package be trusted). See Note [Trust Own Package] in GHC.Rename.Names‹/Safe Haskell Trust information for this module.Ë:True if this program uses Hpc at any point in the program.ċ Sorted rulesŋSorted family instancesƋSorted class instanceNjJust enough information to reconstruct the top level environment in the original source code for this module. which is NOT the same as mi_exports, nor mi_decls (which may contains declarations for things not actually defined by the user). Used for GHCi and for inspecting the contents of modules via the GHC API only.(We need the source file to figure out the top-level environment, if we didn't compile this module from source then this field contains Nothing).1Strictly speaking this field should live in the  HomeModInfo", but that leads to more plumbing.ȋ+default declarations exported by the moduleɋ&Foreign stubs and files to supplement ʋ3. See Note [Foreign stubs and TH bytecode linking]ʋExtra variable definitions which are **NOT** exposed but when combined with mi_decls allows us to restart code generation. See Note [Interface Files with Core Definitions] and Note [Interface File with Core: Sharing RHSs]ˋType, class and variable declarations The hash of an Id changes if its fixity or deprecations change (as well as its type of course) Ditto data constructors, class operations, except that the hash of the parent class/tycon changes̋Annotations NOT STRICT! we read this field lazily from the interface file͋Warnings NOT STRICT! we read this field lazily from the interface file΋Fixities NOT STRICT! we read this field lazily from the interface fileϋModule required TH splices when it was compiled. This disables recompilation avoidance (see #481).ЋExports Kept sorted by (mod,occ), to make version comparisons easier Records the modules that are the declaration points for things exported by this module, and the s of those thingsыUsages; kept sorted so that it's easy to decide whether to write a new iface file (changing usages doesn't affect the hash of this module) NOT STRICT! we read this field lazily from the interface file It is *only* consulted by the recompilation checkerThe elements must be *deterministically* sorted to guarantee deterministic interface filesҋThe dependencies of the module. This is consulted for directly-imported modules, but not for anything else (hence lazy)ӋBoot? Signature?ԋAre we a sig of another mod?ՋName of the module we are for)In-memory byte array representation of a ʑ.4See Note [Sharing of ModIface] for why we need this. A partial ʑ cannot be serialised to disk. Optional ) that can be serialised to disk directly.See Note [Private fields in ModIface] for when this fields needs to be cleared (e.g., set to K).Selects a IfaceDecl representation. For fully instantiated interfaces we also maintain a fingerprint, which is used for recompilation checks.֋9Partial interface built based on output of core pipeline.Extends a PartialModIface with information which is either: * Computed after codegen * Or computed just before writing the iface to disk. (Hashes) In order to fully instantiate it.Cached lookup for ב. The Nothing in  means that the thing isn't in decls. It's useful to know that when seeing if we are up to date wrt. the old interface. The + is the parent of the name, if it has one.Cached lookup for ԑCached lookup for Ց for export deprecationsCached lookup for Ց for declaration deprecations:Hash for orphan rules, class and family instances combinedHash of export list‘Whether this module has family instances. See Note [The type family instance consistency story].ÑWhether this module has orphansđHash of pluginsőHash of hpc flagsƑHash of optimisation flagsǑHash of the important flags used when compiling the module, excluding optimisation flagsȑHash of the ABI onlyɑHash of the whole interfaceOld-style accessor for whether or not the ModIface came from an hs-boot file.-Lookups up a (possibly cached) fixity from a ʑ. If one cannot be found,  is returned instead.The semantic module for this interface; e.g., if it's a interface for a signature, if ͑ is p[A= A]:A,  will be  A.:The "precise" free holes, e.g., the signatures that this ʑ depends on.Given a set of free holes, and a unit identifier, rename the free holes according to the instantiation of the unit identifier. For example, if we have A and B free, and our unit identity is p[A= C ,B=impl:B]%, the renamed free holes are just C.Constructs cache for the  field of a ʑGiven a ˑ, turn it into a ʑ by completing missing fields.Add a source fingerprint to a - without invalidating the byte array buffer . This is a variant of " which does invalidate the buffer.The  is computed outside of  based on the  ModSummary.6Copy fields that aren't serialised to disk to the new . This includes especially hashes that are usually stored in the interface file header and ۑ.$We need this function after calling  shareIface, to make sure the  doesn't lose any information. This function does not discard the in-memory byte array buffer .׋/Invalidate any byte array buffer we might have.̑ttʑ‘ǑőɑȑƑÑđ֑בڑБґؑݑԑّߑϑܑ͑ޑΑۑёӑՑˑʑ͑ΑϑБёґӑԑՑ֑בڑّؑۑܑݑޑߑ̑ˑ‘ǑőɑȑƑÑđtt    "  '  None+3NLabel for syntax that may occur in terms (expressions) only as part of a required type argument. type t ctx => t t1 -> t2  forall tvs. t'TcRnNoDerivStratSpecified TcRnNoDerivingClauseStrategySpecified' is a warning implied by -Wmissing-deriving-strategies and triggered by a deriving clause without a specified deriving strategy.Example:4newtype T = T Int deriving (Eq, Ord, Show)4Here we would suggest fixing the deriving clause to:8deriving stock (Show) deriving newtype (Eq, Ord)Test cases: derivingshould_compile"T15798a derivingshould_compile"T15798c derivingshould_compile"T24955a derivingshould_compileT24955b'TcRnNoDerivStratSpecified TcRnNoStandaloneDerivingStrategySpecified' is a warning implied by -Wmissing-deriving-strategies and triggered by a standalone deriving declaration without a specified deriving strategy.Example:=data T a = T a deriving instance Show a => Show (T a)-Here we would suggest fixing the instance to:,deriving stock instance Show a => Show (T a)Test cases: derivingshould_compile"T15798b derivingshould_compileT24955c7Reason why a type cannot be marshalled through the FFI.The phase in which an exception was encountered when dealing with a TH spliceLabel for a TH declarationThe reason a TH splice could not be converted to a Haskell expressionϒSourceג3Identifies the TH splice attempting to be convertedߒSpliceThrewException is an error that occurs when running a Template Haskell splice throws an exception. Example(s):Test cases: annotations should_fail!annfail12 perfcompiler0MultiLayerModulesTH_Make perfcompilerMultiLayerModulesTH_OneShot th/T10796b th/T19470 th/T19709d th/T5358 th/T5976 th/T7276a th/T8987 th/TH_exn1 th/TH_exn2 th/TH_runIORunSpliceFailure is an error indicating that a Template Haskell splice failed to be converted into a valid expression. Example(s):Test cases: th/T10828a th/T10828b th/T12478_4 th/T15270A th/T15270B th/T16895a th/T16895b th/T16895c th/T16895d th/T16895e th/T18740d th/T2597b th/T2674 th/T3395 th/T7484 th/T7667a th/TH_implicitParamsErr1 th/TH_implicitParamsErr2 th/TH_implicitParamsErr3 th/TH_invalid_add_top_declSplicePolymorphicLocalVar is the error that occurs when the expression inside typed Template Haskell brackets is a polymorphic local variable. a) -> [|| y ||]Test cases: quotes/T10384TypedTHWithPolyType is an error that signifies the illegal use of a polytype in a typed Template Haskell expression.Example(s): bad :: (forall a. a -> a) -> () bad = $$( [|| _ -> () ||] )Test cases: th/T11452InvalidTopDecl is a Template Haskell error occurring when one of the Decs passed to  addTopDecls is not a function, value, annotation, or foreign import declaration. Example(s): Test cases:UnexpectedDeclarationSplice is an error that occurs when a Template Haskell splice appears inside top-level declarations added with  addTopDecls.Example(s): noneTest cases: noneCannotReifyInstance is a Template Haskell error for when an instance being reified via reifyInstances6 is not a class constraint or type family application. Example(s): Test cases:CannotReifyOutOfScopeThing is a Template Haskell error indicating that the given name is not in scope and therefore cannot be reified. Example(s):Test cases: th/T16976fCannotReifyThingNotInTypeEnv is a Template Haskell error occurring when the given name is not in the type environment and therefore cannot be reified. Example(s): Test cases:NoRolesAssociatedWithName is a Template Haskell error for when the user tries to reify the roles of a given name but it is not something that has roles associated with it. Example(s): Test cases:CannotRepresentThing is a Template Haskell error indicating that a type cannot be reified because it does not have a representation in Template Haskell. Example(s): Test cases:NonExactName is a Template Haskell error that occurs when the user attempts to define a binder with a 4 that is not an exact . Example(s): Test cases:QuotedNameWrongStage is an error that can happen when a (non-top-level) Name is used at a different Template Haskell stage than the stage at which it is bound.Test cases: T16976zAn error involving Template Haskell quotes or splices, e.g. nested quotation brackets or the use of an untyped bracket inside a typed splice.IllegalTHQuotes is an error that occurs when a Template Haskell quote is used without the TemplateHaskell extension enabled.Test case: T18251eIllegalTHSplice is an error that occurs when a Template Haskell splice occurs without having enabled the TemplateHaskell extension.Test cases: bkpfail01, bkpfail05, bkpfail09, bkpfail16, bkpfail35, bkpcabal06NestedTHBrackets is an error that occurs when Template Haskell brackets are nested without any intervening splices.Example: foo = [| [| x |] |])Test cases: TH_NestedSplicesFail{5,6,7,8}MismatchedSpliceType is an error that happens when a typed bracket or splice is used inside a typed splice/bracket, or the other way around. Examples:;f1 = [| $$x |] f2 = [|| $y ||] f3 = $$( [| x |] ) f4 = $( [|| y ||] ))Test cases: TH_NestedSplicesFail{1,2,3,4}BadImplicitSplice is an error thrown when a user uses top-level implicit TH-splice without enabling the TemplateHaskell extension.Example:pure [] -- on top-levelTest cases: ghciprog019prog019 ghciscriptsT1914 ghciscriptsT6106 rename should_failT4042 rename should_failT12146;A syntax error with Template Haskel quotes & splices. See .'An error in Template Haskell involving s. See ..An error in Template Haskell reification. See .An error due to typing restrictions in Typed Template Haskell. See .An error occurred when trying to run a splice in Template Haskell. See ޒ.An error involving the  addTopDecls functionality. See .IllegalStaticFormInSplice is an error when a user attempts to define a static pointer in a Template Haskell splice. Example(s):"Test cases: th/TH_StaticPointers02FailedToLookupThInstName is a Template Haskell error that occurrs when looking up an instance fails. Example(s):Test cases: showIface should_failTHPutDocNonExistentAddInvalidCorePlugin is a Template Haskell error indicating that a Core plugin being added has an invalid module due to being in the current package. Example(s): Test cases:AddDocToNonLocalDefn is a Template Haskell error for documentation being added to a definition which is not in the current module. Example(s):Test cases: showIface should_failTHPutDocExternal;ReportCustomQuasiError is an error or warning thrown using qReport from the Quasi instance of TcM. Example(s): Test cases:Which instance coverage condition failed? Was it the liberal coverage condition?,Failed the instance coverage condition (ICC)5Failed the liberal instance coverage condition (LICC))Whether the instance also failed the LICC6Description of an instance coverage condition failure.1Why was a HasField instance declaration rejected?3HasField instance for a type not headed by a TyCon.Example:instance HasField a where {..}Test case: hasfieldfail03$HasField instance for a data family.Example:3data family D a data instance D Int = MkDInt Char*instance HasField "fld" (D Int) where {..}Test case: hasfieldfail039HasField instance for a type that already has that field.Exampledata T = MkT { quux :: Int } instance HasField "quux" T Int where {..}Test case: hasfieldfail03HasField instance for a type that already has fields, when the field label could potentially unify with those fields.Example:data T = MkInt { quux :: Int } instance forall (fld :: Symbol). HasField fld T Int where {..}Test case: hasfieldfail03.Why was a class instance declaration rejected?,An illegal type at the head of the instance.See ז."An illegal HasField instance. See .8An illegal instance for a built-in typeclass such as  Coercible, , or KnownNat, outside of a signature file.Test cases: deriving should_failT9687 deriving should_fail>T14916 polykinds/T8132 typecheck should_fail)TcCoercibleFail2 typecheck should_failT12837 typecheck should_failT14390)Why was an instance declaration rejected?6Possible cases for the -Wnoncanonical-monad-instances. pure = return was defined. (*>) = (>>) was defined.return% was defined as something other than pure.(>>)% was defined as something other than (*>).7Possible cases for the -Wnoncanonical-monoid-instances.(<>) = mappend was defined.mappend% was defined as something other than (<>).1Different reasons for TcRnNonCanonicalDefinition. Related to (<>) and mappend. Related to (*>)(>>) and purereturn.Provenance of an unused name.Different places in which a nested foralls/contexts error might occur.Nested forall in SPECIALISE instanceNested forall in  deriving via (via-type)/Nested forall in the type of a GADT constructor!Nested forall in an instance head4Nested forall in a standalone deriving instance head$Nested forall in deriving class type-Different types of errors for unused imports.3No names in the import list are used in the module.Test cases: overloadedrecfldsfail06, T10890_2, t22391, t22391j, T1074, prog018, mod177, rn046, rn037, T5211=A set of names in the import list are not used in the module.Test cases: overloadedrecfldsfail06, T17324, mod176, T11970A, rn046, T14881, T7454, T8149, T13064?Distinguish record fields from other names for pretty-printing.,Different types of errors for import lookup.An item in an import statement is not exported by the corresponding module.Test cases: T21826, recomp001, retc001, mod79, mod80, mod81, mod91, T6007, T7167, T9006, T11071, T9905fail2, T5385, T10668-A name is specified with a qualifying module.Test cases: T3792;Something completely unexpected is in an import list, like  module Foo.%Test cases: ImportLookupIllegalAn item in an import list matches multiple names exported from that module.Test cases: None.Different types of warnings for dodgy imports.An import of the form 'T(..)' or 'f(..)' does not actually import anything beside T/f itself.Test cases: DodgyImportsA hiding clause contains something that would be reported as an error in a regular import, but is relaxed to a warning.%Test cases: DodgyImports_hiding“ doThe information necessary to report mismatched numbers of arguments in a match group.1Context for a mismatch in the number of argumentsName of the functionPattern match specificsStores the information to be reported in a representation-polymorphism error message.Which non-concrete type did we try to unify this concrete type variable with?What is the original type we checked for representation-polymorphism, and what specific check did we perform?3Whether we ran out of fuel generating the bindings..A collection of hole fits and refinement fits.A collection of valid hole fits or refinement fits, in which some fits might have been suppressed.Whether we have suppressed any fits because there were too many.”This datatype collates instances that match or unifier, in order to report an error message for an unsolved typeclass constraint.Ɣ!Explain a problem with an import.ǔ/Couldn't find a module with the requested name.Ȕ9The imported modules don't export what we're looking for.ɔA message that aims to explain why two types couldn't be seen to be representationally equal.ʔNot knowing the role of a type constructor prevents us from concluding that two types are representationally equal.Example:foo :: Applicative m => m (Sum Int) foo = coerce (pure $ 1 :: Int)We don't know what role m2 has, so we can't coerce `m Int` to `m (Sum Int)`.#Test cases: T8984, TcCoercibleFail.˔The fact that a - is abstract prevents us from decomposing a TyConApp: and deducing that two types are representationally equal.Test cases: none.̔ Down Int foo = coerceTest cases: TcCoercibleFail.͔Report an error involving a .This could be an out of scope data constructor or variable, a typed hole, or a wildcard in a type.ΔReport an out-of-scope data constructor or variable masquerading as an expression hole.Report a typed hole, or wildcard, with additional information.Д2Configuration for pretty-printing valid hole fits.ה Some form of "not in scope" error. See also the Δ constructor of ͔.ؔA run-of-the-mill "not in scope" error.ٔLike ؔ6, but when we know we are looking for a record field.ڔ An exact  was not in scope.This usually indicates a problem with a Template Haskell splice.Test cases: T5971, T18263.۔always at least 2 elementsݔ"Couldn't find a top-level binding.Happens when specifying an annotation for something that is not in scope.,Test cases: annfail01, annfail02, annfail11.ޔA class doesn't have a method with this name, or, a class doesn't have an associated type with this name, or, a record doesn't have a record field with this name.ߔA name is not in scope during type checking but passed the renamer.Test cases: noneModule does not export...is ExplicitNamespaces enabled? | Trying to import a data constructor directly, e.g. import Data.Maybe (Just) instead of import Data.Maybe (Maybe(Just)).The parent does not export the given children. Incorrect type5 keyword when importing something which isn't a type.'Explain how a kind equality originated.Expected/actual information.&Display the expected and actual types.Display the expected and actual types, after expanding type synonyms.$Add some information about ambiguity?Some type variables remained ambiguous: print them to the user.?Remind the user that a particular type family is not injective.Ambiguous kind and type variables, respectively. Guaranteed to not both be empty.True  => start the message with "Ambiguous type variable ..." False  =? create a message of the form "The type variable is ambiguous.":Add some information to disambiguate errors in which two Names( would otherwise appear to be identical.)See Note [Disambiguating (X ~ X) errors].Whether the two "s also came from the same package.A cue to print out information about type variables, e.g. where they were bound, when there is a mismatch  tv1 ~ ty2.(Additional information to be given in a & message, which is then passed on to mk_supplementary_ea_msg.7A type equality between a type variable and a polytype.(Test cases: T12427a, T2846b, T10194, ...An occurs check.)A skolem type variable escapes its scope.Example:7data Ex where { MkEx :: a -> MkEx } foo (MkEx x) = x#Test cases: TypeSkolEscape, T11142.Can't unify the type variable with the other type due to the kind of type variable it is.For example, trying to unify a SkolemTv with the type Int, or with a TyVarTv.:Whether to use expected/actual in a type mismatch message.Don't use expected/actual.Use expected/actual./Whether to also mention type synonym expansion."Couldn't unify two types or kinds.Example:93 + 3# -- can't match a lifted type with an unlifted typeTest cases: T1396, T8263, ...A type has an unexpected kind.Test cases: T2994, T7609, ...?A mismatch between two types, which arose from a type equality.Test cases: T1470, tcfail212.Couldn't solve some Wanted constraints using the Givens. Used for messages such as "No instance for ..." and "Could not deduce ... from".4Second type (the actual type if mismatch_ea is True)8First type (the expected type if if mismatch_ea is True)0The constraint in which the mismatch originated.6Should this be phrased in terms of expected vs actual?What thing is  the kind of?What thing is  the kind of?The overall actual typeThe overall expected type!Some additional info consumed by mk_supplementary_ea_msg.)The Wanted constraints we couldn't solve. N.B.: the ĕ at the head of the list has been tidied, perhaps not the others.An error reported after constraint solving. This is usually, some sort of unsolved constraint error, but we try to be specific about the precise problem we encountered.4Quantified variables appear out of dependency order.Example:forall (a :: k) k. ...:Test cases: BadTelescope2, T16418, T16247, T16726, T18451.We came across a custom type error and we have decided to report it.Example:9type family F a where F a = TypeError (Text "error")err :: F () err = ()1Test cases: CustomTypeErrors0{1,2,3,4,5}, T12104.;Report a Wanted constraint of the form "Unsatisfiable msg".We want to report an out of scope variable or a typed hole. See ͔.4Cannot unify a variable, because of a type mismatch.A mismatch between two types.:A violation of the representation-polymorphism invariants.See  and FixedRuntimeRepContext for more information.An equality between two types is blocked on a kind equality between their kinds.Test cases: none.9Something was not applied to sufficiently many arguments.Example:instance Eq Maybe where {..}Test case: T11563.,Trying to use an unbound implicit parameter.Example:foo :: Int foo = ?paramTest case: tcfail130.A constraint couldn't be solved because it contains ambiguous type variables.Example:!class C a b where f :: (a,b) x = fst fTest case: T4921.Could not solve a constraint; there were several unifying candidate instances but no matching instances. This is used to report as much useful information as possible about why we couldn't choose any instance, e.g. because of ambiguous type variables.Could not solve a constraint using available instances because the instances overlap.,Test cases: tcfail118, tcfail121, tcfail218.Could not solve a constraint from instances because instances declared in a Safe module cannot overlap instances from other modules (with -XSafeHaskell).%Test cases: SH_Overlap{1,2,5,6,7,11}.ĕA predicate with its arising location; used to encapsulate a constraint that will give rise to a diagnostic.ʕ=for Wanteds, where to put the evidence for Givens, Nothing̕ Context needed when reporting a , such as the enclosing implication constraints or whether we are deferring type errors.ΕTrue  = More important errors have occurred, so create bindings if need be, but don't issue any more errors/warnings See Note [Suppressing error messages]ϕTrue  = -fprint-expanded-synonymsЕTrue  = -Wredundant-constraintsѕ(Reason for reporting out of scope holes.ҕ$Reason for reporting holes in types.ӕ*Reason for reporting holes in expressions.ԕ*Whether to defer type errors until runtimeՕWe make some errors (depending on cec_defer) into warnings, and emit evidence bindings into Օ for unsolved constraintsוEnclosing implications (innermost first) ic_skols and givens are tidied, rest are notؕA , together with context (e.g. enclosing implication constraints) that are needed in order to report it.ڕ%The content of the message to report.ەContext for what we wish to report. This can change as we enter implications, so is stored alongside the content.ܕ%Additional information to print in a <, after the important messages and after the error context.See Note [Error report].A collection of main error messages and supplementary information.In practice, we will: - display the important messages first, - then the error context (e.g. by way of a call to  ), - then the supplementary information (e.g. relevant bindings, valid hole fits), - then the hints ("Possible fix: ...").So this is mostly just a way of making sure that the error context appears early on rather than at the end of the message.$See Note [Error report] for details.A mismatch in a data constrcutor, between its declaration in an hs-boot file or signature file, and its implementation in a source Haskell module.The  s of the ( s differ.The fixities of the ( s differ."The strictness annotations of the ( s differ.The (s have different field labels.The (s have incompatible types.A mismatch in a datatype declaration, between an hs-boot file or signature file and its implementing module.5A datatype is implemented as a newtype or vice-versa.The constructors don't match.The datatype contexts differ.A mismatch in an associated type of a class, between its declaration in an hs-boot or signature file, and its implementation in a source Haskell file.!Two associated types don't match.)Two associated type defaults don't match.A mismatch in a class method, between its declaration in an hs-boot or signature file, and its implementation in a source Haskell file.%The class method names are different.*The types of a class method are different.,The default method types are not compatible.A mismatch in a class, between its declaration in an hs-boot or signature file, and its implementation in a source Haskell file.The class methods don't match.!The associated types don't match.(The functional dependencies don't match.The superclasses don't match.The MINIMAL pragmas are not compatible.4The quantified variables in an equation don't match.Example: the quantification of a in 1type family F a where { forall a. F a = Maybe a }$The LHSs of an equation don't match.$The RHSs of an equation don't match.Utility datatype to record errors when checking compatibity between two lists of things, e.g. class methods, associated types, type family equations, etc.Different number of items.3The item at the given position in the list differs.Mismatched implementation of a ! in an hs-boot or signature file.The  kinds differ.The   s aren't compatible.The two s are of a different flavour, e.g. one is a data family and the other is a type family.+The equations of a type family don't match.4The type family injectivity annotations don't match.The s are both datatype s, but they have diferent (s.The  s are both K s, but the classes don't match.The %s are something completely different. An abstract  is implemented using a type synonym in an invalid manner. See .An error in the implementation of an abstract datatype using a type synonym. The type synony was not nullary.The type synonym RHS contained invalid types, e.g. a type family or a forall.A mismatch of two s between an hs-boot or signature file and its implementing module.The s have different types.Something from the hs-boot or signature file is missing from the implementing module.Something defined in the hs-boot or signature file is not defined in the implementing module.Something exported by the hs-boot or signature file is not exported by the implementing module.A mismatch between an hs-boot or signature file and its implementing module.Something defined or exported by an hs-boot or signature file is missing from the implementing module.A typeclass instance is declared in the hs-boot file but it is not present in the implementing module.A mismatch between an hsig file and its implementing module in the ' that a particular re-export refers to.A mismatch between the declaration of something in the hs-boot or signature file and its implementation, e.g. a type mismatch or a type family implemented as a class.>What declarations were not allowed in an hs-boot or hsig file?2Is the object we are dealing with exported or not?Used for reporting "missing signature" warnings, see ./What kind of thing is missing a type signature?Used for reporting "missing signature" warnings, see tcRnMissingSignature.whether -XCUSKs is enabledIf , the associated type of a typeclass is not parameterized over the last type variable of the class'The associated type family of the classIf , the associated type of a typeclass contains the last type variable of the class in a kind, which is not (yet) allowed by GHC.'The associated type family of the classA type representing whether or not the input type has associated data family instances.?Invalid arguments in an associated family instance declaration.An argument which isn't a type variable in an associated family instance default declaration.Duplicate occurrence of a type variable in an associated family instance default declaration.The reason that an associated family default declaration was invalid.An associated family default declaration for something that isn't an associated family.3Invalid arguments in an associated family instance.See .:The reason that an associated family instance was invalid.A class instance is missing its expected associated type/data instance.Test cases: derivingshould_compile!T14094 indexed-typesshould_compileSimple2 typecheckshould_compiletc254.A top-level instance for an associated family .Example:4class C a where { type T a } instance T Int = BoolTest case: indexed-types should_fail SimpleFail7An associated type instance is provided for a class that doesn't have that associated type.8Examples(s): $(do d <- instanceD (cxt []) (conT ''Eq appT conT ''Foo) [tySynInstD $ tySynEqn Nothing (conT ''Rep appT conT ''Foo) (conT ''Maybe)] return [d]) ======> instance Eq Foo where type Rep Foo = MaybeTest cases: th/T12387aAn associated family instance does not mention any of the parent K s. Test cases: T2888, T9167, T12867Ö&An invalid associated family instance.See .BuilderĖ1An invalid associated family default declaration.See .ƖA dodgy binder, i.e. a variable that syntactically appears in LHS patterns but only in non-injective positions.See Note [Dodgy binding sites in type family instances] in GHC.Tc.Validity.ǖA quantified type variable in a type or data family equation that is not bound in any LHS patterns.ȖA quantified type variable in a type or data family equation that is not used on the RHS.ɖA quantified type variable in a type or data family equation that is either not bound in any LHS patterns or not used in the RHS (or both).˖9For what reason was the quantified type variable invalid?̖Did the user write this type variable, or was introduced by GHC? For example: with  -XPolyKinds, in type instance forall a. F = (), we have a user-written a$ but GHC introduces a kind variable k as well. See #23734.Ζ0Why is a (type or data) family instance invalid?ϖ"A top-level family instance for a  that isn't a family .Example:/data D a = MkD type instance D Int = BoolTest case: indexed-types should_failT3092ЖA top-level (open) type family instance for a closed type family.Test cases: indexed-types should_failOverlap7 indexed-types should_failOverlap3іA family instance was declared for a family of a different kind, e.g. a data instance for a type family .&Test cases: T9896, SimpleFail3aҖA family instance was declared with a different number of arguments than expected. See Note [Oversaturated type family equations] in GHC.Tc.Validity.Test cases: TyFamArity1, TyFamArity2, T11136, Overlap4, AssocTyDef05, AssocTyDef06, T14110ӖA closed type family equation used a different name than the parent family.Example:*type family F a where G Int = Bool:Test cases: Overlap5, T15362, T16002, T20260, T11623ԖThere are out-of-scope type variables in the right-hand side of an associated type or data family instance.Example:instance forall a. C Int where data instance D Int = MkD1 aTest cases: indexed-types should_failT5515, polykinds T9574, renameshould_fail/T18021Ֆthe unused bound type variablesז%Why is a class instance head invalid?ؖAn instance for an abstract class from an hs-boot or Backpack hsig file.Example:,- A.hs-boot module A where class C a- B.hs module B where import {-# SOURCE #-} A instance C Int where- A.hs module A where import B class C a where f :: aTest cases: typecheck should_failT13068ٖ&An instance whose head is not a class. Examples(s): instance c instance 42instance !Show D7type C1 a = (Show (a -> Bool)) instance C1 Int whereTest cases: typecheckrenameT5513 typecheckrenameT16385 parser should_failT3811c rename should_fail;T18240a polykinds/T13267 deriving should_failT23522ږ+Instance head was headed by a type synonym.Example: type MyInt = Int class C a where {..} instance C MyInt where {..}8Test cases: drvfail015, mod42, TidyClassKinds, tcfail139ۖ"Instance head was not of the form  T a1 ... an , where  a1, ..., an$ are all type variables or literals.Example:instance Num [Int] where {..}/Test cases: mod41, mod42, tcfail044, tcfail047.ܖ5Multi-param instance without -XMultiParamTypeClasses.Example:instance C a b where {..}$Test case: IllegalMultiParamInstanceݖ;Whether a sole extra-constraint wildcard is allowed, e.g. _ => .. as opposed to ( .., _ ) => ...6A context in which we don't allow anonymous wildcards.-The type must not have some datatype context.The data constructor must not have exotic unlifted or polymorphic arguments.3The data constructor must be a vanilla constructor.The type must have some type parameters. check (d) from Note [Requirements for deriving Generic and Rep] in GHC.Tc.Deriv.Generics.9The data constructor must not have existential arguments.The derivation applies a type to an argument involving the last parameter but the applied type is not of kind * -> *. The given ( must be truly polymorphic in the last argument of the data type. The given (7 must not use the type variable in a function argument" The given ( must not contain function types The given ( must use the type variable only as the last argument of a data type The given (; is a GADT so we cannot directly derive an istance for it. The given (( has existentials type vars in its type. The given ( has constraints in its type. The given ( has a higher-rank type.8Why a particular typeclass instance couldn't be derived.*The typeclass instance is not well-kinded.=The instance type | We cannot derive instances in boot files&We cannot use GND on non-newtype types-We cannot derive instances of nullary classes,Last arg must be newtype or data application The given  is not a class."The given (representation of the)  has no data constructors./GHC simply doesn't how to how derive the input K for the given . The given  must be an enumeration. See Note [Enumeration types] in GHC.Core.TyCon The given  must have  precisely one constructor..The given data type must have some parameters.2The given data type must not have a class context.We couldn't derive an instance for a particular data constructor for a variety of reasons.We couldn't derive a ؋6 instance for the given type for a variety of reasonsWe couldn't derive an instance either because the type was not an enum type or because it did have more than one constructor.A data type to describe why a variable is not closed. See Note [Not-closed error messages] in GHC.Tc.Gen.ExprHelper type used in checkDataKindSig.Superficially similar to  ContextKind, but it lacks AnyKind and , and instead of TheKind liftedTypeKind provides 3, which is much simpler to match on and handle in isAllowedDataResKind.'A description of whether something is adata or newtype () data instance or newtype instance () data family ()/At present, this data type is only consumed by checkDataKindSig.Why the particular injectivity error arose together with more information, if any.Why the particular illegal newtype error arose together with more information, if any.In what context did we require a type to have a fixed runtime representation?Used by   for throwing representation polymorphism errors when validity checking.See Note [Representation polymorphism checking] in GHC.Tc.Utils.ConcreteData constructor fields must have a fixed runtime representation.Tests: T11734, T18534.Pattern synonym signature arguments must have a fixed runtime representation.Test: RepPolyPatSynArg.—Pattern synonym signature scrutinee must have a fixed runtime representation.Test: RepPolyPatSynRes.× Where a shadowed name comes fromė(The shadowed name is local to the moduleŗ?The shadowed name is global, typically imported from elsewhere.Ɨ"Why did we reject a record update?Ǘ.No constructor has all of the required fields.ȗThere are several possible parents which have all of the required fields, and we weren't able to disambiguate in any way.ɗWe used type-directed disambiguation, but this resulted in an invalid parent (the type-directed parent is not among the parents we computed from the field labels alone).˗Which parts of a record field are affected by a particular error or warning.З>Whether the error pertains to a function argument or a result.ӗSpecifies which calling convention is unsupported on the current platformחSpecifies which back ends can handle a requested foreign import or exportؗThings forbidden in  type data1 declarations. See Note [Type data declarations]ޗZonkerCannotDefaultConcrete is an error occurring when a concrete type variable cannot be defaulted.Test cases: T23153ߗ8An error which might arise during typechecking/renaming.Simply wraps an unknown Ɓ message a. It can be used by plugins to provide custom diagnostic messages originated during typechecking/renaming.Wrap an  to a ߗ for when we attempt to load interface files during typechecking but encounter an error. TcRnMessageWithInfo is a constructor which is used when extra information is needed to be provided in order to qualify a diagnostic and where it was originated (and why). It carries an extra  which can be used to pretty-print some names and it wraps a , which includes any extra context associated with this diagnostic.TcRnWithHsDocContext annotates an error message with the context in which it originated.TcRnSolverReport is the constructor used to report unsolved constraints after constraint solving, as well as other errors such as hole fit errors.See the documentation of 8 datatype for an overview of the different errors.TcRnSolverDepthError is an error that occurs when the constraint solver exceeds the maximum recursion depth.Example:class C a where { meth :: a } instance Cls [a] => Cls a where { meth = head . meth }t :: () t = methTest cases: T7788 T8550 T9554 T15316A T17267{D,a,b,c,e} T17458 ContextStack1 T22924b TcCoercibleFailTcRnRedundantConstraints is a warning that is emitted when a binding has a user-written type signature which contains superfluous constraints.Example:f :: (Eq a, Ord a) => a -> a -> a f x y = (x < y) || x == y -- `Eq a` is superfluous: the `Ord a` constraint suffices. Bool foo MkFalse = False foo MkTrue = True -- Inaccessible: requires True ~ FalseTest cases: T7293, T7294, T15558, T17646, T18572, T18610, tcfail167.TcRnInaccessibleCoAxBranch is a warning that is emitted when a closed type family has a branch which is inaccessible due to a more general, prior branch.Example: type family F a where F a = Int F Bool = Bool Test cases: T9085, T14066a, T9085, T6018, tc265,A type which was expected to have a fixed runtime representation does not have a fixed runtime representation.Example:data D (a :: TYPE r) = MkD aTest cases: T11724, T18534, RepPolyPatSynArg, RepPolyPatSynUnliftedNewtype, RepPolyPatSynRes, T20423TcRnImplicitLift is a warning (controlled with -Wimplicit-lift) that occurs when a Template Haskell quote implicitly uses lift.Example: warning1 :: Lift t => t -> Q Exp warning1 x = [| x |]Test cases: th/T17804TcRnUnusedPatternBinds is a warning (controlled with -Wunused-pattern-binds) that occurs if a pattern binding binds no variables at all, unless it is a lone wild-card pattern, or a banged pattern.Example: Just _ = rhs3 -- Warning: unused pattern binding (_, _) = rhs4 -- Warning: unused pattern binding _ = rhs3 -- No warning: lone wild-card pattern !() = rhs4 -- No warning: banged pattern; behaves like seq+Test cases: rename/{T13646,T17c,T17e,T7085}TcRnUnusedQuantifiedTypeVar is a warning that occurs if there are unused quantified type variables.,Examples: f :: forall a. Int -> CharTest cases: renameshould_compile-ExplicitForAllRules1 renameshould_compileT5331TcRnDodgyImports is a group of warnings (controlled with -Wdodgy-imports).See  for the different warnings.TcRnDodgyExports is a warning (controlled by -Wdodgy-exports) that occurs when an export of the form 'T(..)' for a type constructor T0 does not actually export anything beside T itself.Example: module Foo ( T(..) -- Warning: T is a type synonym , A(..) -- Warning: A is a type family , C(..) -- Warning: C is a data family ) wheretype T = Int type family A :: * -> * data family C :: * -> *Test cases: warningsshould_compileDodgyExports01TcRnMissingImportList is a warning (controlled by -Wmissing-import-lists) that occurs when an import declaration does not explicitly list all the names brought into scope.Test cases: renameshould_compileT4489When a module marked trustworthy or unsafe (using -XTrustworthy or -XUnsafe) is compiled with a plugin, the TcRnUnsafeDueToPlugin warning (controlled by -Wunsafe) is used as the reason the module was inferred to be unsafe. This warning is not raised if the -fplugin-trustworthy flag is passed.Test cases: plugins/T19926TcRnModMissingRealSrcSpan is an error that occurs when compiling a module that lacks an associated .Test cases: NoneTcRnIdNotExportedFromModuleSig is an error pertaining to backpack that occurs when an identifier required by a signature is not exported by the module or signature that is being used as a substitution for that signature.Example(s): NoneTest cases: backpack should_fail bkpfail36TcRnIdNotExportedFromLocalSig is an error pertaining to backpack that occurs when an identifier which is necessary for implementing a module signature is not exported from that signature.Example(s): NoneTest cases: backpack should_fail#bkpfail30 backpack should_fail#bkpfail31 backpack should_fail bkpfail34TcRnShadowedName is a warning (controlled by -Wname-shadowing) that occurs whenever an inner-scope value has the same name as an outer-scope value, i.e. the inner value shadows the outer one. This can catch typographical errors that turn into hard-to-find bugs. The warning is suppressed for names beginning with an underscore.Examples(s): f = ... let f = id in ... f ... -- NOT OK, f is shadowed f x = do { _ignore <- this; _ignore <- that; return (the other) } -- suppressed via underscoreTest cases: typecheckshould_compileT10971a renameshould_compilern039 renameshould_compilern064 renameshould_compileT1972 rename should_failT2723 renameshould_compile () where pattern P = () -- not valid, it can't be local, it must be defined at top-level.Test cases: patsyn should_faillocalTcRnLinearPatSyn is an error that occurs whenever a pattern synonym signature uses a field that is not unrestricted.Example(s): NoneTest cases: linear should_fail LinearPatSyn2TcRnEmptyRecordUpdate is an error that occurs whenever a record is updated without specifying any field. Examples(s):$(deriveJSON defaultOptions{} ''Bad) -- not ok, no fields selected for update of defaultOptionsTest cases: th/T12788TcRnIllegalFieldPunning is an error that occurs whenever field punning is used without the NamedFieldPuns extension enabled. Examples(s):data Foo = Foo { a :: Int }foo :: Foo -> Int foo Foo{a} = a -- Not ok, punning used without extension.Test cases: parser should_failRecordDotSyntaxFail12TcRnIllegalWildcardsInRecord is an error that occurs whenever wildcards (..) are used in a record without the relevant extension being enabled. Examples(s):data Foo = Foo { a :: Int }foo :: Foo -> Int foo Foo{..} = a -- Not ok, wildcards used without extension.Test cases: parser should_failRecordWildCardsFailTcRnIllegalWildcardInType is an error that occurs when a wildcard appears in a type in a location in which wildcards aren't allowed. Examples:Type synonyms: type T = _!Class declarations and instances: class C _ instance C _Standalone kind signatures:type D :: _ data DTest cases: ExtraConstraintsWildcardInTypeSplice2 ExtraConstraintsWildcardInTypeSpliceUsed ExtraConstraintsWildcardNotLast ExtraConstraintsWildcardTwice NestedExtraConstraintsWildcard NestedNamedExtraConstraintsWildcard PartialClassMethodSignature PartialClassMethodSignature2 T12039 T13324_fail1 UnnamedConstraintWildcard1 UnnamedConstraintWildcard2 WildcardInADT1 WildcardInADT2 WildcardInADT3 WildcardInADTContext1 WildcardInDefault WildcardInDefaultSignature WildcardInDeriving WildcardInForeignExport WildcardInForeignImport WildcardInGADT1 WildcardInGADT2 WildcardInInstanceHead WildcardInInstanceSig WildcardInNewtype WildcardInPatSynSig WildcardInStandaloneDeriving WildcardInTypeFamilyInstanceRHS WildcardInTypeSynonymRHS saks_fail003 T15433aTcRnIllegalNamedWildcardInTypeArgument is an error that occurs when a named wildcard is used in a required type argument.Example:vfun :: forall (a :: k) -> () x = vfun _nwc -- ^^^^ -- named wildcards not allowed in type arguments$Test cases: T23738_fail_wildTcRnDuplicateFieldName is an error that occurs whenever there are duplicate field names in a single record. Examples(s):data R = MkR { x :: Int, x :: Bool } f r = r { x = 3, x = 4 }Test cases: T21959.TcRnIllegalViewPattern is an error that occurs whenever the ViewPatterns syntax is used but the ViewPatterns language extension is not enabled..Examples(s): data Foo = Foo { a :: Int }8foo :: Foo -> Int foo (a -> l) = l -- not OK, the  ViewPattern extension is not enabled.Test cases: parser should_failViewPatternsFailTcRnCharLiteralOutOfRange is an error that occurs whenever a character is out of range.Examples(s): NoneTest cases: NoneTcRnNegativeNumTypeLiteral is an error that occurs whenever a type-level number literal is negative. type Neg = -1/Test cases: th/T8412 typecheck should_failT8306TcRnIllegalWildcardsInConstructor is an error that occurs whenever the record wildcards '..'6 are used inside a constructor without labeled fields.Examples(s): NoneTest cases: rename should_failT9815.hs rename should_failT9815b.hs rename should_failT9815ghci.hs rename should_fail T9815bghci.hsTcRnIgnoringAnnotations is a warning that occurs when the source code contains annotation pragmas but the platform in use does not support an external interpreter such as GHCi and therefore the annotations are ignored.Example(s): NoneTest cases: NoneTcRnAnnotationInSafeHaskell is an error that occurs if annotation pragmas are used in conjunction with Safe Haskell.Example(s): NoneTest cases: annotations should_failT10826TcRnInvalidTypeApplication is an error that occurs when a visible type application is used with an expression that does not accept "specified" type arguments.Example(s): foo :: forall {a}. a -> a foo x = x bar :: () bar = let x = foo @Int 42 in ()Test cases: overloadedrecflds should_fail1overloadedlabelsfail03 typecheck should_fail/ExplicitSpecificity1 typecheck should_fail0ExplicitSpecificity10 typecheck should_fail/ExplicitSpecificity2 typecheck should_fail!T17173 typecheck should_failVtaFailExample(s): foo :: forall a. a foo = tagToEnum# 0#Test cases: typecheck should_fail tcfail164=TcRnTagToEnumResTyNotAnEnum is an error that occurs when the  'tagToEnum#' function is given a result type that is not an enumeration type.Example(s): foo :: Int -- not an enumeration TyCon foo = tagToEnum# 0#Test cases: typecheck should_fail tcfail164 Int f x = 2 * x -- binding not allowed:- B.hs-boot type family F a where { F Int = Bool }#- type family equations not allowed- C.hsig bar :: Int -> Int {-# RULES forall x. bar x = x #-} -- RULES not allowed Test cases:bindings: T19781class instance body: nonetype family instance: HsBootFam splice: noneforeign declaration: nonedefault declaration: none RULEs: noneTcRnBootMismatch is a family of errors that occur when there is a mismatch between the hs-boot and hs files. Examples:9- A.hs-boot foo :: Int -> Bool data D = MkD1- A.hs foo :: Int -> Char foo = chrdata D = MkD Int Test cases:missing export: bkpcabal06, bkpfail{01,05,09,16,35}, rnfail{047,055}missing definition: nonemissing instance: T14075#mismatch in exports: bkpfail{03,19}conflicting definitions: bkpcabal02, bkpfail{04,06,07,10,12,133,14,15,17,22,23,25,26,27,41,42,45,47,50,52,53,54}, T19244{a,b}, T23344, ClosedFam3, rnfail055TcRnRecursivePatternSynonym is an error that occurs when a pattern synonym is defined in terms of itself, either directly or indirectly.3Example(s): pattern A = B pattern B = ATest cases: patsyn should_failT16900TcRnPartialTypeSigTyVarMismatch is an error that occurs when a partial type signature attempts to unify two different types.7Example(s): f :: a -> b -> _ f x y = [x, y]Test cases: partial-sigs should_failT14449TcRnPartialTypeSigBadQuantifier is an error that occurs when a type variable being quantified over in the partial type signature of a function gets unified with a type that is free in that function's context.Example(s): foo :: Num a => a -> a foo xxx = g xxx where g :: forall b. Num b => _ -> b g y = xxx + yTest cases: partial-sig should_failT14479TcRnMissingSignature is a warning that occurs when a top-level binding or a pattern synonym does not have a type signature.Controlled by the flags: -Wmissing-signatures -Wmissing-exported-signatures -Wmissing-pattern-synonym-signatures -Wmissing-exported-pattern-synonym-signatures -Wmissing-kind-signatures -Wmissing-poly-kind-signaturesTest cases: T11077 (top-level bindings) T12484 (pattern synonyms) T19564 (kind signatures)TcRnPolymorphicBinderMissingSig is a warning controlled by -Wmissing-local-signatures that occurs when a local polymorphic binding lacks a type signature.Example(s): id a = aTest cases: warningsshould_compileT12574TcRnOverloadedSig is an error that occurs when a binding group conflicts with the monomorphism restriction.Example(s): data T a = T a mono = ... where x :: Applicative f => f a T x = ...Test cases: typecheckshould_compileT11339TcRnTupleConstraintInst is an error that occurs whenever an instance for a tuple constraint is specified.Examples(s): class C m a class D m a f :: (forall a. Eq a => (C m a, D m a)) => m a f = undefined)Test cases: quantified-constraints/T15334TcRnUserTypeError is an error that occurs due to a user's custom type error, which can be triggered by adding a  TypeError< constraint in a type signature or typeclass instance.Examples(s): f :: TypeError (Text "This is a type error") f = undefinedTest cases: typecheck should_fail.CustomTypeErrors02 typecheck should_failCustomTypeErrors03TcRnConstraintInKind is an error that occurs whenever a constraint is specified in a kind.4Examples(s): data Q :: Eq a => Type where {}Test cases: dependent should_failT13895 polykinds/T16263 saks should_fail(saks_fail004 typecheck should_fail#T16059a typecheck should_failT18714TcRnUnboxedTupleTypeFuncArg is an error that occurs whenever an unboxed tuple or unboxed sum type is specified as a function argument, when the appropriate extension (`-XUnboxedTuples` or `-XUnboxedSums`) isn't enabled.Examples(s): -- T15073.hs import T15073a newtype Foo a = MkFoo a deriving P- T15073a.hs class P a where p :: a -> (# a #)Test cases: deriving should_fail$T15073.hs deriving should_fail&T15073a.hs typecheck should_failT16059dTcRnLinearFuncInKind is an error that occurs whenever a linear function is specified in a kind.(Examples(s): data A :: * %1 -> *Test cases: linear should_fail#LinearKind linear should_fail$LinearKind2 linear should_fail LinearKind3TcRnForAllEscapeError is an error that occurs whenever a quantified type's kind mentions quantified type variable.Examples(s): type T :: TYPE (BoxedRep l) data T = MkTTest cases: unlifted-datatypes should_failUnlDataNullaryPolyTcRnVDQInTermType is an error that occurs whenever a visible dependent quantification is specified in the type of a term.Examples(s): a = (undefined :: forall k -> k -> Type) @IntTest cases: dependent should_fail"T15859 dependent should_fail(T16326_Fail1 dependent should_fail(T16326_Fail2 dependent should_fail(T16326_Fail3 dependent should_fail(T16326_Fail4 dependent should_fail(T16326_Fail5 dependent should_fail(T16326_Fail6 dependent should_fail(T16326_Fail7 dependent should_fail(T16326_Fail8 dependent should_fail(T16326_Fail9 dependent should_fail)T16326_Fail10 dependent should_fail)T16326_Fail11 dependent should_fail)T16326_Fail12 dependent should_fail"T17687 dependent should_failT18271TcRnBadQuantPredHead is an error that occurs whenever a quantified predicate lacks a class or type variable head.Examples(s): class (forall a. A t a => A t [a]) => B t where type A t a :: Constraint)Test cases: quantified-constraints/T16474TcRnIllegalTupleConstraint is an error that occurs whenever an illegal tuple constraint is specified.Examples(s): g :: ((Show a, Num a), Eq a) => a -> a g = undefinedTest cases: typecheck should_fail tcfail209aTcRnNonTypeVarArgInConstraint is an error that occurs whenever a non type-variable argument is specified in a constraint.;Examples(s): data T instance Eq Int => Eq TTest cases: ghciscriptsT13202 ghciscriptsT13202a polykinds/T12055a typecheck should_fail"T10351 typecheck should_fail"T19187 typecheck should_fail!T6022 typecheck should_failT8883TcRnIllegalImplicitParam is an error that occurs whenever an illegal implicit parameter is specified.Examples(s): type Bla = ?x::Int data T = T instance Bla => Eq T8Test cases: polykinds/T11466 typecheck should_fail!T8912 typecheck should_fail%tcfail041 typecheck should_fail%tcfail211 typecheck should_failtcrun045TcRnIllegalConstraintSynonymOfKind is an error that occurs whenever an illegal constraint synonym of kind is specified.Examples(s): type Showish = Show f :: (Showish a) => a -> a f = undefinedTest cases: typecheck should_fail tcfail209TcRnOversaturatedVisibleKindArg is an error that occurs whenever an illegal oversaturated visible kind argument is specified.Examples(s): type family F2 :: forall (a :: Type). Type where F2 @a = Maybe aTest cases: typecheck should_fail"T15793 typecheck should_failT16255TcRnForAllRankErr is an error that occurs whenever an illegal ranked type is specified.Examples(s): foo :: (a,b) -> (a~b => t) -> (a,b) foo p x = pTest cases: - ghci should_runT15806 - indexed-types should_fail SimpleFail15 - typecheck should_failT11355 - typecheck should_failT12083a - typecheck should_failT12083b - typecheck should_failT16059c - typecheck should_failT16059e - typecheck should_failT17213 - typecheck should_failT18939_Fail - typecheck should_failT2538 - typecheck should_failT5957 - typecheck should_failT7019 - typecheck should_failT7019a - typecheck should_failT7809 - typecheck should_failT9196 - typecheck should_failtcfail127 - typecheck should_failtcfail184 - typecheck should_failtcfail196 - typecheck should_fail tcfail197TcRnSimplifiableConstraint is a warning triggered by the occurrence of a simplifiable constraint in a context, when MonoLocalBinds is not enabled.Examples(s): simplifiableEq :: Eq (a, a) => a -> a -> Bool simplifiableEq = undefined#Test cases: - indexed-typesshould_compileT15322 - partial-sigsshould_compile%SomethingShowable - typecheckshould_compileT13526TcRnArityMismatch is an error that occurs when a type constructor is supplied with fewer arguments than required.'Examples(s): f Left = undefinedTest cases: - backpack should_failbkpfail25.bkp - ghci should_failT16013 - ghci should_failT16287 - indexed-types should_failBadSock - indexed-types should_fail3T9433 - module/mod60 - ndexed-types should_failT2157 - parser should_fail(ParserNoBinaryLiterals2 - parser should_fail(ParserNoBinaryLiterals3 - patsyn should_fail5T12819 - polykinds/T10516 - typecheck should_failT12124 - typecheck should_failT15954 - typecheck should_failT16874 - typecheck should_failtcfail100 - typecheck should_failtcfail101 - typecheck should_failtcfail107 - typecheck should_failtcfail129 - typecheck should_fail tcfail187TcRnIllegalClassInstance is a collection of diagnostics that arise from an invalid class or family instance declaration.See .TcRnMonomorphicBindings is a warning (controlled by -Wmonomorphism-restriction) that arises when the monomorphism restriction applies to the given bindings.Examples(s): {-# OPTIONS_GHC -Wmonomorphism-restriction #-}bar = 10foo :: Int foo = bar&main :: IO () main = print foo)The example above emits the warning (for bar), because without monomorphism restriction the inferred type for bar: is 'bar :: Num p => p'. This warning tells us that if= we were to enable '-XMonomorphismRestriction' we would make bar less polymorphic, as its type would become 'bar :: Int', so GHC warns us about that.Test cases: typecheckshould_compileT13785TcRnOrphanInstance is a warning (controlled by -Worphans) that arises when a typeclass instance or family instance is an "orphan", i.e. if it appears in a module in which neither the class/family nor the type being instanced are declared in the same module.Examples(s): NoneTest cases: warningsshould_compile!T9178 typecheckshould_compileT4912TcRnFunDepConflict is an error that occurs when there are functional dependencies conflicts between instance declarations.Examples(s): NoneTest cases: typecheck should_fail!T2307 typecheck should_fail%tcfail096 typecheck should_fail tcfail202TcRnDupInstanceDecls is an error that occurs when there are duplicate instance declarations.Examples(s): class Foo a where foo :: a -> Int)instance Foo Int where foo = id/instance Foo Int where foo = const 42Test cases: cabalT12733"T12733 typecheck should_fail%tcfail035 typecheck should_fail$tcfail023 backpack should_fail%bkpfail18 typecheck should_fail+TcNullaryTCFail typecheck should_fail%tcfail036 typecheck should_failtcfail073 module/mod51 module/mod52 module/mod44TcRnConflictingFamInstDecls is an error that occurs when there are conflicting family instance declarations.Examples(s): None.Test cases: indexed-types should_fail4ExplicitForAllFams4b indexed-types should_fail&NoGood indexed-types should_fail$Over indexed-types should_fail1OverDirectThisMod indexed-types should_fail3OverIndirectThisMod indexed-types should_fail-SimpleFail11a indexed-types should_fail-SimpleFail11b indexed-types should_fail-SimpleFail11c indexed-types should_fail-SimpleFail11d indexed-types should_fail,SimpleFail2a indexed-types should_fail,SimpleFail2b indexed-types should_fail-T13092/T13092 indexed-types should_fail/T13092c/T13092c indexed-types should_fail&T14179 indexed-types should_fail&T2334A indexed-types should_fail%T2677 indexed-types should_fail&T3330b indexed-types should_fail%T4246 indexed-types should_fail&T7102a indexed-types should_failT9371 polykinds/T7524 typecheck should_failUnliftedNewtypesOverlapTcRnFamInstNotInjective is a collection of errors that arise from a type family equation violating the injectivity annotation.See .TcRnBangOnUnliftedType is a warning (controlled by -Wredundant-strictness-flags) that occurs when a strictness annotation is applied to an unlifted type.Example(s): data T = MkT !Int# -- Strictness flag has no effect on unlifted typesTest cases: typecheckshould_compile"T20187a typecheckshould_compileT20187bTcRnLazyBangOnUnliftedType is a warning (controlled by -Wredundant-strictness-flags) that occurs when a lazy annotation is applied to an unlifted type.Example(s): data T = MkT ~Int# -- Lazy flag has no effect on unlifted typesTest cases: typecheckshould_compile"T21951a typecheckshould_compileT21951bTcRnMultipleDefaultDeclarations is an error that occurs when a module has more than one default declaration for the same class.Example: default (Integer, Int) -- implicitly applies to Num default (Double, Float) -- 2nd default declaration not allowedText cases: module/mod58TcRnWarnClashingDefaultImports is a warning that occurs when a module imports more than one default declaration for the same class, and they are not all subsumed by one of them nor by a local  `default` declaration.;See Note [Named default declarations] in GHC.Tc.Gen.DefaultTest cases: default/Import07.hsTcRnBadDefaultType is an error that occurs when a type used in a default declaration does not have an instance for any of the applicable classes..Example(s): data Foo default (Foo)Test cases: typecheck should_failT11974bTcRnPatSynBundledWithNonDataCon is an error that occurs when a module's export list bundles a pattern synonym with a type that is not a proper `data` or  `newtype` construction.Example(s): module Foo (MyClass(.., P)) where pattern P = Nothing class MyClass a where foo :: a -> IntTest cases: patsyn should_fail export-classTcRnPatSynBundledWithWrongType is an error that occurs when the export list of a module has a pattern synonym bundled with a type that does not match the type of the pattern synonym.Example(s): module Foo (R(P,x)) where data Q = Q Int data R = R pattern P{x} = Q xText cases: patsyn should_fail)export-ps-rec-sel patsyn should_fail+export-type-synonym patsyn should_fail export-type0TcRnDupeModuleExport is a warning controlled by -Wduplicate-exports that occurs when a module appears more than once in an export list.Example(s): module Foo (module Bar, module Bar) import BarText cases: NoneTcRnExportedModNotImported is an error that occurs when an export list contains a module that is not imported.Example(s): NoneText cases: module/mod135 module/mod8 rename should_fail#rnfail028 backpack should_fail bkpfail48TcRnNullExportedModule is a warning controlled by -Wdodgy-exports that occurs when an export list contains a module that has no exports.Example(s): module Foo (module Bar) where import Bar ()Test cases: NoneTcRnMissingExportList is a warning controlled by -Wmissing-export-lists that occurs when a module does not have an explicit export list.Example(s): NoneTest cases: typecheck should_failMissingExportList03TcRnExportHiddenComponents is an error that occurs when an export contains constructor or class methods that are not visible.Example(s): NoneTest cases: NoneTcRnExportHiddenDefault is an error that occurs when an export contains a class default (with language extension NamedDefaults) that is not visible.Example(s): NoneTest cases: default/fail06.hsTcRnDuplicateExport is a warning (controlled by -Wduplicate-exports) that occurs when an identifier appears in an export list more than once.Example(s): NoneTest cases: module/MultiExport module/mod128 module/mod14 module/mod5 overloadedrecflds should_fail(DuplicateExports patsynshould_compileT11959TcRnExportedParentChildMismatch is an error that occurs when an export is bundled with a parent that it does not belong toExample(s): module Foo (T(a)) where data T a = TrueTest cases: module/T11970 module/T11970B module/mod17 module/mod3 overloadedrecflds should_failNoParentTcRnConflictingExports is an error that occurs when different identifiers that have the same name are being exported by a module.Example(s): module Foo (Bar.f, module Baz) where import qualified Bar (f) import Baz (f)Test cases: module/mod131 module/mod142 module/mod143 module/mod144 module/mod145 module/mod146 module/mod150 module/mod155 overloadedrecflds should_fail)T14953 overloadedrecflds should_fail/overloadedrecfldsfail10 rename should_fail!rnfail029 rename should_fail$rnfail040 typecheck should_fail#T16453E2 typecheck should_fail$tcfail025 typecheck should_fail tcfail026TcRnDuplicateFieldExport is an error that occurs when a module exports multiple record fields with the same name, without enabling DuplicateRecordFields.Example:module M1 where data D1 = MkD1 { foo :: Int } module M2 where data D2 = MkD2 { foo :: Int } module M ( D1(..), D2(..) ) where import module M1 import module M2Test case: overloadedrecflds should_failoverloadedrecfldsfail10TcRnAmbiguousRecordUpdate is a warning, controlled by -Wambiguous-fields, which occurs when a user relies on the type-directed disambiguation mechanism to disambiguate a record update. This will not be supported by -XDuplicateRecordFields in future releases. Example(s):data Person = MkPerson { personId :: Int, name :: String } data Address = MkAddress { personId :: Int, address :: String } bad1 x = x { personId = 4 } :: Person -- ambiguous bad2 (x :: Person) = x { personId = 4 } -- ambiguous good x = (x :: Person) { personId = 4 } -- not ambiguousTest cases: overloadedrecflds should_failoverloadedrecfldsfail06TcRnMissingFields is a warning controlled by -Wmissing-fields occurring when the intialisation of a record is missing one or more (lazy) fields.Example(s): data Rec = Rec { a :: Int, b :: String, c :: Bool } x = Rec { a = 1, b = "two" } -- missing field cTest cases: deSugarshould_compileT13870 deSugarshould_compileds041 patsynshould_compileT11283 renameshould_compileT5334 renameshould_compileT12229 renameshould_compile T5892a warnings should_fail WerrorFail2TcRnFieldUpdateInvalidType is an error occurring when an updated field's type mentions something that is outside the universally quantified variables of the data constructor, such as an existentially quantified type.Example(s): data X = forall a. MkX { f :: a } x = (MkX ()) { f = False }Test cases: patsyn should_fail+records-exquant typecheck should_failT3323TcRnMissingStrictFields is an error occurring when a record field marked as strict is omitted when constructing said record.Example(s): data R = R { strictField :: !Bool, nonStrict :: Int } x = R { nonStrict = 1 }Test cases: typecheck should_fail T18869 typecheck should_fail#tcfail085 typecheck should_fail tcfail112TcRnAmbiguousFieldInUpdate is an error that occurs when a field in a record update clashes with another field or top-level function of the same name, and the user hasn't enabled -XDisambiguateRecordFields.Example:{-# LANGUAGE NoFieldSelectors #-} {-# LANGUAGE NoDisambiguateRecordFields #-} module M wheredata A = MkA { fld :: Int }!fld :: Bool fld = Falsef r = r { fld = 3 }˜TcRnBadRecordUpdate is an error when a regular (non-overloaded) record update cannot be pinned down to any one parent.4The problem with the record update is stored in the Ɨ field. Example(s):data R1 = R1 { x :: Int } data R2 = R2 { x :: Int } update r = r { x = 1 } -- ambiguousdata R1 = R1 { x :: Int, y :: Int } data R2 = R2 { y :: Int, z :: Int } update r = r { x = 1, y = 2, z = 3 } -- no parent has all the fieldsTest cases: overloadedrecflds should_fail9overloadedrecfldsfail01 overloadedrecflds should_fail9overloadedrecfldsfail01 overloadedrecflds should_failoverloadedrecfldsfail14ØTcRnStaticFormNotClosed is an error pertaining to terms that are marked static using the -XStaticPointers extension but which are not closed terms.Example(s): f x = static xTest cases: rename should_fail-RnStaticPointersFail01 rename should_failRnStaticPointersFail03ĘTcRnUselessTypeable is a warning (controlled by -Wderiving-typeable) that occurs when trying to derive an instance of the  class. Deriving  is no longer necessary (hence the "useless") as all types automatically derive  in modern GHC versions.Example(s): None.Test cases: warningsshould_compileDerivingTypeableŘTcRnDerivingDefaults is a warning (controlled by -Wderiving-defaults) that occurs when both DeriveAnyClass and GeneralizedNewtypeDeriving2 are enabled, and therefore GHC defaults to DeriveAnyClass/, which might not be what the user wants.Example(s): None.Test cases: typecheckshould_compile!T15839a derivingshould_compileT16179ƘTcRnNonUnaryTypeclassConstraint is an error that occurs when GHC encounters a non-unary constraint when trying to derive a typeclass.Example(s): class A deriving instance A data B deriving A -- We cannot derive A, is not unary (i.e. 'class A a').Test cases: deriving should_failT7959 deriving should_fail$drvfail005 deriving should_fail$drvfail009 deriving should_fail drvfail006ǘTcRnPartialTypeSignatures is a warning (controlled by -Wpartial-type-signatures) that occurs when a wildcard '_' is found in place of a type in a signature or a type class derivation5Example(s): foo :: _ -> Int foo = ...!deriving instance _ => Eq (Foo a)Test cases: dependentshould_compile!T11241 dependentshould_compile!T15076 dependentshould_compile#T14880-2 typecheckshould_compile!T17024 typecheckshould_compile$T10072 partial-sigs should_fail(TidyClash2 partial-sigs should_fail.Defaulting1MROff partial-sigs should_fail:WildcardsInPatternAndExprSig partial-sigs should_fail$T10615 partial-sigs should_fail%T14584a partial-sigs should_fail'TidyClash partial-sigs should_fail$T11122 partial-sigs should_fail$T14584 partial-sigs should_fail$T10045 partial-sigs should_fail;PartialTypeSignaturesDisabled partial-sigs should_fail$T10999 partial-sigs should_failExtraConstraintsWildcardInExpressionSignature partial-sigs should_failExtraConstraintsWildcardInPatternSplice partial-sigs should_fail4WildcardInstantiations partial-sigs should_run$T15415 partial-sigsshould_compile$T10463 partial-sigsshould_compile%T15039a partial-sigsshould_compile%T16728b partial-sigsshould_compile%T15039c partial-sigsshould_compile$T10438 partial-sigsshould_compile)SplicesUsed partial-sigsshould_compile$T18008 partial-sigsshould_compile*ExprSigLocal partial-sigsshould_compile%T11339a partial-sigsshould_compile$T11670 partial-sigsshould_compile;WarningWildcardInstantiations partial-sigsshould_compile$T16728 partial-sigsshould_compile$T12033 partial-sigsshould_compile%T15039b partial-sigsshould_compile$T10403 partial-sigsshould_compile$T11192 partial-sigsshould_compile%T16728a partial-sigsshould_compile)TypedSplice partial-sigsshould_compile%T15039d partial-sigsshould_compile$T11016 partial-sigsshould_compile'T13324_compile2 linear should_failLinearPartialSig polykinds/T14265 polykinds/T14172ȘTcRnCannotDeriveInstance is an error that occurs every time a typeclass instance can't be derived. The 9 will contain the specific reason this error arose.Example(s): None.Test cases: genericsT10604.T10604_no_PolyKinds deriving should_fail%drvfail009 deriving should_fail+drvfail-functor2 deriving should_fail'T10598_fail3 deriving should_fail-deriving-via-fail2 deriving should_fail,deriving-via-fail deriving should_failT16181ɘTcRnLazyGADTPattern is an error that occurs when a user writes a nested GADT pattern match inside a lazy (~) pattern.Test case: gadt/lazypatʘTcRnArrowProcGADTPattern is an error that occurs when a user writes a GADT pattern inside arrow proc notation.Test case: arrows should_fail arrowfail004.˘TcRnCapturedTermName is a warning (controlled by -Wterm-variable-capture) that occurs when an implicitly quantified type variable's name is already used for a term. Example: a = 10 f :: a -> aTest cases: T22513a T22513b T22513c T22513d T22513e T22513f T22513g T22513h T22513i̘TcRnTypeEqualityOutOfScope is a warning (controlled by -Wtype-equality-out-of-scope) that occurs when the type equality (a ~ b) is not in scope.Test case: warningsshould_compileT18862b͘TcRnTypeEqualityRequiresOperators is a warning (controlled by -Wtype-equality-requires-operators) that occurs when the type equality (a ~ b) is used without the TypeOperators extension.Example: {-# LANGUAGE NoTypeOperators #-} f :: (a ~ b) => a -> bTest case: T18862aΘTcRnIllegalTypeOperator is an error that occurs when a type operator is used without the TypeOperators extension.Example: {-# LANGUAGE NoTypeOperators #-} f :: Vec a n -> Vec a m -> Vec a (n + m)Test case: T12811ϘTcRnIllegalTypeOperatorDecl is an error that occurs when a type or class operator is declared without the TypeOperators extension..See Note [Type and class operator definitions]Example: {-# LANGUAGE Haskell2010 #-} {-# LANGUAGE MultiParamTypeClasses #-}module T3265 wheredata a :+: b = Left a | Right bclass a :*: b where {}Test cases: T3265, tcfail173ИTcRnGADTMonoLocalBinds is a warning controlled by -Wgadt-mono-local-binds that occurs when pattern matching on a GADT when -XMonoLocalBinds is off.Example(s): NoneTest cases: T20485, T20485aјThe TcRnNotInScope constructor is used for various not-in-scope errors. See ה for more details. ҘTcRnTermNameInType is an error that occurs when a term-level identifier is used in a type.Example:import qualified Prelude4bad :: Prelude.fst (Bool, Float) bad = FalseTest cases: T21605{c,d}ӘTcRnUntickedPromotedThing is a warning (controlled with -Wunticked-promoted-constructors) that is triggered by an unticked occurrence of a promoted data constructor. Examples:data A = MkA type family F (a :: A) where { F MkA = Bool }type B = [ Int, Bool ]Test cases: T9778, T19984.ԘTcRnIllegalBuiltinSyntax is an error that occurs when built-in syntax appears in an unexpected location, e.g. as a data constructor or in a fixity declaration. Examples: infixl 5 : data P = (,)/Test cases: rnfail042, T14907b, T15124, T15233.՘TcRnWarnDefaulting is a warning (controlled by -Wtype-defaults) that is triggered whenever a Wanted typeclass constraint is solving through the defaulting of a type variable.Example:one = show 1 -- We get Wanteds Show a0, Num a0, and default a0 to Integer.Test cases: none (which are really specific to defaulting), but see e.g. tcfail204.֘6TcRnIncorrectNameSpace is an error that occurs when a  is used in the incorrect  NameSpace, e.g. a type constructor or class used in a term, or a term variable used in a type.Example:list2 = $( conE ''(:) appE litE (IntegerL 5) appE conE '[] ) -- ^^^^^ -- should use a single quotation tick, i.e. '(:)Test cases: T20884.טTcRnForeignImportPrimExtNotSet is an error occurring when a foreign import is declared using the prim calling convention without having turned on the -XGHCForeignImportPrim extension.Example(s): foreign import prim "foo" foo :: ByteArray# -> (# Int#, Int# #)Test cases: ffi should_failT20116ؘTcRnForeignImportPrimSafeAnn is an error declaring that the safe/unsafe annotation should not be used with prim foreign imports.Example(s): foreign import prim unsafe "my_primop_cmm" :: ...Test cases: None٘TcRnForeignFunctionImportAsValue is an error explaining that foreign value) imports cannot have function types.Example(s): foreign import capi "math.h value sqrt" f :: CInt -> CIntTest cases: ffi should_failcapi_value_functionژ IO ())Test cases: ffishould_compileT1357ۘTcRnIllegalForeignDeclBackend is an error occurring when a foreign import declaration is not compatible with the code generation backend being used.Example(s): NoneTest cases: NoneܘTcRnUnsupportedCallConv informs the user that the calling convention specified for a foreign export declaration is not compatible with the target platform. It is a warning controlled by !-Wunsupported-calling-conventions in the case of stdcall& but is otherwise considered an error.Example(s): NoneTest cases: NoneݘTcRnIllegalForeignType is an error for when a type appears in a foreign function signature that is not compatible with the FFI.Example(s): NoneTest cases: ffi should_failT3066 ffi should_failccfail004 ffi should_failT10461 ffi should_failT7506 ffi should_fail!T5664 safeHaskellghcip6 safeHaskell safeLanguageSafeLang08 ffi should_failT16702 linear should_failLinearFFI ffi should_failT7243ޘTcRnInvalidCIdentifier indicates a C identifier that is not valid.Example(s): foreign import prim safe "not valid" cmm_test2 :: Int# -> Int#Test cases: th/T10638ߘTcRnExpectedValueId is an error occurring when something that is not a value identifier is used where one is expected.Example(s): noneTest cases: noneTcRnRecSelectorEscapedTyVar is an error indicating that a record field selector containing an existential type variable is used as a function rather than in a pattern match.Example(s): data Rec = forall a. Rec { field :: a } field (Rec True)Test cases: patsyn should_fail)records-exquant typecheck should_failT3176TcRnPatSynNotBidirectional is an error for when a non-bidirectional pattern synonym is used as a constructor.Example(s): pattern Five :: Int pattern Five <- 5 five = FiveTest cases: patsyn should_fail,records-no-uni-update patsyn should_failrecords-no-uni-update2TcRnIllegalDerivingItem is an error for when something other than a type class appears in a deriving statement.(Example(s): data X = X deriving IntTest cases: deriving should_failT5922TcRnIllegalDefaultClass is an error for when something other than a type class appears in a default declaration after the keyword.&Example(s): default Integer (Int)Test cases: default/fail01TcRnIllegalNamedDefault is an error for specifying an explicit default class name without -XNamedDefaults.&Example(s): default Num (Integer)Test cases: default/fail02TcRnUnexpectedAnnotation indicates the erroroneous use of an annotation such as strictness, laziness, or unpacking.Example(s): data T = T { t :: Maybe {-# UNPACK #-} Int } data C = C { f :: !IntMap Int }Test cases: parser should_fail,unpack_inside_type typecheck should_failT7210 rename should_failT22478bTcRnIllegalRecordSyntax is an error indicating an illegal use of record syntax.0Example(s): data T = T Int { field :: Int }Test cases: rename should_failT7943 rename should_failT9077 rename should_failT22478bTcRnInvalidVisibleKindArgument is an error for a kind application on a target type that cannot accept it.Example(s): bad :: Int Type bad = 1 type Foo :: forall a {b}. a -> b -> b type Foo x y = y type Bar = Foo Bool @Int True 42Test cases: indexed-types should_fail&T16356_Fail3 typecheck should_fail.ExplicitSpecificity7 typecheck should_fail!T12045b typecheck should_fail!T12045c typecheck should_fail!T15592a typecheck should_failT15816TcRnTooManyBinders is an error for a type constructor that is declared with more arguments then its kind specifies.Example(s): type T :: Type -> (Type -> Type) -> Type data T a (b :: Type -> Type) x1 (x2 :: Type -> Type)Test cases: saks should_fail saks_fail008TcRnDifferentNamesForTyVar is an error that indicates different names being used for the same type variable.Example(s): data SameKind :: k -> k -> * data Q (a :: k1) (b :: k2) c = MkQ (SameKind a b)Test cases: polykinds/T11203 polykinds/T11821a saks should_fail T20916 typecheck should_fail!T17566b typecheck should_failT17566cTcRnDisconnectedTyVar is an error for a data declaration that has a kind signature, where the implicitly-bound type type variables can't be matched up unambiguously with the ones from the signature. See Note [Disconnected type variables] in GHC.Tc.Gen.HsType.Test cases: T24083TcRnInvalidReturnKind is an error for a data declaration that has a kind signature with an invalid result kind..Example(s): data family Foo :: ConstraintTest cases: typecheck should_fail!T14048b typecheck should_fail:UnliftedNewtypesConstraintFamily typecheck should_fail T12729 typecheck should_fail T15883 typecheck should_fail!T16829a typecheck should_fail!T16829b typecheck should_fail4UnliftedNewtypesNotEnabled typecheck should_fail tcfail079TcRnUnexpectedKindVar is an error that occurs when the user tries to use kind variables without -XPolyKinds.0Example: f :: forall k a. Proxy (a :: k)Test cases: polykinds/BadKindVar polykinds/T14710 saks should_failT16722TcRnIllegalKind is used for a various illegal kinds errors includingExample: type T :: forall k. Type -- without emabled -XPolyKindsTest cases: polykinds/T16762bTcRnClassKindNotConstraint is an error for a type class that has a kind that is not equivalent to Constraint.6Example(s): type C :: Type -> Type class C aTest cases: saks should_failT16826TcRnUnpromotableThing is an error that occurs when the user attempts to use the promoted version of something which is not promotable.Example(s): data T :: T -> * data X a where MkX :: Show a => a -> X a foo :: Proxy ('MkX 'True) foo = ProxyTest cases: dependent should_fail'PromotedClass dependent should_fail&T14845_fail1 dependent should_fail&T14845_fail2 dependent should_fail T15215 dependent should_fail!T13780c dependent should_failT15245 polykinds/T5716 polykinds/T5716a polykinds/T6129 polykinds/T7433 patsyn should_failT11265 patsyn should_failT9161-1 patsyn should_fail!T9161-2 dependent should_failSelfDep polykinds/PolyKinds06 polykinds/PolyKinds07 polykinds/T13625 polykinds/T15116 polykinds/T15116a saks should_failT16727a saks should_failT16727b rename should_failT12686 rename should_failT16635a rename should_failT16635b rename should_failT16635cTcRnIllegalTermLevelUse is an error that occurs when the user attempts to use a type-level entity at the term-level.Examples: f x = Int -- illegal use of a type constructor g (Proxy :: Proxy a) = a -- illegal use of a type variableNote that the namespace cannot be used to determine if a name refers to a type-level entity:{-# LANGUAGE RequiredTypeArguments #-} bad :: forall (a :: k) -> k bad t = t The name t is assigned the varName namespace but stands for a type variable that cannot be used at the term level.?Test cases: T18740a, T18740b, T23739_fail_ret, T23739_fail_caseTcRnMatchesHaveDiffNumArgs is an error occurring when something has matches that have different numbers of arguments2Example(s): foo x = True foo x y = FalseTest cases: rename should_fail#rnfail045 typecheck should_fail T20768_failTcRnUnexpectedPatSigType is an error occurring when there is a type signature in a pattern without -XScopedTypeVariables extension%Examples: f (a :: Bool) = ...Test case: rename should_failT11663TcRnIllegalKindSignature is an error occurring when there is a kind signature without -XKindSignatures extension,Examples: data Foo (a :: Nat) = ....Test case: parser should_fail readFail036TcRnDataKindsError is an error occurring when there is an illegal type or kind, probably required -XDataKinds and is used without the enabled extension.This error can occur in both the renamer and the typechecker. The field of type F (6 5) 0 reflects this: this field will contain a N value if the error occurred in the renamer, and this field will contain a O6 value if the error occurred in the typechecker. Examples:type Foo = [Nat, Char]type Bar = [Int, String]Test cases: linear should_failT18888 parser should_failreadFail001 polykinds/T7151 polykinds/T7433 rename should_failT13568 rename should_failT22478e th/TH_Promoted1Tuple typecheckshould_compile%tcfail094 typecheckshould_compile#T22141a typecheckshould_compile#T22141b typecheckshould_compile#T22141c typecheckshould_compile#T22141d typecheckshould_compile#T22141e typecheckshould_compile#T22141f typecheckshould_compile#T22141g typecheck should_fail#T20873c typecheck should_failT20873dTcRnCannotBindScopedTyVarInPatSig is an error stating that scoped type variables cannot be used in pattern bindings.!Example(s): let (x :: a) = 5Test cases: typecheckshould_compiletc141TcRnCannotBindTyVarsInPatBind is an error for when type variables are introduced in a pattern binding&Example(s): Just @a x = Just TrueTest cases: typecheck should_fail1TyAppPat_PatternBinding typecheck should_fail"TyAppPat_PatternBindingExistentialTcRnTooManyTyArgsInConPattern is an error occurring when a constructor pattern has more than the expected number of type argumentsExample(s): f (Just Int  Bool x) = xTest cases: typecheck should_fail*TyAppPat_TooMany typecheck should_failT20443bTcRnMultipleInlinePragmas is a warning signifying that multiple inline pragmas reference the same definition.Example(s): {-# INLINE foo #-} {-# INLINE foo #-} foo :: Bool -> Bool foo = idTest cases: noneTcRnUnexpectedPragmas is a warning that occurs when unexpected pragmas appear in the source. Example(s):Test cases: noneTcRnNonOverloadedSpecialisePragma is a warning for a specialise pragma being placed on a definition that is not overloaded.Example(s): {-# SPECIALISE foo :: Bool -> Bool #-} foo :: Bool -> Bool foo = idTest cases: simplCoreshould_compileT8537 typecheckshould_compileT10504TcRnSpecialiseNotVisible is a warning that occurs when the subject of a SPECIALISE pragma has a definition that is not visible from the current module.Example(s): noneTest cases: noneTcRnPragmaWarning is a warning that can happen when usage of something is warned or deprecated by pragma.Test cases: DeprU T5281 T5867 rn050 rn066 (here is a warning, not deprecation) T3303 ExportWarnings1 ExportWarnings2 ExportWarnings3 ExportWarnings4 ExportWarnings5 ExportWarnings6 InstanceWarningsTcRnDifferentExportWarnings is an error that occurs when the warning messages for exports of a name differ between several export items.(Test case: DifferentExportWarningsTcRnIncompleteExportWarnings is a warning (controlled by -Wincomplete-export-warnings) that occurs when some of the exports of a name do not have an export warning and some do Test case: ExportWarnings6TcRnIllegalHsigDefaultMethods is an error that occurs when a binding for a class default method is provided in a Backpack signature file.Test case: bkpfail40TcRnHsigFixityMismatch is an error indicating that the fixity decl in a Backpack signature file differs from the one in the source file for the same operator.&Test cases: bkpfail37, bkpfail38TcRnHsigShapeMismatch is a group of errors related to mismatches between backpack signatures.TcRnHsigMissingModuleExport is an error indicating that a module doesn't export a name exported by its signature.Test cases: bkpfail01, bkpfail05, bkpfail09, bkpfail16, bkpfail35, bkpcabal06TcRnBadGenericMethod This test ensures that if you provide a "more specific" type signatures for the default method, you must also provide a binding.0Example: {-# LANGUAGE DefaultSignatures #-}class C a where meth :: a default meth :: Num a => a meth = 0Test case: typecheck should_failMissingDefaultMethodBinding.hsTcRnWarningMinimalDefIncomplete is a warning that one must specify which methods must be implemented by all instances.Example: class Cheater a where -- WARNING LINE cheater :: a {-# MINIMAL #-} -- warning!Test case: warningsminimalWarnMinimal.hs:TcRnIllegalQuasiQuotes is an error that occurs when a quasi-quote is used without the QuasiQuotes extension.Example:foo = [myQuoter|x y z|]Test cases: none; the parser fails to parse this if QuasiQuotes is off.TcRnTHError is a family of errors involving Template Haskell. See .TcRnDefaultMethodForPragmaLacksBinding is an error that occurs when a default method pragma is missing an accompanying binding.Test cases: typecheck should_failT5084.hs typecheck should_failT2354.hsTcRnIgnoreSpecialisePragmaOnDefMethod is a warning that occurs when a specialise pragma is put on a default method.Test cases: noneTcRnBadMethodErr is an error that happens when one attempts to provide a method in a class instance, when the class doesn't have a method by that name.Test case: th/T12387:TcRnIllegalNewtype is an error that occurs when a newtype:#Does not have exactly one field, oris non-linear, or is a GADT, or+has a context in its constructor's type, or declaration occurs without the TypeOperators extension.!See Note [Type data declarations]Test case: type-data should_fail TDNoPragma3TcRnTypeDataForbids is an error that occurs when a  type data declaration contains data4 declaration features that are forbidden in a  type data declaration.!See Note [Type data declarations]Test cases: type-data should_failTDDeriving type-data should_failTDRecordsGADT type-data should_failTDRecordsH98 type-data should_fail!TDStrictnessGADT type-data should_failTDStrictnessH98TcRnOrPatBindsVariables is an error that happens when an or-pattern binds term or type variables, e.g. (A @x; B y).Test case: testsuitetests typecheck should_failOr3TcRnUnsatisfiedMinimalDef is a warning that occurs when a class instance is missing methods that are required by the minimal definition.Example: class C a where foo :: a -> a instance C () -- | foo needs to be defined hereTest cases: typecheckprog001$typecheck.prog001 typecheckshould_compiletc126 typecheckshould_compileT7903 typecheckshould_compiletc116 typecheckshould_compiletc175 typecheckshould_compileHasKey typecheckshould_compiletc125 typecheckshould_compiletc078 typecheckshould_compiletc161 typecheck should_failT5051 typecheckshould_compileT21583 backpackshould_compilebkp47 backpack should_failbkpfail25 parsershould_compileT2245 parsershould_compileread014 indexed-typesshould_compileClass3 indexed-typesshould_compileSimple2 indexed-types should_failT7862 derivingshould_compilederiving-1935 derivingshould_compileT9968a derivingshould_compiledrv003 derivingshould_compileT4966 derivingshould_compileT14094 perfcompilerT15304 warningsminimalWarnMinimal simplCoreshould_compilesimpl020 deSugarshould_compileT14546d ghciscriptsT5820 ghciscriptsghci019 is an error that happens when a method in a class instance is given a type signature, but the user has not enabled the  InstanceSigs extension.Test case: module/mod45TcRnNoRebindableSyntaxRecordDot is an error triggered by an overloaded record update without RebindableSyntax enabled. Example(s):Test cases: parser should_failRecordDotSyntaxFail5TcRnNoFieldPunsRecordDot is an error triggered by the use of record field puns in an overloaded record update without enabling NamedFieldPuns./Example(s): print $ a{ foo.bar.baz.quux }Test cases: parser should_failRecordDotSyntaxFail12TcRnIllegalStaticExpression is an error thrown when user creates a static pointer via TemplateHaskell without enabling the StaticPointers extension. Example(s):Test cases: th/T14204TcRnListComprehensionDuplicateBinding is an error triggered by duplicate let-bindings in a list comprehension.2Example(s): [ () | let a = 13 | let a = 17 ]Test cases: typecheck should_fail tcfail092TcRnEmptyStmtsGroup is an error triggered by an empty list of statements in a statement block. For more information, see  Example(s):  () | then ()do proc () -> doTest cases: rename should_failRnEmptyStatementGroup1TcRnLastStmtNotExpr is an error caused by the last statement in a statement block not being an expression. Example(s):do x <- pure () do let x = 5Test cases: rename should_failT6060 parser should_failT3811g parser should_fail readFail028TcRnUnexpectedStatementInContext is an error when a statement appears in an unexpected context (e.g. an arrow statement appears in a list comprehension). Example(s):Test cases: parser should_fail#readFail042 parser should_fail#readFail038 parser should_fail readFail043TcRnIllegalTupleSection is an error triggered by usage of a tuple section without enabling the TupleSections extension.Example(s): (5,)Test cases: rename should_fail rnfail056TcRnIllegalImplicitParameterBindings is an error triggered by binding an implicit parameter in an mdo block.,Example(s): mdo { let { ?x = 5 }; () }Test cases: rename should_failRnImplicitBindInMdoNotationTcRnSectionWithoutParentheses is an error triggered by attempting to use an operator section without parentheses.Example(s): ( x, ())Test cases: rename should_failT2490 rename should_failT5657TcRnBindingOfExistingName is an error triggered by an attempt to rebind built-in syntax, punned list or tuple syntax, or a name quoted via Template Haskell. Examples:data [] data (->) $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []])Test cases: rename should_failT14907b rename should_failT22839 rename should_fail$rnfail042 th/T13968TcRnMultipleFixityDecls is an error triggered by multiple fixity declarations for the same operator. Example(s):infixr 6 $$ infixl 4 $$Test cases: rename should_failRnMultipleFixityFailTcRnIllegalPatternSynonymDecl is an error thrown when a user defines a pattern synonyms without enabling the PatternSynonyms extension.Example:%pattern O :: Int pattern O = 0Test cases: rename should_failRnPatternSynonymFailTcRnIllegalClassBinding is an error triggered by a binding in a class or instance declaration of an illegal form. Examples:class ZeroOne a where zero :: a one :: a instance ZeroOne Int where (zero,one) = (0,1))class C a where pattern P = ()0Test cases: module/mod48 patsyn should_failT9705-1 patsyn should_fail"T9705-2 typecheck should_fail tcfail021TcRnOrphanCompletePragma is an error triggered by a {-# COMPLETE #-} pragma which does not mention any data constructors or pattern synonyms defined in the current module.Test cases: patsyn should_failT13349TcRnEmptyCase is an error thrown when a user uses a case expression with an empty list of alternatives without enabling the EmptyCase extension. Example(s): case () ofTest cases: rename should_failRnEmptyCaseFailTcRnNonStdGuards is a warning thrown when a user uses non-standard guards (e.g. patterns in guards) without enabling the PatternGuards extension. More realistically: the user has explicitly disabled PatternGuards, as it is enabled by default with `-XHaskell2010`. Example(s):f | 5 <- 2 + 3 = ...Test cases: renameshould_compilern049TcRnDuplicateSigDecl is an error triggered by two or more signatures for one entity. Examples::f :: Int -> Bool f :: Int -> Bool f _ = True9g x = x {-# INLINE g #-} {-# NOINLINE g #-}pattern P = () {-# COMPLETE P #-} {-# COMPLETE P #-}0Test cases: module/mod68 parser should_fail(OpaqueParseFail4 patsyn should_failT12165 rename should_fail!rnfail048 rename should_failT5589 rename should_failT7338 rename should_failT7338aTcRnMisplacedSigDecl is an error triggered by the pragma application in the wrong context, like MINIMAL applied to a function or  SPECIALIZE to an instance.Example: f x = x {-# MINIMAL f #-}Test cases: rename should_fail T18138 warningsminimalWarnMinimalFail1TcRnUnexpectedDefaultSig is an error thrown when a user uses default signatures without enabling the DefaultSignatures extension.Example:class C a where m :: a default m :: Num a => a m = 0Test cases: rename should_failRnDefaultSigFailTcRnDuplicateMinimalSig is an error triggered by two or more minimal signatures for one type class.Example:class C where f :: () {-# MINIMAL f #-} {-# MINIMAL f #-}Test cases: rename should_failRnMultipleMinimalPragmaFail is an error that occurs when invisible type variable binders in type declarations are used without enabling the TypeAbstractions extension.Example: {-# LANGUAGE NoTypeAbstractions #-} -- extension disabled data T  k (a :: k) <(j :: Type) (b :: j) ^^ ^^^^^^^^^^^^Test case: T22560_fail_ext is an error that occurs when a wildcard binder is used in a type declaration without enabling the TypeAbstractions extension.Example: {-# LANGUAGE NoTypeAbstractions #-} -- extension disabled type Const a _ = a ^Test case: T23501_fail_ext is an error that occurs when an invisible type variable binder has no corresponding  forall k.- quantifier in the standalone kind signature.Example: type P :: forall a -> Type data P @a = MkP'Test cases: T22560_fail_a T22560_fail_b is an error triggered by attempting to use an invisible type variable binder in a type declaration without a standalone kind signature or a complete user-supplied kind.;Example: data T @k (a :: k) -- No CUSK, no SAKSTest case: T22560_fail_dTcRnDeprecatedInvisTyArgInConPat is a warning that triggers on type applications in constructor patterns when the user has not enabled '-XTypeAbstractions' but instead has enabled both '-XScopedTypeVariables' and '-XTypeApplications'.This warning is a deprecation mechanism that is scheduled until GHC 9.12.TcRnUnexpectedStandaloneDerivingDecl is an error thrown when a user uses standalone deriving without enabling the StandaloneDeriving extension.Example:deriving instance Eq FooTest cases: rename should_failRnUnexpectedStandaloneDerivingTcRnUnusedVariableInRuleDecl is an error triggered by forall'd variable in rewrite rule that does not appear on left-hand sideExample:&{-# RULES "rule" forall a. id = id #-}Test cases: rename should_failExplicitForAllRules2TcRnUnexpectedStandaloneKindSig is an error thrown when a user uses standalone kind signature without enabling the StandaloneKindSignatures extension.Example:!type D :: Type data D = DTest cases: saks should_fail saks_fail001TcRnIllegalRuleLhs is an error triggered by malformed left-hand side of rewrite rule Examples:&{-# RULES "test" forall x. f x = x #-},{-# RULES "test" forall x. case x of = x #-}Test cases: rename should_failT15659TcRnDuplicateRoleAnnot is an error triggered by two or more role annotations for one typeExample:data D a type role D phantom type role D phantomTest cases: roles should_failRoles8TcRnDuplicateKindSig is an error triggered by two or more standalone kind signatures for one typeExample:4type D :: Type type D :: Type data DTest cases: saks should_fail saks_fail002TcRnIllegalDerivStrategy is an error thrown when a user uses deriving strategy without enabling the DerivingStrategies extension or uses deriving via without enabling the DerivingVia extension. Examples:data T = T deriving stock Eqdata T = T deriving via Eq TTest cases: deriving should_fail-deriving-via-fail3 deriving should_fail T10598_fail4TcRnIllegalMultipleDerivClauses is an error thrown when a user uses two or more deriving clauses without enabling the DerivingStrategies extension.Example:7data T = T deriving Eq deriving OrdTest cases: deriving should_fail T10598_fail5TcRnNoDerivStratSpecified is a warning implied by -Wmissing-deriving-strategies and triggered by deriving without mentioning a strategy.See  cases for examples.Test cases: derivingshould_compile"T15798a derivingshould_compile"T15798b derivingshould_compile"T15798c derivingshould_compile"T24955a derivingshould_compile"T24955b derivingshould_compileT24955cTcRnStupidThetaInGadt is an error triggered by data contexts in GADT-style data declarationExample:/data (Eq a) => D a where MkD :: D IntTest cases: rename should_failRnStupidThetaInGadtTcRnShadowedTyVarNameInFamResult is an error triggered by type variable in type family result that shadows type variable from left hand sideExample:type family F a b c = bTest cases: ghciscripts(T6018ghcirnfail rename should_fail T6018rnfailTcRnIncorrectTyVarOnRhsOfInjCond is an error caused by a situation where the left-hand side of an injectivity condition of a type family is not a variable referring to the type family result. See Note [Renaming injectivity annotation] for more details.Example:type family F a = r | a -> aTest cases: ghciscripts(T6018ghcirnfail rename should_fail T6018rnfailTcRnUnknownTyVarsOnRhsOfInjCond is an error triggered by out-of-scope type variables on the right-hand side of a of an injectivity condition of a type familyExample: type family F a = res | res -> bTest cases: ghciscripts(T6018ghcirnfail rename should_fail T6018rnfailTcRnLookupInstance groups several errors emitted when looking up class instances.Test cases: noneTcRnBadlyStaged is an error that occurs when a TH binding is used in an invalid stage.Test cases: T17820dTcRnStageRestriction is an error that occurs when a top level splice refers to a local name.Test cases: T17820, T21547, T5795, qq00[1-4], annfail0{3,4,6,9}TcRnBadlyStagedWarn is a warning that occurs when a TH type binding is used in an invalid stage.0Controlled by flags: - Wbadly-staged-type9Test cases: T23829_timely T23829_tardy T23829_hastyTcRnTyThingUsedWrong is an error that occurs when a thing is used where another thing was expected.Test cases: noneTcRnCannotDefaultKindVar is an error that occurs when attempting to use unconstrained kind variables whose type isn't Type, without -XPolyKinds.Test cases: T11334bTcRnUninferrableTyVar is an error that occurs when metavariables in a type could not be defaulted.Test cases: T17301, T17562, T17567, T17567StupidTheta, T15474, T21479TcRnSkolemEscape is an error that occurs when type variables from an outer scope is used in a context where they should be locally scoped.Test cases: T15076, T15076b, T14880-2, T15825, T14880, T15807, T16946, T14350, T14040A, T15795, T15795a, T14552TcRnPatSynEscapedCoercion is an error indicating that a coercion escaped from a pattern synonym into a type. See Note [Coercions that escape] in GHC.Tc.TyCl.PatSynTest cases: T14507TcRnPatSynExistentialInResult is an error indicating that the result type of a pattern synonym mentions an existential type variable.#Test cases: PatSynExistentialTcRnPatSynArityMismatch is an error indicating that the number of arguments in a pattern synonym's equation differs from the number of parameters in its signature.Test cases: PatSynArity™TcRnPatSynInvalidRhs is an error group indicating that the pattern on the right hand side of a pattern synonym is invalid. Test cases: unidir, T14112ÙTcRnZonkerMessage is collection of errors that occur when zonking, i.e. filling in metavariables with their final values.See ݗęTcRnTyFamDepsDisabled is an error indicating that a type family injectivity annotation was used without enabling the extension TypeFamilyDependencies.Test cases: T11381řTcRnAbstractClosedTyFamDecl is an error indicating that an abstract closed type family was declared in a regular source file, while it is only allowed in hs-boot files.Test cases: ClosedFam4ƙTcRnPartialFieldSelector is a warning indicating that a record field was not defined for all constructors of a data type.)Test cases: DRFPartialFields, T7169ǙTcRnHasFieldResolvedIncomplete is a warning triggered when a HasField constraint is resolved for a record field for which a `getField @"field"` application might not be successful. Currently, this means that the warning is triggered when the parent data type of that record field does not have that field in all its constructors.Example(s): data T = T1 | T2 {x :: Bool} f :: HasField t "x" Bool => t -> Bool f = getField @"x" g :: T -> Bool g = f%Test cases: TcIncompleteRecSelșTcRnBadFieldAnnotation is an error/warning group indicating that a strictness/unpack related data type field annotation is invalid.əTcRnSuperclassCycle is an error indicating that a class has a superclass cycle.Test cases: mod40, tcfail027, tcfail213, tcfail216, tcfail217, T9415, T9739ʙTcRnDefaultSigMismatch is an error indicating that a default method signature doesn't match the regular method signature.1Test cases: T7437, T12918a, T12918b, T12151˙TcRnTyFamsDisabled is an error indicating that a type family or instance was declared while the extension TypeFamilies was disabled. Test cases: TyFamsDisabled̙:TcRnBadTyConTelescope is an error caused by an ill-scoped  kind, due to type variables being out of dependency order.Example:class C a (b :: Proxy a) (c :: Proxy b) where type T c aTest cases: BadTelescope{D,3,4} T14066{f,g} T14887 T15591{b,c} T15743{c,d} T15764 T23252͙TcRnTyFamResultDisabled is an error indicating that a result variable was used on a type family while the extension TypeFamilyDependencies was disabled.!Test cases: T13571, T13571aΙTcRnRoleValidationFailed is an error indicating that a variable was assigned an invalid role by the inference algorithm. This is only performed with -dcore-lint.ϙTcRnCommonFieldResultTypeMismatch is an error indicating that a sum type declares the same field name in multiple constructors, but the constructors' result types differ./Test cases: CommonFieldResultTypeMismatchЙTcRnCommonFieldTypeMismatch is an error indicating that a sum type declares the same field name in multiple constructors, but their types differ.)Test cases: CommonFieldTypeMismatchљTcRnClassExtensionDisabled is an error indicating that a class was declared with an extension feature while the extension was disabled.ҙTcRnDataConParentTypeMismatch is an error indicating that a data constructor was declared with a type that doesn't match its type constructor (i.e. a GADT result type and its data name).Test cases: T7175, T13300, T14719, T18357, T18357b, gadt11, tcfail155, tcfail176әTcRnGADTsDisabled is an error indicating that a GADT was declared while the extension GADTs was disabled. Test cases: ghci057, T9293ԙTcRnExistentialQuantificationDisabled is an error indicating that a data constructor was declared with existential features while the extension ExistentialQuantification was disabled.Test cases: ghci057, T9293, gadtSyntaxFail001, gadtSyntaxFail002, gadtSyntaxFail003, prog006, rnfail053, T12083aՙTcRnGADTDataContext is an error indicating that a GADT was declared with a data type context. This error is emitted in the tc, but it is also caught in the renamer.֙TcRnMultipleConForNewtype is an error indicating that a newtype was declared with multiple constructors. This error is caught by the parser.יTcRnKindSignaturesDisabled is an error indicating that a kind signature was used in a data type declaration while the extension KindSignatures was disabled.&Test cases: T20873c, readFail036ؙTcRnEmptyDataDeclsDisabled is an error indicating that a data type was declared with no constructors while the extension EmptyDataDecls was disabled.Test cases: readFail035ٙTcRnRoleMismatch is an error indicating that the role specified in an annotation differs from its inferred role. Test cases: T7253, Roles11ڙTcRnRoleCountMismatch is an error indicating that the number of roles in an annotation doesn't match the number of type parameters.Test cases: Roles6ۙTcRnIllegalRoleAnnotation is an error indicating that a role annotation was attached to a decl that doesn't allow it.Test cases: Roles5ܙTcRnRoleAnnotationsDisabled is an error indicating that a role annotation was declared while the extension RoleAnnotations was disabled.#Test cases: Roles5, TH_Roles1ݙTcRnIncoherentRoles is an error indicating that a role annotation for a class parameter was declared as not nominal.Test cases: T8773ޙTcRnPrecedenceParsingError is an error caused by attempting to use operators with the same precedence in one infix expression.)Example: eq :: (a ~ b ~ c) :~: ()1Test cases: module/mod61 parser should_fail$readFail016 rename should_fail"rnfail017 rename should_fail!T9077 typecheck should_failT18252aߙTcRnPrecedenceParsingError is an error caused by attempting to use an operator with higher precedence than the operand.Example: k = (-3 **) where (**) = const infixl 7 **Test cases: overloadedrecflds should_fail0T13132_duplicaterecflds parser should_fail$readFail023 rename should_fail2rnfail019 th/TH_unresolvedInfix2TcRnTypeSynonymCycle is an error indicating that a cycle between type synonyms has occurred./Test cases: mod27, ghc-e-fail2, bkpfail29TcRnSelfImport is an error indicating that a module contains an import of itself.Test cases: T9032TcRnNoExplicitImportList is a warning indicating that an import statement did not include an explicit import list.Test cases: T1789, T4489TcRnSafeImportsDisabled is an error indicating that an import was declared using the safe) keyword while SafeHaskell wasn't active.Test cases: Mixed01TcRnDeprecatedModule is a warning indicating that an imported module is annotated with a warning or deprecation pragma.Test cases: DeprUTcRnRedundantSourceImport is a warning indicating that a {-# SOURCE #-} import was used when there is no import cycle.Test cases: none?TcRnImportLookup is a group of errors about bad imported names.;TcRnUnusedImport is a group of errors about unused imports.TcRnDuplicateDecls is an error indicating that the same name was used for multiple declarations.Test cases: FieldSelectors, overloadedrecfldsfail03, T17965, NFSDuplicate, T9975a, TDMultiple01, mod19, mod38, mod21, mod66, mod20, TDPunning, mod18, mod22, TDMultiple02, T4127a, ghci048, T8932, rnfail015, rnfail010, rnfail011, rnfail013, rnfail002, rnfail003, rn_dup, rnfail009, T7164, rnfail043, TH_dupdecl, rnfail012TcRnPackageImportsDisabled is an error indicating that an import uses a package qualifier while the extension PackageImports was disabled.(Test cases: PackageImportsDisabledTcRnIllegalDataCon is an error indicating that a data constructor was defined using a lowercase name, or a symbolic name in prefix position. Mostly caught by PsErrNotADataCon.Test cases: NoneTcRnNestedForallsContexts is an error indicating that multiple foralls or contexts are nested/curried where this is not supported, like  D x. D y. instead of D x y..Test cases: T12087, T14320, T16114, T16394, T16427, T18191, T18240a, T18240b, T18455, T5951TcRnRedundantRecordWildcard is a warning indicating that a pattern uses a record wildcard even though all of the record's fields are bound explicitly.Test cases: T15957_FailTcRnUnusedRecordWildcard is a warning indicating that a pattern uses a record wildcard while none of the fields bound by it are used.Test cases: T15957_FailTcRnUnusedName is a warning indicating that a defined or imported name is not used in the module.Test cases: ds053, mc10, overloadedrecfldsfail05, overloadedrecfldsfail06, prog018, read014, rn040, rn041, rn047, rn063, T13839, T13839a, T13919, T17171b, T17a, T17b, T17d, T17e, T18470, T1972, t22391, t22391j, T2497, T3371, T3449, T7145b, T7336, TH_recover_warns, unused_haddock, WarningGroups, werrorTcRnQualifiedBinder is an error indicating that a qualified name was used in binding position.Test cases: mod62, rnfail021, rnfail034, rnfail039, rnfail046TcRnTypeApplicationsDisabled is an error indicating that a type application was used while the extension TypeApplications was disabled.9Test cases: T12411, T12446, T15527, T16133, T18251cTcRnInvalidRecordField is an error indicating that a record field was used that doesn't exist in a constructor.Test cases: T13644, T13847, T17469, T8448, T8570, tcfail083, tcfail084TcRnTupleTooLarge is an error indicating that the arity of a tuple exceeds mAX_TUPLE_SIZE.Test cases: T18723a, T18723b, T18723c, T6148a, T6148b, T6148c, T6148dTcRnCTupleTooLarge is an error indicating that the arity of a constraint tuple exceeds mAX_CTUPLE_SIZE.Test cases: T10451TcRnIllegalInferredTyVars is an error indicating that some type variables were quantified as inferred (like D {a}.) in a place where this is not allowed, like in an instance declaration.Test cases: ExplicitSpecificity5, ExplicitSpecificity6, ExplicitSpecificity8, ExplicitSpecificity9TcRnAmbiguousName is an error indicating that an unbound name might refer to multiple names in scope.Test cases: BootFldReexport, DRFUnused, duplicaterecfldsghci01, GHCiDRF, mod110, mod151, mod152, mod153, mod164, mod165, NoFieldSelectorsFail, overloadedrecfldsfail02, overloadedrecfldsfail04, overloadedrecfldsfail11, overloadedrecfldsfail12, overloadedrecfldsfail13, overloadedrecfldswasrunnowfail06, rnfail044, T11167_ambig, T11167_ambiguous_fixity, T13132_duplicaterecflds, T15487, T16745, T17420, T18999_NoDisambiguateRecordFields, T19397E1, T19397E2, T23010_fail, tcfail037TcRnBindingNameConflict is an error indicating that multiple local or top-level bindings have the same name.Test cases: dsrun006, mdofail002, mdofail003, mod23, mod24, qq006, rnfail001, rnfail004, SimpleFail6, T14114, T16110_Fail1, tcfail038, TH_spliceD1, T22478b, TyAppPat_NonlinearMultiAppPat, TyAppPat_NonlinearMultiPat, TyAppPat_NonlinearSinglePat,TcRnNonCanonicalDefinition is a warning indicating that an instance defines an implementation for a method that should not be defined in a way that deviates from its default implementation, for example because it has been scheduled to be absorbed into another method, like pure making return obsolete.Test cases: WCompatWarningsOn, WCompatWarningsOff, WCompatWarningsOnOff8TcRnImplicitImportOfPrelude is a warning, controlled by Wimplicit-prelude9, that is triggered upon an implicit import of the Prelude module.Example:{-# OPTIONS_GHC -fwarn-implicit-prelude #-} module M where {}Test case: rn055TcRnMissingMain is an error that occurs when a Main module does not define a main function (named main, by default, but overridable with the main-is command line flag).Example:module Main where {}Test cases: T414, T7765, readFail021, rnfail007, T13839b, T17171a, T16453E1, tcfail030, T19397E3, T19397E4TcRnGhciUnliftedBind is an error that occurs when a user attempts to bind an unlifted value in GHCi.Example (in GHCi):let a = (# 1#, 3# #)Test cases: T9140, T19035bTcRnGhciMonadLookupFail is an error that occurs when the user sets the GHCi monad, using the GHC API  setGHCiMonad function, but GHC can't find which monad the user is referring to.Example:import GHC ( setGHCiMonad )... setGHCiMonad  NoSuchThingTest cases: noneTcRnMissingRoleAnnotation is a warning that occurs when type declaration doesn't have a role annotatiosn7Controlled by flags: - Wmissing-role-annotationsTest cases: T22702TcRnPatersonCondFailure is an error that occurs when an instance declaration fails to conform to the Paterson conditions. Which particular condition fails depends on the constructor of PatersonCondFailure See Note [Paterson conditions].Test cases: T15231, tcfail157, T15316, T19187a, fd-loop, tcfail108, tcfail154, T15172, tcfail214TcRnImplicitRhsQuantification is a warning that occurs when GHC implicitly quantifies over a type variable that occurs free on the RHS of the type declaration that is not mentioned on the LHSExample:type T = 'Nothing :: Maybe a:Controlled by flags: - Wimplicit-rhs-quantification/Test cases: T23510a T23510bTcRnIllformedTypePattern is an error raised when the pattern corresponding to a required type argument (visible forall) does not have a form that can be interpreted as a type pattern.Example:vfun :: forall (a :: k) -> () vfun !x = () -- ^^ -- bang-patterns not allowed as type patterns*Test cases: T22326_fail_bang_patTcRnIllegalTypePattern is an error raised when a pattern constructed with the type keyword occurs in a position that does not correspond to a required type argument (visible forall).Example:case x of (type _) -> True -- the (type _) pattern is illegal here _ -> False>Test cases: T22326_fail_ado T22326_fail_caseofTcRnIllformedTypeArgument is an error raised when an argument that specifies a required type argument (instantiates a visible forall) does not have a form that can be interpreted as a type argument.Example:vfun :: forall (a :: k) -> () x = vfun (_ -> _) -- ^^^^^^^^^ -- lambdas not allowed in type arguments'Test cases: T22326_fail_lam_argTcRnInvalidDefaultedTyVar is an error raised when a defaulting plugin proposes to default a type variable that is not an unfilled metavariable"Test cases: T23832_invalidTcRnNamespacedWarningPragmaWithoutFlag is an error that occurs when a namespace specifier is used in {-# WARNING ... #-} or {-# DEPRECATED ... #-} pragmas without the -XExplicitNamespaces extension enabledExample:{-# LANGUAGE NoExplicitNamespaces #-} f = id {-# WARNING data f "some warning message" #-}Test cases: T24396cTcRnInvisPatWithNoForAll is an error raised when invisible type pattern is used without associated `forall` in types Examples:f :: Int f @t = 5+g :: [a -> a] g = [ @t x -> x :: t]Test cases: T17694c T17594dTcRnIllegalInvisibleTypePattern is an error raised when invisible type pattern is used without the TypeAbstractions extension enabledExample:{-# LANGUAGE NoTypeAbstractions #-} id :: a -> a id @t x = xTest cases: T17694bTcRnNamespacedFixitySigWithoutFlag is an error that occurs when a namespace specifier is used in fixity signatures without the -XExplicitNamespaces extension enabledExample:{-# LANGUAGE NoExplicitNamespaces #-} f = const infixl 7 data fTest cases: T14032cTcRnDefaultedExceptionContext is a warning that is triggered when the backward-compatibility logic solving for implicit ExceptionContext constraints fires.#Test cases: DefaultExceptionContextTcRnOutOfArityTyVar is an error raised when the arity of a type synonym (as determined by the SAKS and the LHS) is insufficiently high to accommodate an implicit binding for a free variable that occurs in the outermost kind signature on the RHS of the said type synonym.Example:type SynBad :: forall k. k -> Type type SynBad = Proxy :: j -> TypeTest cases: T24770a* is an "internal" type (used only inside    that wraps a ߗ while also providing any extra info needed to correctly pretty-print this diagnostic later on.1Extra supplementary info associated to the error.&Extra context associated to the error.(Whether we show the error context or not5Construct a basic mismatch message between two types.See pprMismatchMsg. for how such a message is displayed to users.7Report a mismatch error without any extra information. Create a "not in scope" error message for the given 4.Display some relevant bindings.The instance signature (e.g Show a => Show (T a)) Expected type Actual typeߒResult of showing the exception (cannot be done safely outside IO)type of the splicewhat's nested inside Module nameTrue => Error, False => Warning Error body#the label type in the instance headWhether the error is due to Safe Haskell being enabled | The instance failed the coverage condition, i.e. the functional dependencies were not respected.Example:;class C a b | a -> b where {..} instance C a b where {..}4Test cases: T9106, T10570, T2247, T12803, tcfail170.the instance head type"the problem with the instance headthe instance head typeis this an invisible argument? type familytype family argumentThe unsed nameswhether -XPatternSynonyms was enabled'The name extracted from the import item'The name extracted from the import itemThe potential matchesΓ The arity6suggestions for what might have been meant | Missing type keyword when importing a type. e.g. `import TypeLits( (+) )`, where TypeLits exports a type (+), not a term (+) Then we want to suggest using `import TypeLits( type (+) )`the message to reportthe message to reportalways a class constraint/ambiguous kind and type variables, respectivelyTrue  = subtype checkTrue  == role subtype check | Two type synonyms have different RHSs.boot real  | Two s aren't compatible.boot real the boot instance - NB: we never trigger this for hsig files, as in that case we do a full round of constraint solving, and a missing instance gets reported as an unsolved Wanted constraint with a InstProvidedOrigin (. See GHC.Tc.Utils.Backpack.check_inst. boot thing real thingK   | Multiple default declarations were given for an associated family instance.Test cases: none.family expected type argumentsactual type argumentsϖ was this a 'type' or a 'data' instance?іThe family tyconҖThe family tyconThe right number of parametersӖThe family nameThe name used in the equationԖfamily , arguments, and set of "dodgy" type variables See Note [Dodgy binding sites in type family instances] in GHC.Tc.Validitythe out-of-scope type variablesٖthe ' at the head of the instance head, or K/ if the instance head is not even headed by a The type constructor that occurs in the typeclass instance declaration.The typeclass kind.The number of typeclass arguments that GHC kept. See Note [tc_args and tycon arity] in GHC.Tc.Deriv. | Generic instances can only be derived using the stock strategy in Safe Haskell.5Type constructor for which the instance is requestedWhether or not -XDeriveAnyClass is enabled already. | Stock deriving won't work, but perhaps DeriveAnyClass will.ȗ!The possible parents (at least 2)The  will allow us to pretty-print some diagnostics with more detail.The contextual skolem info. The boolean controls whether we want to show it in the user message. (Nice to keep track of the info in either case, for other users of the GHC API.)+The implication containing a contradiction.The contradiction.The type family's constructorThe inaccessible branch tyVar binder. The limit.the wildcard name, or K for an anonymous wildcardfirst type variablesecond type variable function name3user-written name of type variable being quantified function name(type the variable unified with, if knownpartial type signature2whether this is an unboxed tuple or an unboxed sumexpected arity actual arity the violation the family the family equationsclasslocally declared defaultsimported defaultsparentchild&Occurrence name shared by both exports First exportExport decl of first export Second exportExport decl of second export Field update Record type˜the fields of the record update*the reason this record update was rejectedȘ6The typeclass we are trying to derive an instance for The typeclass arguments, if any. The derivation strategy, if any.*Is '-XGeneralizedNewtypeDeriving' enabled?The specific reason why we couldn't derive an instance for the class.јwhat the problem isthe name that is not in scopeimport errors that are relevanthints, e.g. enable DataKinds to refer to a promoted data constructorԘ?what kind of thing this is (a binding, fixity declaration, ...)՘/Wanted constraints in which defaulting occurred!The type variable being defaultedThe default type֘whether the error is happening in a Template Haskell tick (so we should give a Template Haskell hint)The visible kind argumentTarget of the kind application&classification of thing being returned allowed kindthe return kindsuggested extensionThe illegal kind0Whether enabling -XPolyKinds should be suggestedPattern match specificsExpected number of argsActual number of argsTarget of the pragmasThe first pragma Other pragmas'The name with different export warningsThe locations of export list items that differ from the one at which the error is reportedThe name that is exportedThe locations of export list items that are missing the export warning of the classdefault methods$The operator whose fixity is defined"the fixity used in the source file the fixity used in the signatureThe missing nameThe module's unit stateThe implementation module of the classProblematic methodmethod the pragmaTrue if linear types enabledList of binders%True if DerivingStrategies is enabledThe binding being spliced.The binding stage.'The stage at which the binding is used.The binding being spliced.The type binding being spliced.The binding stage.'The stage at which the binding is used.Expected thing.Thing used wrongly.Name of the thing used wrongly.The unconstrained variable.Kind of the variable.*The variables that could not be defaulted.'Description of the surrounding context. The variables that would escape.&The variable that is being quantified.The type in which they occur.The pattern-bound variableThe escaped coercionsThe name of the pattern synonymThe result type!The escaped existential variablesThe name of the pattern synonym The number of equation argumentsThe difference™The name of the pattern synonym The pattern The LHS args The number of equation argumentsƙ The selectorșThe index of the field-The constructor in which the field is definedThe error specificsəThe details of the cycleʙThe name of the method!The type of the default signature˙"The name of the family or instance͙The name of the type familyName of the result variableΙThe validated roleThe failure reasonϙFirst constructorSecond constructor Field nameЙFirst constructorSecond constructor Field nameљ The class The extensionҙThe data constructorThe parent typeәThe name of the GADTԙThe constructorՙThe data type name֙The newtype nameThe number of constructorsיThe data type nameؙThe data type nameٙThe type variableThe annotated roleThe inferred roleڙThe number of type variablesThe role annotationۙThe role annotationܙThe annotated typeݙThe class tyconޙ first operator's name and fixity!second operator's name and fixityߙ first operator's name and fixityargument operatorSection The tycons involved in the cycle The moduleThe imported moduleThe imported moduleThe imported moduleThe pragma dataThe imported moduleDetails about the error The importDetails about the errorThe name of the declarationsThe individual declarationsThe constructor nameThe names bound by the wildcardThe unused nameThe provenance of the nameThe name used as a binder$what kind of type application is it?The constructor nameThe name of the fieldThe arity of the tuple!The arity of the constraint tupleThe offending type variablesThe nameThe possible matchesThe conflicting nameThe locations of the duplicates SpecificsThe instance type.whether the module has an explicit export list&the expected name of the main function3the textual name of the monad requested by the user lookup resultthe failed Paterson Conditionthe LHSthe RHS$The constraints passed to the plugin*The plugin-proposed type variable defaults*The invalid type variables of the proposalType synonym's nameType variable's name&Extra info associated with the messageXXXЗїҗޓߓƗɗȗǗʗɔ̔˔ʔɒ͒Ւʒ֒ђȒƒÒĒΒϒԒӒҒǒŒ̒˒В’͓ГϓΓĕŕʕɕȕǕ˕ƕח—͔ϔΔДєҔӔԔ֔Ք“ÓēƓœΖՖԖҖі֖ϖЖӖזؖܖٖۖږƔǔȔ–ĖÖɖʖ͖˖̖ŖƖǖȖהܔڔݔٔؔߔ۔ޔ”ÔŔĔ˗̗͗Ηϗѓԓӓғܒݒ×ŗėݖߖޖ͕̕ՕԕוϕӕѕΕ֕ҕЕܕݕߕޕٕؕڕەޒߒٓړݓܓۓՓד֓ؓߗřʘș˜̙Ș˘љϙЙҙʙŘؙԙߘ٘טؘژՙИәǙԘۘݘۙΘϘݙ֘ޘיɘ֙Ƙјƙǘ™ޙܙڙٙΙߙØəҘę͙˙̘͘ܘӘĘ՘ÙÕ•גْؒڒےʓ˓̓Ǔȓɓؗٗܗڗۗӗ֗՗ԗݗޗXXXXXXXXXXXXXߗřʘș˜̙Ș˘љϙЙҙʙŘؙԙߘ٘טؘژՙИәǙԘۘݘۙΘϘݙ֘ޘיɘ֙Ƙјƙǘ™ޙܙڙٙΙߙØəҘę͙˙̘͘ܘӘĘ՘Ùؗٗܗڗۗ—×ŗė˗̗͗ΗϗƗɗȗǗʗݖߖޖĕŕʕɕȕǕ˕ƕܕݕߕޕٕؕڕە͕̕ՕԕוϕӕѕΕ֕ҕЕÕ•ДєҔӔԔ֔ՔXXXXXXXXXXXXXXXXהܔڔݔٔؔߔ۔ޔƔǔȔ͔ϔΔɔ̔˔ʔ”ÔŔĔӗ֗՗ԗחЗїҗޓߓٓړݓܓۓՓד֓ؓѓԓӓғ͓ГϓΓʓ˓̓ǓȓɓēƓœ“ÓזؖܖٖۖږΖՖԖҖі֖ϖЖӖɖʖ͖˖̖ŖƖǖȖ–ĖÖޒߒܒݒɒ͒Ւʒ֒ђȒƒÒĒΒϒԒӒҒǒŒ̒˒В’גْؒڒےݗޗ " "$ & && ' ' * * 0 0 0 0/ " "   5 5 5 5 5 5 2 2 3 3 4 4 4 4š 4 4Ú 4 4Ě 4 4Ś 3 3ƚ 3 3ǚ 1 1Ț 1 1ɚ 2 2ʚ 1 1˚ 1 1̚ 0 0͚ 0 0Κ 0 0Ϛ 0 0К 0 0њ 0 0Қ / /Ӛ / /Ԛ / /՚ / /֚ ) )ך + +ؚ , ,ٚ - -ښ - -ۚ , ,ܚ - -ݚ ' 'ޚ ( (ߚ ( ( ' ' $ $ ' ' ' ' ' ' & & & & ' ' ' ' ' ' % % $ $ $ $ # # # # ## # # ## # # ## # # " " " " " " " "4None++None K K  " None+'t*A message from the driver.Simply wraps a generic Ɓ message a.A parse error in parsing a Haskell file header during dependency analysisDriverMissingHomeModules is a warning (controlled with -Wmissing-home-modules) that arises when running GHC in --make mode when some modules needed for compilation are not included on the command line. For example, if A imports B, `ghc --make A.hs` will cause this warning, while `ghc --make A.hs B.hs` will not.Useful for cabal to ensure GHC won't pick up modules listed neither in 'exposed-modules' nor in 'other-modules'.Test case: warningsshould_compile MissingModDriverUnknown is a warning that arises when a user tries to reexport a module which isn't part of that unit.DriverUnknownHiddenModules is a warning that arises when a user tries to hide a module which isn't part of that unit.DriverUnusedPackages occurs when when package is requested on command line, but was never needed during compilation. Activated by -Wunused-packages.Test cases: warningsshould_compileUnusedPackagesDriverUnnecessarySourceImports (controlled with -Wunused-imports) occurs if there are {-# SOURCE #-} imports which are not necessary. See warnUnnecessarySourceImports in   .Test cases: warningsshould_compileT106375DriverDuplicatedModuleDeclaration occurs if a module A& is declared in multiple files.Test cases: None.(DriverModuleNotFound occurs if a module A can't be found.Test cases: None.0DriverFileModuleNameMismatch occurs if a module A is defined in a file with a different name. The first field is the name written in the source code; the second argument is the name extracted from the filename.Test cases: modulemod178, driver/bug1677>DriverUnexpectedSignature occurs when GHC encounters a module A= that imports a signature file which is neither in the  signatures section of a '.cabal' file nor in any package in the home modules.Example:*- MyStr.hsig is defined, but not added to  signatures in the '.cabal' file. signature MyStr where data Str- A.hs, which tries to import the signature. module A where import MyStrTest cases: driver/T12955DriverFileNotFound occurs when the input file (e.g. given on the command line) can't be found.Test cases: None.1DriverStaticPointersNotSupported occurs when the StaticPointers9 extension is used in an interactive GHCi context.Test cases: ghciscripts StaticPtrDriverBackpackModuleNotFound occurs when Backpack can't find a particular module during its dependency analysis. Test cases: -DriverUserDefinedRuleIgnored is a warning that occurs when user-defined rules are ignored. This typically happens when Safe Haskell. Test cases:tests safeHaskell%safeInfered/UnsafeWarn05 tests safeHaskell%safeInfered/UnsafeWarn06 tests safeHaskell%safeInfered/UnsafeWarn07 tests safeHaskell(safeInfered/UnsafeInfered11 tests safeHaskellsafeLanguage/SafeLang03DriverMixedSafetyImport is an error that occurs when a module is imported both as safe and unsafe. Test cases:tests safeHaskellsafeInfered/Mixed03 tests safeHaskellsafeInfered/Mixed02DriverCannotLoadInterfaceFile is an error that occurs when we cannot load the interface file for a particular module. This can happen for example in the context of Safe Haskell, when we have to load a module to check if it can be safely imported.Test cases: None.DriverInferredSafeImport is a warning (controlled by the Opt_WarnSafe flag) that occurs when a module is inferred safe.Test cases: None.DriverMarkedTrustworthyButInferredSafe is a warning (controlled by the Opt_WarnTrustworthySafe flag) that occurs when a module is marked trustworthy in SafeHaskell but it has been inferred safe.Test cases: tests safeHaskell)safeInfered/TrustworthySafe02 tests safeHaskellsafeInfered/TrustworthySafe03DriverInferredSafeImport is a warning (controlled by the Opt_WarnInferredSafeImports flag) that occurs when a safe-inferred module is imported from a safe module.Test cases: None.DriverCannotImportUnsafeModule is an error that occurs when an usafe module is being imported from a safe one.Test cases: None.DriverMissingSafeHaskellMode is a warning (controlled by the Opt_WarnMissingSafeHaskellMode flag) that occurs when a module is using SafeHaskell features but SafeHaskell mode is not enabled.Test cases: None.DriverPackageNotTrusted is an error that occurs when a package is required to be trusted but it isn't.Test cases: tests safeHaskellcheck/Check01 tests safeHaskellcheck/Check08 tests safeHaskellcheck/Check06 tests safeHaskellcheckpkg01ImpSafeOnly09 tests safeHaskellcheckpkg01ImpSafe03 tests safeHaskellcheckpkg01ImpSafeOnly07 tests safeHaskellcheckpkg01 ImpSafeOnly08DriverCannotImportFromUntrustedPackage is an error that occurs in the context of Safe Haskell when trying to import a module coming from an untrusted package.Test cases: tests safeHaskellcheck/Check09 tests safeHaskellcheckpkg01ImpSafe01 tests safeHaskellcheckpkg01ImpSafe04 tests safeHaskellcheckpkg01ImpSafeOnly03 tests safeHaskellcheckpkg01ImpSafeOnly05 tests safeHaskellflags/SafeFlags17 tests safeHaskellflags/SafeFlags22 tests safeHaskellflags/SafeFlags23 tests safeHaskellghci/p11 tests safeHaskellghci/p12 tests safeHaskellghci/p17 tests safeHaskellghci/p3 tests safeHaskell'safeInfered/UnsafeInfered01 tests safeHaskell'safeInfered/UnsafeInfered02 tests safeHaskell'safeInfered/UnsafeInfered02 tests safeHaskell'safeInfered/UnsafeInfered03 tests safeHaskell'safeInfered/UnsafeInfered05 tests safeHaskell'safeInfered/UnsafeInfered06 tests safeHaskell'safeInfered/UnsafeInfered09 tests safeHaskell'safeInfered/UnsafeInfered10 tests safeHaskell'safeInfered/UnsafeInfered11 tests safeHaskell$safeInfered/UnsafeWarn01 tests safeHaskell$safeInfered/UnsafeWarn03 tests safeHaskell$safeInfered/UnsafeWarn04 tests safeHaskell$safeInfered/UnsafeWarn05 tests safeHaskell"unsafeLibs/BadImport01 tests safeHaskell"unsafeLibs/BadImport06 tests safeHaskell"unsafeLibs/BadImport07 tests safeHaskell"unsafeLibs/BadImport08 tests safeHaskell"unsafeLibs/BadImport09 tests safeHaskellunsafeLibs/Dep05 tests safeHaskellunsafeLibs/Dep06 tests safeHaskellunsafeLibs/Dep07 tests safeHaskellunsafeLibs/Dep08 tests safeHaskellunsafeLibs/Dep09 tests safeHaskellunsafeLibs/Dep10DriverModuleGraphCycle is an error that occurs if the module graph contains cyclic imports.Test cases: testsbackpackshould_fail/bkpfail51 testsdriverT20459 testsdriverT24196/T24196 testsdriver T24275/T24275DriverInstantiationNodeInDependencyGeneration is an error that occurs if the module graph used for dependency generation contains Backpack s. DriverNoConfiguredLLVMToolchain is an error that occurs if there is no LLVM toolchain configured but -fllvm is passed as an option to the compiler.Test cases: None.A collection of driver messagesThe umbrella type that encompasses all the different messages that GHC might output during the different compilation stages. See Note [GhcMessage].!A message from the parsing phase.(A message from typecheck/renaming phase./A message from the desugaring (HsToCore) phase.A message from the driver.An "escape" hatch which can be used when we don't know the source of the message or if the message is not one of the typed ones. The Ɓ and  constraints ensure that if we know, at pattern-matching time, the originating type, we can attempt a cast and access the fully-structured error. This would be the case for a GHC plugin that offers a domain-specific error type but that doesn't want to place the burden on IDEs/application code to "know" it. The Ɓ constraint ensures that worst case scenario we can still render this into something which can be eventually converted into a ΁.A single warning message.  INVARIANT: It must have  severity.!A collection of error messages.  INVARIANT: Each  in the collection should have  severity.#A collection of warning messages.  INVARIANT: Each  in the collection should have  severity.Creates a new  out of any diagnostic. This function is also provided to ease the integration of #18516 by allowing diagnostics to be wrapped into the general (but structured)  type, so that the conversion can happen gradually. This function should not be needed within GHC, as it would typically be used by plugin or library authors (see comment for the  type constructor)9Abstracts away the frequent pattern where we are calling  ioMsgMaybe2 on the result of 'IO (Messages TcRnMessage, a)'.9Abstracts away the frequent pattern where we are calling  ioMsgMaybe0 on the result of 'IO (Messages DsMessage, a)'.>  (None !3 ًDecide whether to pick the left or right branch when deciding how to recurse into a product.ڋUse the generic representation of a type to retrieve the collection of all diagnostic codes it can give rise to.ۋUse the generic representation of a type to retrieve the diagnostic code, using the  type family.See Note [Diagnostic codes using generics] in GHC.Types.Error.Codes.܋Some constructors of diagnostic datatypes don't have corresponding error codes, because we recur inside them.2For example, we don't have an error code for the Ș constructor of ߗ, because we recur into the  to obtain an error code.2This type family keeps track of such constructors.݋ constructorCodes @T = fromList [ (123, "MkT1"), (456, "MkT2") ] <    6 <    , *  ?   -  1  0  None  #&'+3 , ,None )3;1An mtl-style class for monads that support parsing-related operations. For example, sometimes we make a second pass over the parsing results to validate, disambiguate, or rearrange them, and we do so in the PV monad which cannot consume input but can report parsing errors, check for extension bits, and accumulate parsing annotations. Both P and PV are instances of MonadP.MonadP grants us convenient overloading. The other option is to have separate operations for each monad: addErrorP vs addErrorPV, getBitP vs getBitPV, and so on.Add a non-fatal error. Use this when the parser can produce a result despite the error.#For example, when GHC encounters a forall in a type, but -XExplicitForAll$ is disabled, the parser constructs ForAllTy as if -XExplicitForAll= was enabled, adding a non-fatal error to the accumulator.Control flow wise, non-fatal errors act like warnings: they are added to the accumulator and parsing continues. This allows GHC to report more than one parse error per file.)Add a warning to the accumulator. Use ! to get the accumulated warnings.Add a fatal error. This will be the last error reported by the parser, and the parser will not produce any result, ending in a  state.Get parser optionsGo through the  comment_q in PState; and remove all comments that belong within the given spanGo through the  comment_q in PState and remove all comments that come before or within the given spanGo through the  comment_q in PState8 and remove all comments that come after the given spanVarious boolean flags, mostly language extensions, that impact lexing and parsing. Note that a handful of these can change during lexing/parsing.If this is enabled, '{-# LINE ... -#}' and '{-# COLUMN ... #-}' update the internal position. Otherwise, those pragmas are lexed as tokens of their own.ދFor reasons of efficiency, boolean parsing flags (eg, language extensions or whether we are currently in a RULE2 pragma) are represented by a bitmap stored in a Word64.!The parsing monad, isomorphic to StateT PState Maybe.Haddock comment as produced by the lexer. These are accumulated in  and then processed in GHC.Parser.PostProcess.Haddock. The location of the s spans over the contents of the docstring - i.e. it does not include the decorator ("-- |", "{-|" etc.)Parser options.See  to construct this.supported extensions (only used for suggestions in error messages))Options to construct diagnostic messages.bitmap of permitted extensionsThe result of running a parser.ߋDo we want to generate ';' layout tokens? In some cases we just want to generate '}', e.g. in MultiWayIf we don't need ';'s because '|'# separates alternatives (unlike a `case` expression where we need ';' to as a separator between alternatives). (| |) -< >- -<< >>-*Used when the lexer can't make sense of itend of file tokenThe HsDocString contains more details about what this is and how to pretty print it(doc options (prune, ignore-exports, etc)comment starting by "--"comment in {- -}The parser has consumed a (possibly empty) prefix of the input and failed.The carried parsing state can be used to resume parsing. It is the state right before failure, including the fatal parse error.  and ' must return a non-empty bag of errors.The parser has consumed a (possibly empty) prefix of the input and produced a result. Use 9 to check for accumulated warnings and non-fatal errors.8The carried parsing state can be used to resume parsing.Includes the trailing '-}' decorators drop the last two elements with the callback if you don't want them to be included4Helper to parse ExtendedLiterals (e.g. -0x10#Word32)This function finds the offset of the "#" character and checks that the suffix is valid. Then it calls tok_integral with the appropriate suffix length taken into account.Ideally, we would define this completely with Alex syntax, like normal strings. Instead, this is defined as a hybrid solution by manually invoking lex states, which we're doing for two reasons: 1. The multiline string should all be one lexical token, not multiple 2. We need to allow bare quotes, which can't be done with one regexDummy action that should never be called. Should only be used in lex states that are manually lexed in tok_string_multi.Throw a smart quote error, where the smart quote was the last character lexedTest whether a  is set Advance the given input N bytes..Advance the given input to the given position.1Given exactly the information needed, set up the .Set parser options for parsing OPTIONS pragmasCreates a parse state from a  value5Check if a given flag is currently set in the bitmap.Get a bag of the errors that have been accumulated so far. Does not take -Werror into account.Get the warnings and errors accumulated so far. Does not take -Werror into account.Given a  that surrounds a HsPar or HsParTy , generate 1 values for the opening and closing bordering on the start and end of the spanGiven a  that surrounds a HsPar or HsParTy , generate 1 values for the opening and closing bordering on the start and end of the spanContinuation that gets the rest of the input and the lexed commentstarting value for accumulator (reversed) - When we want to include a decorator '{-' in the commenttoken constructor"value transformation (e.g. negate)Offset of the unsigned value (e.g. 1 when we parsed "-", 2 for "0x", etc.)>Number of non-numeric characters parsed (e.g. 6 in "-12#Int8")%(radix, char_to_int parsing function)"value transformation (e.g. negate)Offset of the unsigned value (e.g. 1 when we parsed "-", 2 for "0x", etc.)%(radix, char_to_int parsing function)%permitted language extensions enableddiagnostic options"Supported Languages and Extensionsare safe imports on?keeping Haddock comment tokenskeep regular comment tokensIf this is enabled, '{-# LINE ... -#}' and '{-# COLUMN ... #-}' update the internal position kept by the parser. Otherwise, those pragmas are lexed as  and  tokens.              48        None )+3 Disambiguate constructs that may appear when we do not know ahead of time whether we are parsing a type or a newtype/data constructor.?See Note [Ambiguous syntactic categories] for the general idea.See Note [Parsing data constructors is hard] for the specific issue this particular class is solving.Process the head of a type-level function/constructor application, i.e. the H in H a b c. Disambiguate f x3 (function application or prefix data constructor). Disambiguate f @t (visible kind application) Disambiguate f # x (infix operator) Disambiguate {-# UNPACK #-} t (unpack/nounpack pragma)Disambiguate constructs that may appear when we do not know ahead of time whether we are parsing an expression, a command, or a pattern. See Note [Ambiguous syntactic categories]See Note [Body in DisambECP]Infix operator representation Function argument representationReturn a command without ambiguity, or fail in a non-command context.Return an expression without ambiguity, or fail in a non-expression context.Return a pattern without ambiguity, or fail in a non-pattern context.Disambiguate "let ... in ..."Bring superclass constraints on InfixOp into scope. See Note [UndecidableSuperClasses for associated types]%Disambiguate "f # x" (infix operator)Disambiguate "case ... of ..."6Disambiguate "... -> ..." (lambda), "case" and "cases"Bring superclass constraints on FunArg into scope. See Note [UndecidableSuperClasses for associated types])Disambiguate "f x" (function application).Disambiguate "f @t" (visible type application)'Disambiguate "if ... then ... else ..."'Disambiguate "do { ... }" (do notation)$Disambiguate "( ... )" (parentheses)2Disambiguate a variable "f" or a data constructor MkF."Disambiguate a monomorphic literal"Disambiguate an overloaded literalDisambiguate a wildcard'Disambiguate "a :: t" (type annotation)$Disambiguate "[a,b,c]" (list syntax)5Disambiguate "$(...)" and "[quasi|...|]" (TH splices)Disambiguate "f { a = b, ... }" syntax (record construction and record updates)Disambiguate "-a" (negation)-Disambiguate "(# a)" (right operator section)=Disambiguate "(a -> b)" (view pattern or function type arrow)4Disambiguate "%m" to the left of "->" (multiplicity)Disambiguate "forall a. b" and "forall a -> b" (forall telescope)" (constraint list)*Disambiguate "a => b" (constraint context)Disambiguate "a@b" (as-pattern) Disambiguate "~a" (lazy pattern) Disambiguate "!a" (bang pattern),Disambiguate tuple sections and unboxed sums%Disambiguate "type t" (embedded type)Validate infixexp LHS to reject unwanted {-# SCC ... #-} pragmasDisambiguate infix operators. See Note [Ambiguous syntactic categories]Result of parsing {-# UNPACK #-} or {-# NOUNPACK #-}.Essentially a wrapper for a RuleBndr GhcPsmkClassDecl builds a RdrClassDecl, filling in the names for tycon and datacon by deriving them from the name of the class. We fill in the names for the tycon and datacon corresponding to the class, by deriving them from the name of the class itself. This saves recording the names in the interface file (which would be equally good).Converts a list of 7s annotated with their  to binders without annotations. Only accepts specified variables, and errors if any of the provided binders has an  annotation. Converts 7 annotated with its  to one without annotations. Only accepts specified variables, and errors if the provided binder has an  annotation.Add the annotation for a 'where' keyword to existing  HsLocalBindsThe anchor for a stmtlist is based on either the location or the first semicolon annotion.Function definitions are restructured here. Each is assumed to be recursive initially, and non recursive definitions are discovered by the dependency analyser.Reinterpret a type constructor, including type operators, as a data constructor. See Note [Parsing data constructors is hard]Construct a GADT-style data constructor from the constructor names and their type. Some interesting aspects of this function:This splits up the constructor type into its quantified type variables (if provided), context (if provided), argument types, and result type, and records whether this is a prefix or record GADT constructor. See Note [GADT abstract syntax] in  GHC.Hs.Decls for more details.;This rather gruesome function is used mainly by the parser.Case #1. When parsing: data T a = T | T1 Int"we parse the data constructors as types? because of parser ambiguities, so then we need to change the  type constr to a  data constrThe exact-name case can occur when parsing: data [] a = [] | a : [a]3For the exact-name case we return an original name.Case #2. When parsing: /x = fn (forall a. a) -- RequiredTypeArgumentswe use setRdrNameSpace to set the namespace of forall-bound variables.Check whether the given list of type parameters are all type variables (possibly with a kind signature).Check if the gadt_constrlist is empty. Only raise parse error for `data T where` to avoid affecting existing error message, see #8258.Yield a parse error if we have a function applied directly to a do block etc. and BlockArguments is not enabled.Validate the context constraints and break up a context into a list of predicates.  (Eq a, Ord b) --> [Eq a, Ord b] Eq a --> [Eq a] (Eq a) --> [Eq a] (((Eq a))) --> [Eq a]  The same as , but for expressions.Validate the context constraints and break up a context into a list of predicates.  (Eq a, Ord b) --> [Eq a, Ord b] Eq a --> [Eq a] (Eq a) --> [Eq a] (((Eq a))) --> [Eq a] Annotate a type with either an {-# UNPACK #-} or a {-# NOUNPACK #-} pragma.Check for monad comprehensions1If the flag MonadComprehensions is set, return a T# context, otherwise use the usual T contextEnsure that a literal pattern isn't of type Addr#, Float#, Double#.Rejects declarations such as  data T = 'MkT (note the leading tick).Check if a fixity is valid. We support bypassing the usual bound checks for some special operators.#Hint about bang patterns, assuming  BangPatterns is off.Check whether  ListTuplePuns is enabled and return the first arg if it is, the second arg otherwise.Emit an error of type  with a location from start to end if the extension  ListTuplePuns is disabled.=This is used in Parser.y to guard rules that require punning.Call a parser with a span and its comments given by a start and end token.%Decide whether to parse tuple syntax  (Int, Double) in a type as a type or data constructor, based on the extension  ListTuplePuns.. The case with an explicit promotion quote, '(Int, Double), is handled by mkExplicitTupleTy.)Decide whether to parse tuple con syntax (,) in a type as a type or data constructor, based on the extension  ListTuplePuns.. The case with an explicit promotion quote, '(,), is handled by the rule SIMPLEQUOTE sysdcon_nolist in atype.*Decide whether to parse list tycon syntax [] in a type as a type or data constructor, based on the extension  ListTuplePuns.. The case with an explicit promotion quote, '[], is handled by mkExplicitListTy.)Decide whether to parse list type syntax [Int] in a type as a type or data constructor, based on the extension  ListTuplePuns.. The case with an explicit promotion quote, '[Int], is handled by mkExplicitListTy. precedence operators *        !  !  &  &  "  !       +None )Z $Return first success or first error.Primary case should be the first because it would determine returned error message#16895 Ensure an infix expression's operator is a variable/constructor. Consider this example: $(uInfixE [|1|] [|id id|] [|2|])This infix expression is obviously ill-formed so we use this helper function to reject such programs outright.The constructors  permits should be in sync with  pprInfixExp> in Language.Haskell.TH.Ppr from the template-haskell library.cvtOpApp x op y converts op and y' and produces the operator application x op y. The produced tree of infix expressions will be left-biased, provided x is.We can see that cvtOpApp9 is correct as follows. The inductive hypothesis is that cvtOpApp x op y is left-biased, provided x7 is. It is clear that this holds for both branches (of cvtOpApp:), provided we assume it holds for the recursive calls to cvtOpApp. When we call cvtOpApp from cvtl, the first argument will always be left-biased since we have already run cvtl on it.cvtOpAppP x op y converts op and y' and produces the operator application x op y. The produced tree of infix patterns will be left-biased, provided x is.See the cvtOpApp+ documentation for how this function works.Convert a Template Haskell  to an 6%. To avoid duplicating the logic in  here, we simply reuse  and perform surgery on the 7 it returns to turn it into an 6.Constructs an application of a type to arguments passed in a list.cvtOpAppT x op y converts op and y' and produces the operator application x op y. The produced tree of infix types will be right-biased, provided y is.See the cvtOpApp+ documentation for how this function works.Convert Maybe Kind to a type family result signature. Used with data families where naming of the result is not possible (thus only kind or no signature is possible).Convert type family result signature. Used with both open and closed type families.0Convert injectivity annotation of a type family.If passed an empty list of 7/s, this simply returns the third argument (an 7). Otherwise, return an 6 using the provided 7 and 7.If passed an empty   ., this simply returns the third argument (an 7). Otherwise, return an 6 using the provided 7 and 7. lc returns K if lc is empty and L lc otherwise.This is much like , except that it returns a @ (7 5). This is used specifically for constructing superclasses, datatype contexts (#20011), and contexts in GADT constructor types (#20590). We wish to avoid using L [] in the case of an empty contexts, as the pretty-printer always prints L" contexts, even if they're empty.(name of first constructor of parent typeconvert constructor nameparent constructor nameThe location of the returned 7" if it needs an explicit forall#The converted type variable bindersThe converted rho type8The complete type, quantified with a forall if necessary%The original Template Haskell contextThe location of the returned 7# if it needs an explicit contextThe converted contextThe converted tau type8The complete type, qualified with a context if necessary  ! . /  None)#Extract identifier from Alex state.Lex  for warning messages!Lex identifiers from a docstring.adornment length Token length2The remaining input beginning with the found tokenA precise identifier parserA precise identifier parserNone 6,Represents a predicate on the column number.ColumnBound | Int -> Bool --------------+----------------- ColumnFrom n | (>=n)+The semigroup instance corresponds to (&&).Warnings accumulated in HdkM.The state of HdkM.Add Haddock documentation accumulated in the parser state to a parsed HsModule.Reports badly positioned comments when -Winvalid-haddock is enabled.The inverse of | that merges partitioned items back into a flat list. Elements are put back into the order in which they appeared in the original program before partitioning, using BufPos to order them.=Precondition (unchecked): the input lists are already sorted.,Only for module exports, not module imports.module M (a, b, c) where -- use on this [LIE GhcPs] import I (a, b, c) -- do not use here!2Imports cannot have documentation comments anyway.  !  !        .  1  >  7  /  6      '  #  .  *  6  /  (     ! # (   NoneIInsert alignment checks (cf -falignment-sanitisation)  NonePReturn the UnitId of the home-unit. This is used to create labels.   . . * * ' 'None  +3Parse a Haskell module with Haddock comments. This is done in two steps: to build the AST# to insert Haddock comments into itThis and the signature module parser are the only parser entry points that deal with Haddock comments. The other entry points (, ', etc) do not insert them into the AST.Parse a Haskell signature module with Haddock comments. This is done in two steps: to build the AST# to insert Haddock comments into itThis and the module parser are the only parser entry points that deal with Haddock comments. The other entry points (, ', etc) do not insert them into the AST.Instead of getting the *enclosed* comments, this includes the *preceding* ones. It is used at the top level to get comments between top level declarations.Construct an EpToken from the location of the token, provided the span is not zero widthNone"Returns True! if passed string is a statement.Returns True, if passed string has an import declaration.Returns True+ if passed string is an import declaration.Returns True' if passed string is a declaration but  not a splice.None &')3General version of cantFindError which has some holes which allow GHC/GHCi to display slightly different error messages. 5 5! 2 23None +3  NoneA map storing all the different uses of a specific data constructor and the approximate source position that usage arose from. The > is an incrementing identifier which distinguishes each usage of a constructor in a module. It is paired with the source position the constructor was used at, if possible and a string which names the source location. This is the same information as is the payload for the A  constructor. A map from a ? to the best approximate source position that name arose from.Position and information about an info table. For return frames these are the contents of a   .  None 3Try to find the best source position surrounding a . The heuristic strips ticks from the current expression until it finds one which is from the module currently being compiled. This is the same method that the DWARF information uses to give locations to info tables.2It is usually a better alternative than using the - which is carefully propagated downwards by . It's "quick" because it works only using immediate context rather than looking at the parent context like NoneA4Initialize STG pretty-printing options from DynFlagsNone 3+3If the argument expression is (potential chain of) _, return the head of the app chain, and collect ticks/args along the chain. INVARIANT: If the app head is trivial, return the atomic Var/Lit that was wrapped in casts, empty case, ticks, etc. So keep in sync with q.           NoneNone|-Create HPC initialization C code for a moduleEach module compiled with -fhpc declares an initialisation function of the form `hpc_init_ module?()`, which is emitted into the _stub.c file and annotated with  attribute9((constructor)) so that it gets executed at startup time.The function's purpose is to call hs_hpc_module to register this module with the RTS, and it looks something like this: static void hpc_init_Main(void) __attribute__((constructor)); static void hpc_init_Main(void) { extern StgWord64 _hpc_tickboxes_Main_hpc[]; hs_hpc_module("Main",8,1150288664,_hpc_tickboxes_Main_hpc); }tNoneooooooNone}uSets of registersuA stack area is either the stack slot where a variable is spilled or the stack space where function arguments and results are passed.uReturns an alignment in bytes of a CmmExpr when it's a statically known integer constant, otherwise returns an alignment of 1 byte. The caller is responsible for using with a sensible CmmExpr argument.uuuuuuuuvvuuuuuuuuvvvvHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHFFFFFFFFFFFFFFFFEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEuuuuuuuuuuuuuuuuuuuuuuuuuuuuuFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHGHHHHHHHHHHHHHHHHHGGHHHHHHHHHGGGGHHGHHHHHGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHGGGGGFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEEEEEEEEEEEEEEEuuuuuuuuuuuFFFFFuuuuuuuuuuuuuFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFuuuuvvuuuuuuuuvuvvuvuuuuuuuv v  v  %v &v v  ,v  >v  !v  (v  %v  $v  2v  $v  +v  (v  'v v  v v v v v v v NoneNoneNoneNoneNoneì¬ƬŬĬ¬ìĬŬƬNoneȬǬˬʬɬǬȬɬʬˬNone̬ͬЬϬά̬ͬάϬЬNoneҬѬլԬӬѬҬӬԬլNone׬֬ڬ٬ج֬׬ج٬ڬNoneܬ۬߬ެݬ۬ܬݬެ߬NoneReturns M if this global register is stored in a caller-saves machine register.Here is where the STG register map is defined for each target arch. The order matters (for the llvm backend anyway)! We must make sure to maintain the order here with the order used in the LLVM calling conventions. Note that also, this isn't all registers, just the ones that are currently possibly mapped to real registers.None+ Tick scope identifier, allowing us to reason about what annotations in a Cmm block should scope over. We especially take care to allow optimisations to reorganise blocks without losing tick association in the process.The global scope is the "root" of the scope graph. Every scope is a sub-scope of the global scope. It doesn't make sense to add ticks to this scope. On the other hand, this means that setting this scope on a block means no ticks apply to it.Constructs a new sub-scope to an existing scope. This allows us to translate Core-style scoping rules (see  tickishScoped2) into the Cmm world. Suppose the following code:tick 1# case ... of A -> tick 2 ... B -> tick 3 ...We want the top-level tick annotation to apply to blocks generated for the A and B alternatives. We can achieve that by generating tick 1 into a block with scope a, while the code for alternatives A and B gets generated into sub-scopes a/b and a/c respectively.A combined scope scopes over everything that the two given scopes cover. It is therefore a sub-scope of either scope. This is required for optimisations. Consider common block elimination: A -> tick 2, case ... of C -> [common] B -> tick 3 case ... of D -> [common]We will generate code for the C and D alternatives, and figure out afterwards that it's actually common code. Scoping rules dictate that the resulting common block needs to be covered by both tick 2 and tick 3, therefore we need to construct a scope that is a child to *both* scope. Now we can do that - if we assign the scopes ac and bd to the common-ed up blocks, the new block could have a combined tick scope ac+bd, which both tick 2 and tick 3 apply to.A convention maps a list of values (function arguments or return values) to registers or stack locations. top-level Haskell functions use NativeDirectCall, which maps arguments to registers starting with R2, according to how many registers are available on the platform. This convention ignores R1, because for a top-level function call the function closure is implicit, and doesn't need to be passed.non-top-level Haskell functions, which pass the address of the function closure in R1 (regardless of whether R1 is a real register or not), and the rest of the arguments in registers or on the stack.a native return. The convention for returns depends on how many values are returned: for just one value returned, the appropriate register is used (R1, F1, etc.). regardless of whether it is a real register or not. For multiple values returned, they are mapped to registers or the stack./Slow entry points: all args pushed on the stackEntry to the garbage collector: uses the node reg! (TODO: I don't think we need this --SDM)Output all scope paths.Returns the head uniques of the scopes. This is based on the assumption that the Unique of SubScope identifies the underlying super-scope. Used for efficient equality and comparison, see below.Checks whether two tick scopes are sub-scopes of each other. True if the two scopes are equal.Combine two tick scopes. The new scope should be sub-scope of both parameters. We simplify automatically if one tick scope is a sub-scope of the other already.ݺߺ޺ĺǺʺȺ˺źɺºƺúںҺӺԺͺ̺ϺѺкպκֺۺغ׺ٺܺVĺǺʺȺ˺źɺºƺúںҺӺԺͺ̺ϺѺкպκֺۺغ׺ٺܺVݺߺ޺    "  &    ,  !      2  .  /  +    2  2  2  2  2  ,        #None>>  None+  None+3*Static data before or after SRT generation%Static data, after SRTs are generated8a literal value, size given by cmmLitRep of the literal. uninitialised data, N bytes long1string of 8-bit values only, not zero terminated.+an embedded binary file and its byte length!Info table as a haskell data typeCmmTopInfo is attached to each CmmDecl (see defn of CmmGroup), and contains the extra info (beyond the executable code) that belongs to that CmmDecl.ĻA top-level chunk, abstracted over the type of the contents of the basic blocks (Cmm or instructions are the likely instantiations).ǻRaw1 cmm group (TODO (osa): not sure what that means)ȻCmm group with SRTsɻCmm group before SRT generationʻCmm group after STG generationԻ?Should a data in this section be considered constant at runtimeػThe branch block id is that of the first block in the branch, which is that branch's entry pointػͻٻڻܻۻջֻ׻ϻԻлλӻһѻuuuuuuuuvvuuuuuuuuvvvvHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHݺߺ޺FFFFFFFFFFFFFFFFEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE»ɻȻ̻ûʻĻƻŻ˻ǻuuuuuuuuuuuuuuuuuuuuuuuuuuuuuFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHGHHHHHHHHHHHHHHHHHGGHHHHHHHHHGGGGHHGHHHHHGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHGGGGGĺǺʺȺ˺źɺºƺúںҺӺԺͺ̺ϺѺкպκֺۺغ׺ٺܺFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEEEEEEEEEEEEEEEaaaaaaaaVʻ̻ɻȻǻ˻»ûĻƻŻͻλϻлԻѻջֻ׻ػٻӻһaaaaaaaaڻܻۻݻ  '޻  !߻  +  ) 4    (  0    >    :            None)0Excludes void arguments (LocalReg is never void)always equal to c: of sli_id, i.e. unarised arity, including void arguments (), it's imperfect but works with wasm-ld.Defined symbols with  visibility.Target platformRepresentation of WebAssembly control flow. Normally written as  WasmControl s e pre post  Type parameter s is the type of (unspecified) statements. It might be instantiated with an open Cmm block or with a sequence of Wasm instructions. Parameter e( is the type of expressions. Parameter pre represents the values that are expected on the WebAssembly stack when the code runs, and post2 represents the state of the stack on completion.The w type variable in the Wasm IR stands for "platform word type", so  on wasm32, and  on wasm64. This way, we can make the codegen logic work on both wasm32/wasm64 in a type-safe manner.ĽMost are Cmm functions, but may also contain synthesized function of other types, sigh. No need to remember the symbols.We need to remember the symbols. Determinism is achieved by sorting symbols before writing the assembly.ͽNeither Cmm or Wasm type system takes integer signedness into account, therefore we always round up a u9 to the right width and handle it as an untyped integer.ؽWebAssembly doesn't really have proper read-only memory regions yet. Neverthless we add the .rodata logic here, wasm-ld will aggregate all .rodata sections into a single one, which adds possibility for runtime checks later, either via a customized runtime, or via code instrumentation. See https://github.com/llvm/llvm-project/blob/b296aed8ae239c20ebdd7969e978f8d2a3b9c178/lld/wasm/Writer.cpp#L856۽Represents whether a symbol is a data symbol or a function symbol. Unlike linkers for other targets, wasm-ld does panic at link-time if it finds symbol kind inconsistency between the definition site and other use sites.Currently we solely rely on isCFunctionLabel to determine a symbol's kind, but it does take extra effort to make it work. The main source of inconsistency arises from hand-written Cmm sources, where it's possible to refer to external entities like xxx_info and  xxx_closure without explicit import CLOSURE declarations. The Cmm parser will implicitly assume those are foreign function labels, and then this will break the WebAssembly backend. #22368 provides more context on this issue.9tl;dr for any GHC contributor that accidentally triggers wasm-ld errors when hacking Cmm: whatever data symbols are used in new code, just add the corresponding import CLOSURE+ declarations at the top of that Cmm file.߽,Not defined in the current compilation unit. ([ undefined binding=global vis=default ]0Defined, not visible to other compilation units. [ binding=local vis=default ],Defined, visible to other compilation units.Adds .globl/ directives in the output assembly. Also adds .hidden when not generating PIC code, similar to -fvisibility=hidden in clang. [ binding=global vis=hidden ],For simplicity, we record other metadata in / by need, instead of carrying them along with .The type of a WebAssembly function, loop, block, or conditional. This type says what values the code expects to pop off the stack and what values it promises to push. The WebAssembly standard requires that this type appear explicitly in the code.List of WebAssembly types used to describe the sequence of WebAssembly values that a block of code may expect on the stack or leave on the stack.+Singleton type useful for programming with  at the type level.WebAssembly type of a WebAssembly value that WebAssembly code could either expect on the evaluation stack or leave on the evaluation stack. The default # must be extracted from the final .Ƚɽ˽ʽ̽ͽֽҽӽϽнѽν׽սԽؽٽڽ½ýĽŽǽƽ۽ܽݽ޽߽޽߽۽ܽݽؽٽڽͽֽҽӽϽнѽν׽սԽȽɽ˽ʽ̽ǽƽ½ýĽŽ "   $  )  '  ) +0         !*   'None+3Module : GHC.Wasm.ControlFlow Description : Representation of control-flow portion of the WebAssembly instruction setNoneReturns the info table associated with the CmmDecl's entry point, if any.Return the list of BlockIds in a CmmDecl that are entry points for this proc (i.e. they may be jumped to from outside this proc).None ػ ػNone#Get bytes of a Float representation$Get bytes of a Double representationEmit a ".string" directiveEmit a ".incbin" directive+A NULL byte is added after the binary data.None7Llvm cast operations.Integer truncateInteger extend (zero fill)Integer extend (sign fill)Float truncate Float extendFloat to unsigned IntegerFloat to signed IntegerUnsigned Integer to FloatSigned Int to FloatPointer to IntegerInteger to Pointer6Cast between types where no bit manipulation is neededLlvm compare operations.Equal (Signed and Unsigned)Not equal (Signed and Unsigned)Unsigned greater thanUnsigned greater than or equalUnsigned less thanUnsigned less than or equalSigned greater thanSigned greater than or equalSigned less thanSigned less than or equal Float equalFloat not equalFloat greater thanFloat greater than or equalFloat less thanFloat less than or equal)Llvm binary operators machine operations.1add two integer, floating point or vector values.subtract two ...¾ multiply ..þ$unsigned integer or vector division.ľsigned integer ..ž*unsigned integer or vector remainder (mod)ƾ signed ...Ǿ(add two floating point or vector values.Ⱦsubtract two ...ɾ multiply ...ʾ divide ...˾ remainder ...̾ Left shift;3Logical shift right Shift right, filling with zeroξArithmetic shift right The most significant bits of the result will be equal to the sign bit of the left operand.ϾAND bitwise logical operation.оOR bitwise logical operation.ѾXOR bitwise logical operation.ҾLinkage type of a symbol.The description of the constructors is copied from the Llvm Assembly Language Reference Manual  -http://www.llvm.org/docs/LangRef.html#linkage5, because they correspond to the Llvm linkage types.ӾGlobal values with internal linkage are only directly accessible by objects in the current module. In particular, linking code into a module with an internal global value may cause the internal to be renamed as necessary to avoid collisions. Because the symbol is internal to the module, all references can be updated. This corresponds to the notion of the static keyword in C.Ծ Globals with linkonce linkage are merged with other globals of the same name when linkage occurs. This is typically used to implement inline functions, templates, or other code which must be generated in each translation unit that uses it. Unreferenced linkonce globals are allowed to be discarded.վweak linkage is exactly the same as linkonce linkage, except that unreferenced weak globals may not be discarded. This is used for globals that may be emitted in multiple translation units, but that are not guaranteed to be emitted into every translation unit that uses them. One example of this are common globals in C, such as int X; at global scope.־ appending linkage may only be applied to global variables of pointer to array type. When two global variables with appending linkage are linked together, the two global arrays are appended together. This is the Llvm, typesafe, equivalent of having the system linker append together sections/ with identical names when .o files are linked.׾The semantics of this linkage follow the ELF model: the symbol is weak until linked, if not linked, the symbol becomes null instead of being an undefined reference.ؾThe symbol participates in linkage and can be used to resolve external symbol references.پ Alias for ؾ3 but with explicit textual form in LLVM assembly.ھSymbol is private to the module and should not appear in the symbol table۾Functions can have a fixed amount of parameters, or a variable amount.޾1Different calling conventions a function can use.߾The C calling convention. This calling convention (the default if no other calling convention is specified) matches the target C calling conventions. This calling convention supports varargs function calls and tolerates some mismatch in the declared prototype and implemented declaration of the function (as does normal C).This calling convention attempts to make calls as fast as possible (e.g. by passing things in registers). This calling convention allows the target to use whatever tricks it wants to produce fast code for the target, without having to conform to an externally specified ABI (Application Binary Interface). Implementations of this convention should allow arbitrary tail call optimization to be supported. This calling convention does not support varargs and requires the prototype of al callees to exactly match the prototype of the function definition.This calling convention attempts to make code in the caller as efficient as possible under the assumption that the call is not commonly executed. As such, these calls often preserve all registers so that the call does not break any live ranges in the caller side. This calling convention does not support varargs and requires the prototype of all callees to exactly match the prototype of the function definition.The GHC-specific  registerised calling convention.Any calling convention may be specified by number, allowing target-specific calling conventions to be used. Target specific calling conventions start at 64. X86 Specific  convention. LLVM includes a specific alias for it rather than just using CC_Ncc.#Different types to call a function.(Normal call, allocate a new stack frame.7Tail call, perform the call in the current stack frame.Llvm Function Attributes.Function attributes are set to communicate additional information about a function. Function attributes are considered to be part of the function, not of the function type, so functions with different parameter attributes can have the same function type. Functions can have multiple attributes.Descriptions taken from )http://llvm.org/docs/LangRef.html#fnattrsThis attribute indicates that the inliner should attempt to inline this function into callers whenever possible, ignoring any active inlining size threshold for this caller.This attribute indicates that the source code contained a hint that inlining this function is desirable (such as the "inline" keyword in C/C++). It is just a hint; it imposes no requirements on the inliner.This attribute indicates that the inliner should never inline this function in any situation. This attribute may not be used together with the alwaysinline attribute.This attribute suggests that optimization passes and code generator passes make choices that keep the code size of this function low, and otherwise do optimizations specifically to reduce code size.This function attribute indicates that the function never returns normally. This produces undefined behavior at runtime if the function ever does dynamically return.This function attribute indicates that the function never returns with an unwind or exceptional control flow. If the function does unwind, its runtime behavior is undefined.This attribute indicates that the function computes its result (or decides to unwind an exception) based strictly on its arguments, without dereferencing any pointer arguments or otherwise accessing any mutable state (e.g. memory, control registers, etc) visible to caller functions. It does not write through any pointer arguments (including byval arguments) and never changes any state visible to callers. This means that it cannot unwind exceptions by calling the C++ exception throwing methods, but could use the unwind instruction.This attribute indicates that the function does not write through any pointer arguments (including byval arguments) or otherwise modify any state (e.g. memory, control registers, etc) visible to caller functions. It may dereference pointer arguments and read state that may be set in the caller. A readonly function always returns the same value (or unwinds an exception identically) when called with the same set of arguments and global state. It cannot unwind an exception by calling the C++ exception throwing methods, but may use the unwind instruction.This attribute indicates that the function should emit a stack smashing protector. It is in the form of a "canary"@a random value placed on the stack before the local variables that's checked upon return from the function to see if it has been overwritten. A heuristic is used to determine if a function needs stack protectors or not.If a function that has an ssp attribute is inlined into a function that doesn't have an ssp attribute, then the resulting function will have an ssp attribute.This attribute indicates that the function should always emit a stack smashing protector. This overrides the ssp function attribute.If a function that has an sspreq attribute is inlined into a function that doesn't have an sspreq attribute or which has an ssp attribute, then the resulting function will have an sspreq attribute.This attribute indicates that the code generator should not use a red zone, even if the target-specific ABI normally permits it.>This attributes disables implicit floating point instructions.This attribute disables prologue / epilogue emission for the function. This can have very system-specific consequences.LLVM Parameter Attributes.Parameter attributes are used to communicate additional information about the result or parameters of a functionThis indicates to the code generator that the parameter or return value should be zero-extended to a 32-bit value by the caller (for a parameter) or the callee (for a return value).This indicates to the code generator that the parameter or return value should be sign-extended to a 32-bit value by the caller (for a parameter) or the callee (for a return value).This indicates that this parameter or return value should be treated in a special target-dependent fashion during while emitting code for a function call or return (usually, by putting it in a register as opposed to memory).This indicates that the pointer parameter should really be passed by value to the function.This indicates that the pointer parameter specifies the address of a structure that is the return value of the function in the source program.This indicates that the pointer does not alias any global or any other parameter.This indicates that the callee does not make any copies of the pointer that outlive the callee itselfThis indicates that the pointer parameter can be excised using the trampoline intrinsics.An LLVM Function(Function align value, must be power of 2Parameter types and attributes'Indicates if this function uses varargsType of the returned value&The calling convention of the functionLinkageType of the function!Unique identifier of the functionLlvm Static Data.These represent the possible global level variables and constants.A comment in a static section#A static variant of a literal valueFor uninitialised dataDefines a static A static arrayA static structure typeA static structure typeA pointer to other dataTruncatePointer to Pointer conversionPointer to Integer conversionConstant addition operationConstant subtraction operationLlvm Literal Data.(These can be used inline in expressions.'Refers to an integer constant (i64 42).Floating point literal.Literal NULL, only applicable to pointer typesVector literal>Undefined value, random bit pattern. Useful for optimisations.LLVM VariablesVariables with a global scope.,Variables local to a function or parameters.Named local variables. Sometimes we need to be able to explicitly name variables (e.g for function arguments).A constant variableMutable global variableConstant global variableAlias of another variableAn LLVM section definition. If Nothing then let LLVM decide the section Llvm Types&An integer with a given width in bits.32 bit floating point64 bit floating point 80 bit (x86 only) floating point128 bit floating pointA pointer to a  An array of  A vector of A  can represent a label (address) Void typePacked structure typeUnpacked structure type A type alias LLVM Metadata3Function type, used to create pointers to functions A type aliasA String in LLVM4A global mutable variable. Maybe defined or externalReturn the value of the Returns the variable of the ] }' form).Metadata node declaration. ('!0 = metadata !{ }' form).Associates some metadata with a specific label for attaching to an instruction.LLVM metadata expressions)A reference to an un-named metadata node.     ! #'None;Llvm ExpressionsAllocate amount * sizeof(tp) bytes on the stack * tp: LlvmType to reserve room for * amount: The nr of tp's which must be allocatedPerform the machine operator op on the operands left and right * op: operator * left: left operand * right: right operandPerform a compare operation on the operands left and right * op: operator * left: left operand * right: right operandExtract a scalar element from a vector * val: The vector * idx: The index of the scalar within the vectorExtract a scalar element from a structure * val: The structure * idx: The index of the scalar within the structure Corresponds to "extractvalue" instruction.Insert a scalar element into a vector * val: The source vector * elt: The scalar to insert * index: The index at which to insert the scalarShuffle two vectors into a destination vector using given indicesAllocate amount * sizeof(tp) bytes on the heap * tp: LlvmType to reserve room for * amount: The nr of tp's which must be allocatedLoad the value at location ptr(Atomic load of the value at location ptrNavigate in a structure, selecting elements * inbound: Is the pointer inbounds? (computed pointer doesn't overflow) * ptr: Location of the structure * indexes: A list of indexes to select the correct value.Cast the variable from to the to type. This is an abstraction of three cast operators in Llvm, inttoptr, ptrtoint and bitcast. * cast: Cast type * from: Variable to cast * to: type to cast toAtomic read-modify-write operation * op: Atomic operation * addr: Address to modify * operand: Operand to operation * ordering: Ordering requirementCompare-and-exchange operation * addr: Address to modify * old: Expected value * new: New value * suc_ord: Ordering required in success case * fail_ord: Ordering required in failure case, can be no stronger than suc_ord Result is an i1, true if store was successful.Call a function. The result is the value of the expression. * tailJumps: CallType to signal if the function should be tail called * fnptrval: An LLVM value containing a pointer to a function to be invoked. Can be indirect. Should be LMFunction type. * args: Concrete arguments for the parameters * attrs: A list of function attributes for the call. Only NoReturn, NoUnwind, ReadOnly and ReadNone are valid here.Call a function as above but potentially taking metadata as arguments. * tailJumps: CallType to signal if the function should be tail called * fnptrval: An LLVM value containing a pointer to a function to be invoked. Can be indirect. Should be LMFunction type. * args: Arguments that may include metadata. * attrs: A list of function attributes for the call. Only NoReturn, NoUnwind, ReadOnly and ReadNone are valid here.Merge variables from different basic blocks which are predecessors of this basic block in a new variable of type tp. * tp: type of the merged variable, must match the types of the predecessor variables. * predecessors: A list of variables and the basic block that they originate from.Inline assembly expression. Syntax is very similar to the style used by GCC. * assembly: Actual inline assembly code. * constraints: Operand constraints. * return ty: Return type of function. * vars: Any variables involved in the assembly code. * sideeffect: Does the expression have side effects not visible from the constraints list. * alignstack: Should the stack be conservatively aligned before this expression is executed./A LLVM expression with metadata attached to it.Llvm StatementsAssign an expression to a variable: * dest: Variable to assign to * source: Source expressionMemory fence operation!Always branch to the target labelBranch to label targetTrue if cond is true otherwise to label targetFalse * cond: condition that will be tested, must be of type i1 * targetTrue: label to branch to if cond is true * targetFalse: label to branch to if cond is falseComment Plain comment.Set a label on this position. * name: Identifier of this label, unique for this moduleStore variable value in pointer ptr. If value is of type t then ptr must be of type t*. * value: Variable/Constant to store. * ptr: Location to store the value inMultiway branch * scrutinee: Variable or constant which must be of integer type that is determines which arm is chosen. * def: The default label if there is no match in target. * target: A list of (value,label) where the value is an integer constant and label the corresponding label to jump to if the scrutinee matches the value.Return a result. * result: The variable or constant to returnAn instruction for the optimizer that the code following is not reachableRaise an expression to a statement (if don't want result or want to use Llvm unnamed values.A nop LLVM statement. Useful as its often more efficient to use this then to wrap LLvmStatement in a Just or [].'LLVM atomic operations. Please see the  atomicrmw instruction in the LLVM documentation for a complete description.LLVM ordering types for synchronization purposes. (Introduced in LLVM 3.0). Please see the LLVM documentation for a better description.(Some partial order of operations exists.?A single total order for operations at a single address exists."Acquire synchronization operation."Release synchronization operation.,Acquire + Release synchronization operation.&Full sequential Consistency operation.An LLVM FunctionThe body of the functions. Prefix data%The section to put the function into,The function attributes.The functions arguments(The signature of this declared function.6An LLVM Module. This is a top level container in LLVM.&LLVM Functions defined in this module.LLVM Functions used in this module but defined in other modules.*Global variables to include in the module.LLVM meta data.LLVM Alias type definitions./Comments to include at the start of the module.A block of LLVM code.A list of LlvmStatement's representing the code for this block. This list must end with a control flow statement.The code label for this block Block labels        NonePrint out a whole LLVM module.Print out a multi-line comment, can be inside a function or on its own;Print out a comment, can be inside a function or on its own7Print out a list of global mutable variable definitions.Print out a global mutable variable definition&Print out a list of LLVM type aliases.Print out an LLVM type alias."Print out a list of LLVM metadata.&Print out an LLVM metadata definition.)Print out a list of function definitions. Print out a function definition.'Print out a function definition header.)Print out a list of function declaration.Print out a function declaration. Declarations define the function type but don't define the actual body of the function. Print out a list of LLVM blocks.Print out an LLVM block. It must be part of a function definition.Print out an LLVM block label.Print out an LLVM statement, with any metadata to append to the statement.Print out an LLVM expression.Should always be a function pointer. So a global var of function type (since globals are always pointers) or a local var of pointer function type.)Return the variable name or value of the * in Llvm IR textual representation (e.g. @x, %y or 42).)Return the variable name or value of the * in a plain textual representation (e.g. x, y or 42).Print a literal value. No type. Blank line.Exclamation point. NoneƿĿſÿֿԿӿҿտ׿̿Ͽ˿Ϳοпؿٿǿɿȿʿ޾߾Ҿ־׾پؾӾԾھվξϾǾʾɾ˾Ⱦ;¾оľƾ̾þžѾ۾ܾݾ޾߾۾ܾݾҾ־׾پؾӾԾھվξϾǾʾɾ˾Ⱦ;¾оľƾ̾þžѾҿӿԿտֿ׿ؿٿϿĿÿƿſȿʿǿɿ˿̿ͿοпNone) A typed register: a register, together with the specific format we are using it at.A typed virtual register: a virtual register, together with the specific format we are using it at.%Get the integer format of this width.-Check if a format represent an integer value.#Get the float format of this width.4Check if a format represents a floating point value.%Check if a format represents a vectorConvert a Cmm type to a Format.Get the Width of a Format.-Take all the virtual registers from this set.*Take all the real registers from this set.&number of elements (always at least 2)format of each element*+    )  "  !         None ;Get the LlvmVar function variable storing the real register;Get the LlvmVar function argument storing the real register>A list of STG Registers that should always be considered alive'STG Type Based Alias Analysis hierarchyId values The  node is the root (there can be more than one) of the TBAA hierarchy and as of LLVM 4.0 should *only* be referenced by other nodes. It should never occur in any LLVM instruction statement.Id values The  node is the root (there can be more than one) of the TBAA hierarchy and as of LLVM 4.0 should *only* be referenced by other nodes. It should never occur in any LLVM instruction statement.Id values The  node is the root (there can be more than one) of the TBAA hierarchy and as of LLVM 4.0 should *only* be referenced by other nodes. It should never occur in any LLVM instruction statement.Id values The  node is the root (there can be more than one) of the TBAA hierarchy and as of LLVM 4.0 should *only* be referenced by other nodes. It should never occur in any LLVM instruction statement.Id values The  node is the root (there can be more than one) of the TBAA hierarchy and as of LLVM 4.0 should *only* be referenced by other nodes. It should never occur in any LLVM instruction statement.Id values The  node is the root (there can be more than one) of the TBAA hierarchy and as of LLVM 4.0 should *only* be referenced by other nodes. It should never occur in any LLVM instruction statement.The TBAA metadata identifierGet the correct TBAA metadata information for this register type  NoneNone#Assignment of vregs to stack slots.3The slots that are still available to be allocated.Identifier for a stack slot.-An empty stack map, with all slots available.If this vreg unique already has a stack assignment then return the slot number, otherwise allocate a new slot, and update the map.4Return the number of stack slots that were allocatedNone9Addressing modes-A register plus some immediate integer, e.g. 8(sp) or -16(sp)'. The offset needs to fit into 12bits. A registerFirst integer register number. zero register.return address registerreturn address register8Last integer register number. Used as TMP (IP) register.8Last integer register number. Used as TMP (IP) register.8Last integer register number. Used as TMP (IP) register.First floating point register.First floating point register.Last floating point register.Not to be confused with the F FAll machine register numbers..Registers available to the register allocator.These are all registers minus those with a fixed role in RISCV ABI (zero, lr, sp, gp, tp, fp, tmp) and GHC RTS (Base, Sp, Hp, HpLim, R1..R8, F1..F6, D1..D6.)>Integer argument registers according to the calling conventionFloating point argument registers according to the calling conventionMap u to 1N.B. this is a partial function, because not all u$s have an immediate representation.regSqueeze_class reg Calculate the maximum number of register colors that could be denied to a node of this class due to having this reg as a neighbour.44      NoneK?Bitmaps to indicate which registers are free (currently unused)The bit index represents the , in case of floating point registers with an offset of 32. The register is free when the bit is set.Show bits as a : of 1s and 0s*Set bits of all allocatable registers to 1 Get all free /s (i.e. those where the corresponding bit is 1)#Set corresponding register bit to 0#Set corresponding register bit to 1#integer/general purpose registers ()floating point registers (RcDouble) * * # #NoneregSqueeze_class reg Calculate the maximum number of register colors that could be denied to a node of this class due to having this reg as a neighbour.//None   NoneLanguage ID used for Haskell..Mapping of registers to DWARF register numbers2Virtual register number to use for return address.None 6Common things that we can do with instructions, on all architectures. These are used by the shared parts of the native code generator, specifically the register allocators.Get the registers that are being used by this instruction. regUsage doesn't need to do any trickery for jumps and such. Just state precisely the regs read and written by that insn. The consequences of control flow transfers, as far as register allocation goes, are taken care of by the register allocator.Apply a given mapping to all the register references in this instruction.Checks whether this instruction is a jump/branch instruction. One that can change the flow of control in a way that the register allocator needs to worry about.Give the possible *local block* destinations of this jump instruction. Must be defined for all jumpish instructions.Check if the instr always transfers control flow to the given block. Used by code layout to eliminate jumps that can be replaced by fall through.Change the destination of this jump instruction. Used in the linear allocator when adding fixup blocks for join points.5An instruction to spill a register into a spill slot.6An instruction to reload a register from a spill slot.?See if this instruction is telling us the current C stack deltaCheck whether this instruction is some meta thing inserted into the instruction stream for other purposes.Not something that has to be treated as a real machine instruction and have its registers allocated. eg, comments, delta, ldata, etc.Copy the value in a register to another one. Must work for all register classes.Take the source and destination from this reg -> reg move instruction or Nothing if it's not oneMake an unconditional jump instruction. For architectures with branch delay slots, its ok to put a NOP after the jump. Don't fill the delay slot with an instruction that references regs or you'll confuse the linear allocator.Pretty-print an instructionHolds a list of source and destination registers used by a particular instruction.Machine registers that are pre-allocated to stgRegs are filtered out, because they are uninteresting from a register allocation standpoint. (We wouldn't want them to end up on the free list!)As far as we are concerned, the fixed registers simply don't exist (for allocation purposes, anyway).No regs read or written to.the reg to spillthe current stack deltaspill slots to use instructionsthe reg to reload.the current stack deltathe spill slot to use instructionssource registerdestination register &&Noneregisterimmediate valuememory reference2Variant of a floating point conversion instruction Operand of a FENCE instruction (r, w or rw)Comment pseudo-opMulti-line comment pseudo-op$Annotated instruction. Should print  instr # docLocation pseudo-op .loc (file, line, col, name),Static data spat out during code generation.Start a new basic block.Useful during codegen, removed later. Preceding instruction should be a jump, as per the invariants for a BasicBlock (see Cmm).=Specify current stack offset for benefit of subsequent passesPush a minimal stack frame consisting of the return address (RA) and the frame pointer (FP).%Pop the minimal stack frame of prior .5Arithmetic addition (both integer and floating point) rd = rs1 + rs28Arithmetic subtraction (both integer and floating point) rd = rs1 - rs2Logical AND (integer only) rd = rs1 & rs2Logical OR (integer only) rd = rs1 | rs2/Logical left shift (zero extened, integer only) rd = rs1 << rs20Logical right shift (zero extened, integer only) rd = rs1 >> rs23Arithmetic right shift (sign-extened, integer only) rd = rs1 >> rs22Store to memory (both, integer and floating point)> 64. Unsigned division (integer only) rd = |rn  rm|XOR (integer only)  rd = rn E op2!ORI with immediate (integer only)  rd = rn | op2 OR with immediate (integer only)  rd = rn E op2-Move to register (integer and floating point)rd = rn or  rd = #imm0Pseudo-op for conditional setting of a register. #if(o2 cond o3) op <- 1 else op <- 03A jump instruction with data for switch/jump tablesUnconditional jump (no linking)/Unconditional jump, links return address (sets ra/x1)$branch with condition (integer only)Fence instructionMemory barrier.Floating point conversionFloating point ABSolute valueMin dest = min(r1)Max.Floating-point fused multiply-add instructionsfmadd : d = r1 * r2 + r3fnmsub: d = r1 * r2 - r3fmsub : d = - r1 * r2 + r3fnmadd: d = - r1 * r2 - r3!Stack frame header size in bytes.The stack frame header is made of the values that are always saved (regardless of the context.) It consists of the saved return address and a pointer to the previous frame. Thus, its size is two stack frame slots which equals two addresses/words (2 * 8 byte).All registers are 8 byte wide.The number of bytes that the stack pointer should be aligned to. reg move instruction$We have to be a bit careful here: A  can also mean an implicit conversion. This case is filtered out.'Make an unconditional jump instruction. Decrement sp to allocate stack space.The stack grows downwards, so we decrement the stack pointer by n (bytes). This is dual to . sp is the RISCV stack pointer, not to be confused with the STG stack pointer.'Increment SP to deallocate stack space.The stack grows downwards, so we increment the stack pointer by n (bytes). This is dual to . sp is the RISCV stack pointer, not to be confused with the STG stack pointer.register to spillcurrent stack deltaspill slot to useregister to loadcurrent stack deltaspill slot to use = =   None>Extract BlockIdNever K for Riscv64 NCG.  None7Print appropriate alignment for the given section type.Currently, this always aligns to a full machine word (8 byte.) A future improvement could be to really do this per section type (though, it's probably not a big gain.)Print section header and appropriate alignment for that section."This will e.g. emit a header like:.section .text .balign 8+Output the ELF .size directive (if needed.)'Pretty print an immediate value in the data sectionThis does not include any checks. We rely on the Assembler to check for errors. Use + for immediates in instructions (operands.)Comment c with # cCommen c with // cComment c with * c * (multiline comment)3Pretty print an immediate operand of an instructionThe kinds of immediates we can use here is pretty limited: RISCV doesn't support index expressions (as e.g. Aarch64 does.) Floating points need to fit in range. As we don't need them, forbit them to save us from future troubles. Negate integer immediate operandThis function is partial and will panic if the operand is not an integer.Pretty print an operand2Pretty print register with calling convention nameThis representation makes it easier to reason about the emitted assembly code.Single precission  (floating-point)Double precission  (floating-point) is an immediate value is an immediate 0 value represents a label$Get the pretty-printed label from a /This function is partial and will panic if the  is not a label.Pretty-print an /This function is partial and will panic if the  is not supported. This can happen due to invalid operands or unexpected meta instructions.!Pretty print a conditional branchThis function is partial and will panic if the conditional is not supported; i.e. if its floating point related.Procedure name Block nameNone 3"Combination of target node id and information about the branch we are looking at.*(backEdge, loopBody), body includes headerBlockId -> LoopLevel mappingList of back edgesInformation about edges%Unknown, but not heap or stack check.Heap or stack checkCan we trace back a edge to a specific Cmm Node or has it been introduced during assembly codegen. We use this to maintain some information which would otherwise be lost during the Cmm <-> asm transition. See also Note [Inverting conditions]A control flow graph where edges have been annotated with a weight. Implemented as IntMap (IntMap ) We must uphold the invariant that for each edge A -> B we must have: A entry B in the outer map. A entry B in the map we get when looking up A. Maintaining this invariant is useful as any failed lookup now indicates an actual error in code which might go unnoticed for a while otherwise.Convenience function, generate edge info based on weight not originating from cmm.Adjust the weight between the blocks using the given function. If there is no such edge returns the original map.Set the weight between the blocks to the given weight. If there is no such edge returns the original map.!Is this block part of this graph?Check if the nodes in the cfg and the set of blocks are the same. In a case of a mismatch we panic and show the difference.Filter the CFG with a custom function f. Parameters are `f from to edgeInfo`Sometimes we insert a block which should unconditionally be executed after a given block. This function updates the CFG for these cases. So we get A -> B => A -> A' -> B -> C => -> C5Adds a new edge, overwrites existing edges if presentAdds a edge with the given weight to the cfg If there already existed an edge it is overwritten. `addWeightEdge from to weight cfg`4Destinations from bid ordered by weight (descending)1Get successors of a given node with edge weights./Returns a unordered list of all edges with info5Returns a unordered list of all edges without weights4Get successors of a given node without edge weights.8Invariant: The edge **must** exist already in the graph.Insert a block in the control flow between two other blocks. We pass a list of tuples (A,B,C) where * A -> C: Old edge * A -> B -> C : New Arc, where B is the new block. It's possible that a block has two jumps to the same block in the assembly code. However we still only store a single edge for these cases. We assign the old edge info to the edge A -> B and assign B -> C the weight of an unconditional jump.Generate weights for a Cmm proc based on some simple heuristics.Modify branch weights based on educated guess on patterns GHC tends to produce and how they affect performance.6Most importantly we penalize jumps across info tables.5Convert block-local branch weights to global weights.Determine loop membership of blocks based on SCC analysis This is faster but only gives yes/no answers.Determine loop membership of blocks based on Dominator analysis. This is slower but gives loop levels instead of just loop membership. However it only detects natural loops. Irreducible control flow is not recognized even if it loops. But that is rare enough that we don't have to care about that special case.We take in a CFG which has on its edges weights which are relative only to other edges originating from the same node.We return a CFG for which each edge represents a GLOBAL weight. This means edge weights are comparable across the whole graph.For irreducible control flow results might be imprecise, otherwise they are reliable.The algorithm is based on the Paper "Static Branch Prediction and Program Profile Analysis" by Y Wu, JR Larus The only big change is that we go over the nodes in the body of loops in reverse post order. Which is required for diamond control flow to work probably.We also apply a few prediction heuristics (based on the same paper)The returned result represents frequences. For blocks it's the expected number of executions and for edges is the number of traversals.Update branch weights based on certain heuristics. See Note [Static Branch Prediction] TODO: This should be combined with optimizeCFGEdges are sorted ascending pointwise by weight, source and destinationCareful! Since we assume there is at most one edge from A to B the Eq instance does not consider weight...                         ! ",NoneregSqueeze_class reg Calculate the maximum number of register colors that could be denied to a node of this class due to having this reg as a neighbour. 77 77  NoneNone Y (A basic block with liveness information.Stash regs live on entry to each basic block in the info part of the cmm code.Liveness information. The regs which die are ones which are no longer live in the *next* instruction in this sequence. (NB. if the instruction is a jump, these registers might still be live at the jump target(s) - you have to check the liveness at the destination block to find out).=registers that died because they were clobbered by something.=registers that died because they were read for the last time.?registers born in this instruction (written to for first time).)An instruction with liveness information.The register allocator also wants to use SPILL/RELOAD meta instructions, so we'll keep those here.A real machine instructionspill this reg to a stack slot!reload this reg from a stack slot5A top level thing which carries liveness information.$Map from some kind of register to a.While we give the type for keys as Reg which is the common case sometimes we end up using VirtualReq or naked Uniques. See Note [UniqFM and the register allocator]7map a function across all the basic blocks in this codemap a function across all the basic blocks in this code (monadic version)map a function across all the basic blocks in this code (monadic version)Slurp out the list of register conflicts and reg-reg moves from this top level thing. Slurping of conflicts and moves is wrapped up together so we don't have to make two passes over the same code when we want to build the graph.For spill/reloads+SPILL v1, slot1 ... RELOAD slot1, v2If we can arrange that v1 and v2 are allocated to the same hreg it's more likely the spill/reload instrs can be cleaned and replaced by a nop reg-reg move.4Strip away liveness information, yielding NatCmmDeclPretty-print a Map over instruction type in Strip away liveness information from a basic block, and make real spill instructions out of SPILL, RELOAD pseudos along the way.Erase Delta instructions.Patch the registers in this code according to this register mapping. also erase reg -> reg moves when the reg is the same. also erase reg -> reg moves when the destination dies in this instr.Patch registers in this LiveInstr, including the liveness information.Convert a NatCmmDecl to a LiveCmmDecl, with liveness informationCheck ordering of Blocks The computeLiveness function requires SCCs to be in reverse dependent order. If they're not the liveness information will be wrong, and we'll get a bad allocation. Better to check for this precondition explicitly or some other poor sucker will waste a day staring at bad assembly code..If we've compute liveness info for this code already we have to reverse the SCCs in each top to get them back to the right order so we can do it again.Computing livenessOn entry, the SCCs must be in "reverse" order: later blocks may transfer control to earlier ones only, else .The SCCs returned are in the *opposite* order, which is exactly what we want for the next pass.:Annotate a basic block with register liveness information.Calculate liveness going forwards, filling in when regs are bornCalculate liveness going backwards, filling in when regs die, and what regs are live across each instructionSCCs of blocks that we're about to run the liveness determinator on.$BlockIds that fail the test (if any)##  $ :    &  '  None&'The register allocator state<(from,fixup,to) : We inserted fixup code between from and to#Native code generator configurationRecord why things were spilled, for -ddrop-asm-stats. Just keep a list here instead of a map of regs -> reasons. We don't want to slow down the allocator if we're not going to emit the stats.?unique supply for generating names for join point fixup blocks.free stack slots for spillingcurrent stack delta assignment of temps to locationsfree machine registersthe current mapping from basic blocks to the register assignments at the beginning of that block.>Used to carry interesting stats out of the register allocator.<(from,fixup,to) : We inserted fixup code between from and toReasons why instructions might be inserted by the spiller. Used when generating stats for -ddrop-asm-stats.vreg was spilled to a slot so we could use its current hreg for another vreg-vreg was moved because its hreg was clobbered!vreg was loaded from a spill slot,reg-reg move inserted during join to targets,reg-mem move inserted during join to targetsA , together with the specific  it is used at.Where a vreg is currently stored A temporary can be marked as living in both a register and memory (InBoth), for example if it was recently loaded from a spill location. This makes it cheap to spill (no save instruction required), but we have to be careful to turn this into InReg if the value in the register is changed.vreg is in a registervreg is held in stack slots/vreg is held in both a register and stack slotsUsed to store the register assignment on entry to a basic block. We use this to handle join points, where multiple branch instructions target a particular label. We have to insert fixup code to make the register assignments from the different sources match up.1Find the register mapping for a specific BlockId.?Lookup which register a virtual register was first assigned to.An initial empty /Add new register mappings for a specific block.'Get the reg numbers stored in this Loc.##      !       ,5,7 ,8,;NoneBuild a map of how many times each reg was alloced, clobbered, loaded etc.+Count reg-reg moves remaining in this code.Pretty print some RegAllocStatsNone"The register allocator monad type.Smart constructor for , as described in Note [The one-shot state monad trick] in GHC.Utils.Monad.'Get native code generator configurationSpills and reloads that have been cleaned in this pass so far.6Spills and reloads cleaned each pass (latest at front)ŒMap of (slot -> blocks which reload from this slot) used to decide if whether slot spilled to will ever be reloaded from on this path.ÌCollecting up what regs were valid across each jump. in the next pass we can collate these and write the results to sJumpValid.Č0Regs which are valid at the start of each block.ŌCleaner monad.ƌThe identification number of a spill slot. A value is stored in a spill slot when we don't have a free register to hold it.;Clean out unneeded spill/reloads from this top level thing.njDo one pass of cleaning.ȌClean out unneeded reload instructions, while walking forward over the code.Ɍ'Clean out unneeded reload instructions.Walking forwards across the code On a reload, if we know a reg already has the same value as a slot then we don't need to do the reload.ʌ?Try and rewrite a reload instruction to something more pleasingˌClean out unneeded spill instructions, while walking backwards over the code.If there were no reloads from a slot between a spill and the last one then the slot was never read and we don't need the spill.SPILL r0 -> s1 RELOAD s1 -> r2 SPILL r3 -> s1 <--- don't need this spill SPILL r4 -> s1 RELOAD s1 -> r5Maintain a set of "slots which were spilled to but not reloaded from yet"Walking backwards across the code: a) On a reload from a slot, remove it from the set.a) On a spill from a slot If the slot is in set then we can erase the spill, because it won't be reloaded from until after the next spill.otherwise keep the spill and add the slot to the setTODO: This is mostly inter-block we should really be updating the noReloads set as we cross jumps also..TODO: generate noReloads from liveSlotsOnEntry̌Combine the associations from all the inward control flow edges.͌See if we have a reg with the same value as this slot in the association table.Ό$Construct the initial cleaner state.ό(Remember the associations before a jump.ЌCheck if this is a reg store.ьAn empty associationҌAdd an association between these two things. addAssoc :: Uniquable a => a -> a -> Assoc a -> Assoc aӌ"Delete all associations to a node.Ԍ*Delete a single association edge (a -> b).Ռ)Check if these two things are associated.֌Find the refl. trans. closure of the association from this point.׌Intersect two associations.nj!Iteration number for the cleaner.!Liveness annotated code to clean.Ɍ!the block that we're currently intwo store locations are associated if they have the same valueacc$instrs to clean (in backwards order)$cleaned instrs (in forward order)،!Slots live on entry to each block3Slots that have been spilled, but not reloaded fromacc#Instrs to clean (in forwards order)$Cleaned instrs (in backwards order)    None Reg moves, if the first reg dies at the same time the second reg is born then the mov only serves to join live ranges. The two regs can be renamed to be the same and the move instruction safely erased.Add a v1 = v2 register renaming to the map. The register with the lowest lexical name is set as the canonical version.Determine the canonical name for a register by following v1 = v2 renamings in this map.?Slurp out mov instructions that only serve to join live ranges.During a mov, if the source reg dies and the destination reg is born then we can rename the two regs to the same thing and eliminate the move.None9Holds interesting statistics from the register allocator.Target platform/Information to help choose which regs to spill.The initial, uncolored graph.Initial code, with liveness.#Code with spill instructions added.Spiller stats.The regs that were coalesced.(Code we tried to allocate registers for.0Spill/reload/reg-reg moves present in this code. Final code.-Code with unneeded spill/reloads cleaned out."Code with vregs replaced by hregs.Code with coalescings applied.Coalesced and colored graph.;Do all the different analysis on this list of RegAllocStatsDump a table of how many spill loads / stores were inserted for each vreg.Dump a table of how long vregs tend to live for in the initial code.Dump a table of how many conflicts vregs tend to have in the initial code.For every vreg, dump how many conflicts it has, and its lifetime. Good for making a scatter plot. Count spillreloadreg-reg moves. Lets us see how well the register allocator has done.global register conflict graph 3 None5The maximum number of build/spill cycles we'll allow.It should only take 3 or 4 cycles for the allocator to converge. If it takes any longer than this it's probably in an infinite loop, so it's better just to bail out and report a bug.7The top level of the graph coloring register allocator.;Perform solver iterations for the graph coloring allocator.We extract a register conflict graph from the provided cmm code, and try to colour it. If that works then we use the solution rewrite the code with real hregs. If coloring doesn't work we add spill code and try to colour it again. After  iterations we give up.Build a graph from the liveness and coalesce information in this code.Add some conflict edges to the graph. Conflicts between virtual and real regs are recorded as exclusions.Add some coalescence edges to the graph Coalescences between virtual and real regs are recorded as preferences.Patch registers in code using the reg -> reg mapping in this graph.#registers we can use for allocationset of available spill slots.current number of spill slots)code annotated with liveness information. CFG of basic blocks if availablecode with registers allocated, additional stacks required and stats for each stage of allocation4Number of solver iterations we've already performed.Function for calculating whether a register is trivially colourable.$Free registers that we can allocate.!Free stack slots that we can use.Number of spill slots in use!Current regalloc stats to add to.$Liveness annotated code to allocate.None!Armv6 | Armv7-A | Armv8-A AArch64 | | SIMD extension | NEON | NEON | |===========================================================================| | - Operates on 32-bit | - Separate reg. bank, | - Separate reg. bank, | | GP ARM registers | 32x64-bit NEON regs | 32x128-bit NEON regs | | - 8-bit16-bit integer | - 8163264-bit int | - 81632/64-bit int | | | - Single precision fp | - Single precision fp | | | | - Double precision fp | | | | - Single/Double fp are | | | | IEEE compliant | | - 2x16-bit/4x8-bit ops | - Up to 16x8-bit ops | - Up to 16x8-bit ops | | per instruction | per instruction | per instruction | '---------------------------------------------------------------------------' 3 3 0 0None,SXTW Operand Operand | SXTX Operand Operand;ADC Operand Operand Operand -- rd = rn + rm + C | ADCS ...ADDS Operand Operand Operand -- rd = rn + rm | ADR ... | ADRP ...MADD ... | MNEG ...6NEGS ... | NGC ... | NGCS ... | SBC ... | SBCS ...&SMADDL ... | SMNEGL ... | SMSUBL ...SUBS ...UMADDL ... -- Xd = Xa + Wn  Wm | UMNEGL ... -- Xd = - Wn  Wm | UMSUBL ... -- Xd = Xa - Wn  WmREV32 Operand Operand -- rd = reverseBytes32(rn) - 64bit operands only! -- 0xAABBCCDD_EEFFGGHH -> 0XDDCCBBAA_HHGGFFEEMOVN Operand Operand.Floating-point fused multiply-add instructionsfmadd : d = r1 * r2 + r3fnmsub: d = r1 * r2 - r3fmsub : d = - r1 * r2 + r3fnmadd: d = - r1 * r2 - r3 ((StgWord32)0x13faU) (-5114) :: W32 ===> ((StgWord32)(-0x13faU))We use casts to support types smaller than `unsigned int`; C literal suffixes support longer but not shorter types.ӍConstruct a constructor/finalizer function. Instead of emitting a initializer/finalizer array we rather just emit a single function, annotated with the appropriate C attribute, which then calls each of the initializers.       NoneԍIs the SRT offset field inline in the info table on this platform?See the section "Referring to an SRT from the info table" in Note [SRTs] in GHC.Cmm.Info.BuildValue of the srt field of an info table when using an StgLargeSRTՍWrap a u in an alignment check when -falignment-sanitisation is enabled.:Takes a closure pointer and returns the info table pointerTakes an info pointer (the first word of a closure) and returns its entry codeTakes a closure pointer, and return the *zero-indexed* constructor tag obtained from the info table This lives in the SRT field of the info table (constructors don't need SRTs).Takes a closure pointer, and return the closure type obtained from the info tableTakes an info pointer (the first word of a closure) and returns a pointer to the first word of the standard-form info table, excluding the entry-code word (if present)Takes an info table pointer (from infoTable) and returns the constr tag field of the info table (same as the srt_bitmap field)Takes an info table pointer (from infoTable) and returns the srt_bitmap field of the info tableTakes an info table pointer (from infoTable) and returns the closure type field of the info table.Takes the info pointer of a function, and returns a pointer to the first word of the StgFunInfoExtra struct in the info table.Takes the info pointer of a function, returns the function's arityByte offset of the SRT bitmap half-word which is in the *higher-addressed* part of the type_lit)Byte offset of the closure type half-word֍Returns: 1. The bitmap (literal value or label) 2. Large bitmap CmmData if neededNone9 Fused multiply-add instructions.FMADD: rd = (ra * rb) + rdFMSUB: rd = ra * rb - rdFNMADD: rd = -(ra * rb + rd)FNMSUB: rd = -(ra * rb - rd)Get the registers that are being used by this instruction. regUsage doesn't need to do any trickery for jumps and such. Just state precisely the regs read and written by that insn. The consequences of control flow transfers, as far as register allocation goes, are taken care of by the register allocator.Apply a given mapping to all the register references in this instruction.Checks whether this instruction is a jump/branch instruction. One that can change the flow of control in a way that the register allocator needs to worry about.Checks whether this instruction is a jump/branch instruction. One that can change the flow of control in a way that the register allocator needs to worry about.Change the destination of this jump instruction. Used in the linear allocator when adding fixup blocks for join points.5An instruction to spill a register into a spill slot.The size of a minimal stackframe header including minimal parameter save area.׍The maximum number of bytes required to spill a register. PPC32 has 32-bit GPRs and 64-bit FPRs, while PPC64 has 64-bit GPRs and 64-bit FPRs. So the maximum is 8 regardless of platforms unlike x86. Note that AltiVec's vector registers are 128-bit wide so we must not use this to spill them. reg move instruction or Nothing if it's not oneNone ! !NoneڍOutput the ELF .size directive.ۍ7Print appropriate alignment for the given section type.܍Procedure nameNone+(Expressions, used for unwind information literal valueregister plus offsetpointer dereferencingMaps registers to expressions that yield their "old" values further up the stack. Most interesting for the stack pointer Sp, but might be useful to document saved registers, too. Note that a register's value will be K= when the register's previous value cannot be reconstructed.A label associated with an ݍIntermediate data structure holding debug-relevant context information about a block.Debug information about a block of code. Ticks scope over nested blocks. Nested blocks+Output position relative to other blocks. Nothing# means the block was optimized outBest source tick covering blockTicks defined in this block9The parent of this proc. See Note [Splitting DebugBlocks]Has an info table? Output label Hoopl labelEntry label of containing procExtract debug data from a group of procedures. We will prefer source notes that come from the given module (presumably the module that we are currently compiling).ލ1Build a map of blocks sorted by their tick scopesThis involves a pre-order traversal, as we want blocks in rough control flow order (so ticks have a chance to be sorted in the right order).Sets position and unwind table fields in the debug block tree according to native generated code.9Converts debug blocks into a label map for easier lookupsConversion of Cmm expressions to unwind expressions. We check for unsupported operator usages and simplify the expression as far as possible.  )  * ) None What kind of min4max operation: signed or unsigned vector integer min3max, or (scalar or vector) floating point min/max?MIN or MAXX86 scalar move instruction.When used at a vector format, only moves the lower 64 bits of data; the rest of the data in the destination may either be zeroed or preserved, depending on the specific format and operands.MOVD/MOVQ SSE2 instructions (bitcast between a general purpose register and a float register). Format is input format, output format is calculated in the  function.The format argument is the size of operand 1 (the number of bits we keep) We always zero *all* high bits, even though this isn't how the actual instruction works. The code generator also seems to rely on this behaviour and it's faster to execute on many cpus as well so for now I'm just documenting the fact.!AVX bitwise logical XOR operation#FMA3 fused multiply-add operations.X86 call instruction-SSE2 unaligned move of floating-point vectors,AVX unaligned move of floating-point vectors8SSE2 move between memory and low-part of an xmm register8SSE move between memory and high-part of an xmm register&SSE2 unaligned move of integer vectors%AVX unaligned move of integer vectorsMove two 32-bit floats from the high part of an xmm register to the low part of another xmm register.Returns which registers are read and written as a (read, written) pair.ߍ8Is this register interesting for the register allocator?Applies the supplied function to all registers in instructions. Typically used to change virtual registers to real registers.Make a spill instruction. Make a spill reload instruction.A move instruction for moving the entire contents of an operand at the given .?See if this instruction is telling us the current C stack delta Make a reg-reg move instruction.Check whether an instruction represents a reg-reg move. The register allocator attempts to eliminate reg->reg moves whenever it can, by assigning the src and dest temporaries to the same real register.)Make an unconditional branch instruction.On most OSes the kernel will place a guard page after the current stack page. If you allocate larger than a page worth you may jump over this guard page. Not only is this a security issue, but on certain OSes such as Windows a new page won't be allocated if you don't hit the guard. This will cause a segfault or access fault.This function defines if the current allocation amount requires a probe. On Windows (for now) we emit a call to _chkstk for this. For other OSes this is not yet implemented. See  https://docs.microsoft.com/en-us/windows/desktop/DevNotes/-win32-chkstk& The Windows stack looks like this:SP GUARD PAGE  UNMAPPED In essence each allocation larger than a page size needs to be chunked and a probe emitted after each page allocation. You have to hit the guard page so the kernel can map in the next page, otherwise you'll segfault. See Note [Windows stack allocations]. Jump target,Arguments (required for register allocation)     None-Output an internal proc label. See Note [Internal proc labels] in CLabel.Output the ELF .size directive.Print section header and appropriate alignment for that section.7Print appropriate alignment for the given section type.Procedure name Block nameNone   = = 7 7 1 1NoneFor a jump instruction at the end of a block, generate fixup code so its vregs are in the correct regs for its destination..Construct a graph of register/spill movements.1Cyclic components seem to occur only very rarely.We cut some corners by not handling memory-to-memory moves. This shouldn't happen because every temporary gets its own stack slot.Expand out the destination, so InBoth destinations turn into a combination of InReg and InMem.Generate fixup code for a particular component in the move graph This component tells us what values need to be moved to what destinations. We have eliminated any possibility of single-node cycles in expandNode above.(Move a vreg between these two locations.maps the unique of the blockid to the set of vregs that are known to be live on the entry to each block.id of the current block,branch instr on the end of the source block.maps the unique of the blockid to the set of vregs that are known to be live on the entry to each block.acc blocks of fixup code.id of the current block,branch instr on the end of the source block.&branch destinations still to consider.source of movedestination of movecurrent C stack delta.%unique of the vreg that we're moving.source location.destination location.move instruction.None5 Constraints on the instruction instances used by the linear allocator.Do register allocation on some basic blocks. But be careful to allocate a block in an SCC only if it has an entry in the block map or it is the first block.*Do register allocation on this basic blockLoad the freeregs and current reg assignment into the RegM state for the basic block with this BlockId.-Do allocation for a sequence of instructions.'Do allocation for a single instruction.Mark all these real regs as allocated, and kick out their vreg assignments.Given a virtual reg find a preferred real register. The preferred register is simply the first one the variable was assigned to (if any). This way when we allocate for a loop variables are likely to end up in the same registers at the end and start of the loop, avoiding redundant reg-reg moves. Note: I tried returning a list of past assignments, but that turned out to barely matter.:Calculate a new location after a register has been loaded.=Load up a spilled temporary if we need to (read from memory). entry points&live regs on entry to each basic block$instructions annotated with "deaths" entry points&live regs on entry to each basic block$instructions annotated with "deaths"&live regs on entry to each basic block"block to do register allocation onblock with registers allocated2map of what vregs are live on entry to each block.'id of the current block, for debugging..liveness annotated instructions in this block.2map of what vregs are love on entry to each block./accumulator for instructions already processed.*the id of the current block, for debugging9the instr to have its regs allocated, with liveness info.'None) \Two 32-bit regs used as a single virtual 64-bit register and the code to set them appropriately8Two 32-bit regs used as a single virtual 64-bit registerHaving a CFG with additional information is essential for some operations. However we can't reconstruct all information once we generated instructions. So instead we update the CFG as we go.&Stack offset for unwinding informationA Native Code Generator implementation is parametrised over * The type of static data (typically related to  CmmStatics>) * The type of instructions * The type of jump destinationsTurn the sequence of jcc l1; jmp l2 into jncc l2;  when possible.given the instruction sequence of a block, produce a list of the block's 2s See Note [What is this unwinding business?] in GHC.Cmm.DebugBlock= and Note [Unwinding information in the NCG] in this module.The list of block ids records the redirected jumps to allow us to update the CFG. is only for printing internal labels. See Note [Internal proc labels] in CLabel.1Change the jump destination(s) of an instruction.Rewrites the destination of a jump instruction to another destination, if the given function returns a new jump destination for the  of the original destination.For instance, for a mapping block_a -> dest_b and a instruction  goto block_a& we would rewrite the instruction to  goto dest_bReplace references to blockIds with other destinations - used to update jump tables.Does this jump always jump to a single destination and is shortcutable?We use this to determine whether the given instruction is a shortcutable jump to some destination - See Note [supporting shortcutting] Note that if we return a destination here we *most* support the relevant shortcutting in shortcutStatics for jump tables and shortcutJump for the instructions itself.Given a jump destination, if it refers to a block, return the block id of the destination.Get CFG edge weights%Record that we added a block between from and old.Place  after block' and change any edges block -> X to  -> X Return a virtual 64-bit register7Convert a 64-bit LocalReg into two virtual 32-bit regs.9Used to handle 64-bit "registers" on 32-bit architectures'Get native code generator configurationHelper to check whether the data resides in a DLL or not, see  labelDynamicSays what we have to add to our 'PIC base register' in order to get the address of a label.   ' None&+<1Where is a reference to data on the stack passed?In a register. On the stack.An argument passed on the stack, either directly or by reference, with additional padding information.(Pass the argument on the stack directly.Pass the argument by reference.padding required (in bytes)padding of the data pointed to (the reference itself never requires padding)the size of the data pointed towhere the reference is passedAn argument passed on the stack, either directly or by reference.6The padding information hasn't yet been computed (see ).(Pass the argument on the stack directly.Pass the argument by reference.the size of the data pointed to7is the reference passed in a register, or on the stack?Information needed to know how to pass arguments in a C call, and in particular how to load them into registers.The code to assign arguments to registers used for argument passing.2Which registers are we using for argument passing?*Additional values to store onto the stack.,Arguments that should be passed on the stack+Memory addressing modes passed up the tree.Register's passed up the tree. If the stix code forces the register to live in a pre-decided machine register, it comes out as Fixed#; otherwise, it comes out as Any>, and the parent can decide which register to put it in.#Condition codes passed up the tree.s are the insn sequences generated by the insn selectors. They are really trees of insns to facilitate fast appending, where a left-to-right traversal yields the insns in the correct order.Convert  instructions into ) instructions to capture changes in the sp: register. See Note [What is this unwinding business?] in GHC.Cmm.DebugBlock for details.bid refers to the current block and is used to update the CFG if new blocks are inserted in the control flow. See Note [Keeping track of the current block] for more details.Grab the Reg for a CmmRegCheck whether an integer will fit in 32 bits. A CmmInt is intended to be truncated to the appropriate number of bits, so here we truncate it to Int64. This is important because e.g. -1 as a CmmInt might be either -1 or 18446744073709551615.(Convert a BlockId to some CmmStatic dataThe dual to getAnyReg: compute an expression into a register, but we don't mind which one it is. Convert a u' representing a memory address into an .An  is a datatype representing a valid address form for the target (e.g. "Base + Index + disp" or immediate) and the code to compute it.Like , but on 32-bit use simple register addressing (i.e. no index register). This stops us from running out of registers on x86 when using instructions such as cmpxchg, which can use up to three virtual registers and one fixed register.Given a , produce a new  with an instruction block which will check the value for alignment. Used for -falignment-sanitisation.6Load the value at the given address into any register.%We return the instructions generated.See Note [Evaluate C-call arguments before placing in destination registers]Might the code to put this expression into a register clobber any other registers?1Generate C call to the given function in ghc-prim-Generate C call to the given function in libc0Generate C call to the given function in the RTSGenerate a real C call to the given address with the given conventionHow much space does this  take up on the stack?Only counts the "reference" part for references, not the data it points to.?Pad arguments, assuming we start aligned to a 16-byte boundary.Returns padded arguments, together with whether we end up aligned to a 16-byte boundary.(Load arguments into available registers.=Load arguments into available registers (System V AMD64 ABI).Generate code for a fused multiply-add operation, of the form   x * y  z*, with 3 operands (FMA3 instruction set).This works on the invariant that all jumps in the given blocks are required. Starting from there we try to make a few more jumps redundant by reordering them. We depend on the information in the CFG to do so so without a given CFG we do nothing.Count trailing zeroesCount trailing zeroes#64-bit width on 32-bit architectureCount trailing zeroes!Generic case (width <= word size) Copy memoryUnroll memcpy calls if the number of bytes to copy isn't too large (cf ncgInlineThresholdMemcpy). Otherwise, call C's memcpy.Set memory to the given byteUnroll memset calls if the number of bytes to copy isn't too large (cf ncgInlineThresholdMemset). Otherwise, call C's memset. 7Basic block these statement will start to be placed in. Cmm StatementResulting instruction6Basic block this statement will start to be placed in.Instructions, and bid of new block if successive statements are placed in a different basic block.function to callwhere to put the resultarguments (of mixed type)The block we are inThe block we are inMachOpwhere to put the resultarguments (of mixed type)the block we are inMachOpwhere to put the resultarguments (of mixed type)address of the function to callcalling conventionwhere to put the resultarguments (of mixed type)address of function to callcalling conventionwhere to put the resultarguments (of mixed type)padding (in bytes)arguments proper (i.e. don't include the data for arguments passed by reference)%arguments we are passing on the stackCFG if presentBlocks with info tablesList of basic blocks             None:-Instruction instance for x86 instruction set. 1 1None#+Register's passed up the tree.If the stix code forces the register to live in a pre-decided machine register, it comes out as Fixed; otherwise, it comes out as Any9, and the parent can decide which register to put it in.9s are the insn sequences generated by the insn selectors.They are really trees of insns to facilitate fast appending, where a left-to-right traversal yields the insns in the correct order. Utilities Annotate an  with a  comment"Generate jump to jump table target9The index into the jump table is calulated by evaluating expr. The corresponding table entry contains the relative address to jump to (relative to the jump table's first entry / the table's own label).&Generate jump table data (if required)The idea is to emit one table entry per case. The entry is the relative address of the block to jump to (relative to the table's first entry / table's own label.) The calculation itself is done by the linker.Sometimes we need to change the Format of a register. Primarily during conversion.Grab a  for a FF"s are assigned virtual registers (), F s are assigned real registers (). It is an error if a F is not a STG register.'Compute an expression into any register6Compute an expression into any floating-point registerIf the initial expression is not a floating-point expression, finally move the result into a floating-point register.Map u to 1N.B. this is a partial function, because not all u$s have an immediate representation.Ž Compute a u into a ÎThe register width to be used for an operation on the given width operand.ĎInstructions to sign-extend the value in the given register from width w up to width w'.Ŏ Sign extends to 64bit, if neededSource  r? stays untouched, while the conversion happens on destination  r'.ƎSign extends to 64bit, if needed and reduces the precission to the target E (w')Source  r? stays untouched, while the conversion happens on destination  r'.ǎInstructions to truncate the value in the given register from width w to width w'.In other words, it just cuts the width out of the register. N.B.: This ignores signedness (no sign extension takes place)!ȎGiven a , produce a new  with an instruction block which will check the value for alignment. Used for -falignment-sanitisation.ɎProvide the value of a u with an ʎN.B. this function should be used to provide operands to load and store instructions with signed 12bit wide immediates (S & I types). For other immediate sizes and formats (e.g. B type uses multiples of 2) this function would need to be adjusted.ˎ+Generate conditional branching instructions.This is basically an "if with else" statement.̎ Generate a call to a C function.0Integer values are passed in GP registers a0-a7.9Floating point values are passed in FP registers fa0-fa7.If there are no free floating point registers, the FP values are passed in GP registers.If all GP registers are taken, the values are spilled as whole words (!) onto the stack..For integers/words, the return value is in a0.The return value is in fa0 if the return type is a floating point value.͎"A conditional jump to a far targetBy loading the far target into a register for the jump, we can address the whole memory range.Ύ%An unconditional jump to a far targetBy loading the far target into a register for the jump, we can address the whole memory range.ώCmm StatementsResulting instructionЎResulting instructionsɎwidth of loaded valueˎthe true branch targetthe false branch target the condition on which to branch InstructionsNone% instance for RV64 ) ) None+юRegister's passed up the tree. If the stix code forces the register to live in a pre-decided machine register, it comes out as Fixed#; otherwise, it comes out as Any>, and the parent can decide which register to put it in.s are the insn sequences generated by the insn selectors. They are really trees of insns to facilitate fast appending, where a left-to-right traversal yields the insns in the correct order.s are the insn sequences generated by the insn selectors. They are really trees of insns to facilitate fast appending, where a left-to-right traversal (pre-order?) yields the insns in the correct order.ҎGrab the Reg for a CmmRegӎ(Convert a BlockId to some CmmStatic dataԎCompute an expression into a register, but we don't mind which one it is.Վ6Generate code for a 4-register FMA instruction, e.g. 'fmadd rt ra rc rb := rt <- ra * rc + rb.None- Instruction instance for powerpc , ,None *  # %*None 3F֎A non empty ordered sequence of basic blocks. It is suitable for serialization in this order.We use OrdList instead of [] to allow fast append on both sides when combining chains.׎Maps blocks near the end of a chain to it's chain AND the other blocks near the end. [A,B,C,D,E] Gives entries like (B -> ([A,B], [A,B,C,D,E])) where [A,B] are blocks in the end region of a chain. This is cheaper then recomputing the ends multiple times.؎Look at X number of blocks in two chains to determine if they are "neighbours".َGiven the Chain A -> B -> C -> D and we break at C we get the two Chains (A -> B, C -> D) as result.ڎFor a given list of chains and edges try to combine chains with strong edges between them.ێPlace basic blocks based on the given CFG. See Note [Chain based CFG serialization]܎Remove redundant jumps between blocks when we can rely on fall through.ڎEdges to considerCurrent chains of blocksResulting list of block chains, and a set of edges which were used to fuse chains and as such no longer need to be considered.ێ)Keys indicate an info table on the block.&Control flow graph and some meta data."List of basic blocks to be placed.Blocks placed in sequence.CFG if we have one.Function to serialize  !    NoneRInitialize the native code generator configuration from the DynFlagsNone'Unwind instructions for a block. Will become part of the containing FDE.these unwind points must occur in the same order as they occur in the blockUnwind instructions for an individual procedure. Corresponds to a "Frame Description Entry" (FDE) in DWARF.%List of blocks. Order must match asm!Information about unwind instructions for a procedure. This corresponds to a "Common Information Entry" (CIE) in DWARF.A DWARF address range. This is used by the debugger to quickly locate which compilation unit a given address belongs to. This type assumes a non-segmented address-space.ݎ;Abbreviation codes used for encoding above records in the  .debug_info section.ގ)Pseudo, used for marking the end of listsIndividual dwarf records. Each one will be encoded as an entry in the  .debug_info section.)label of DIE belonging to the parent tickߎ1Generate assembly for the given abbreviation codeAbbreviation declaration. This explains the binary encoding we use for representing 1. Be aware that this must be updated along with . Generate assembly for DWARF data+Print a CLabel name in a ".stringz "LABEL""Prints assembler data corresponding to DWARF info records. Note that the binary format of this is parameterized in  abbrevDecls and has to be kept in synch.'Close a DWARF info record with children4Print assembler directives corresponding to a DWARF .debug_aranges address table entry.Header for the  .debug_frame section. Here we emit the "Common Information Entry" record that establishes general call frame parameters and the default stack layout.Writes a "Frame Description Entry" for a procedure. This consists mainly of referencing the CIE and writing state machine instructions to describe how the frame base (CFA) changes.Generates unwind information for a block. We only generate instructions where unwind information actually changes. This small optimisations saves a lot of space, as subsequent blocks often have the same unwind information.+Get DWARF register ID for a given GlobalRegGenerate code for setting the unwind information for a register, optimized using its known old value in the table. Note that Sp/ is special: We see it as synonym for the CFA.'Print the register number of the given F' as an unsigned LEB128 encoded number.Generates a DWARF expression for the given unwind expression. If spIsCFA is true, we see Sp0 as the frame base CFA where it gets mentioned.Generate code for re-setting the unwind information for a register to  undefined)Align assembly at (machine) word boundary1Assembly for a single byte of constant DWARF data(Assembly for a two-byte constant integer"Assembly for a constant DWARF flag*Assembly for 4 bytes of dynamic DWARF data+Assembly for 4 bytes of constant DWARF dataAssembly for a DWARF word of dynamic data. This means 32 bit, as we are generating 32 bit DWARF.Assembly for a machine word of dynamic data. Depends on the architecture we are currently generating code for.Prints a number in "little endian base 128" format. The idea is to optimize for small numbers by stopping once all further bytes would be 0. The highest bit in every byte signals whether there are further bytes to read.Same as  pprLEBWord, but for a signed numberGenerates a dynamic null-terminated string. If required the caller needs to make sure that the string is escaped properly.>Generate a string constant. We take care to escape the string.%Escape a single non-unicode characterGenerate an offset into another section. This is tricky because this is handled differently depending on platform: Mac Os expects us to calculate the offset using assembler arithmetic. Linux expects us to just reference the target directly, and will figure out on their own that we actually need an offset. Finally, Windows has a special directive to refer to relative offsets. Fun.4the register to produce an unwinding table entry for&the old and new values of the register..  .  None{  Generate DWARF/debug informationBuild an address range entry for one proc. With split sections, each proc needs its own entry, since they may get scattered in the final binary. Without split sections, we could make a single arange based on the first/last proc.Header for a compilation unit, establishing global format parametersCompilation unit footer, mainly establishing size of debug sectionsSplits the blocks by procedures. In the result all nested blocks will come from the same procedure as the top-level block. See Note [Splitting DebugBlocks] for details./Generate DWARF info for a procedure debug blockGenerate DWARF info for a blockGenerates the data for the debug frame section, which encodes the desired stack unwind behaviour for the debugger8Generates unwind information for a procedure debug blockNone#+Register's passed up the tree. If the stix code forces the register to live in a pre-decided machine register, it comes out as Fixed#; otherwise, it comes out as Any>, and the parent can decide which register to put it in.s are the insn sequences generated by the insn selectors. They are really trees of insns to facilitate fast appending, where a left-to-right traversal yields the insns in the correct order. UtilitiesSometimes we need to change the Format of a register. Primarily during conversion.Grab the Reg for a CmmRegConvert a BlockId to some CmmStatic data TODO: Add JumpTable Logic, see Ticket 19912 jumpTableEntry :: NCGConfig -> Maybe BlockId -> CmmStatic jumpTableEntry config Nothing = CmmStaticLit (CmmInt 0 (ncgWordWidth config)) jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel) where blockLabel = blockLbl blockidThe dual to getAnyReg: compute an expression into a register, but we don't mind which one it is.Move (wide immediate) Allows for 16bit immediate which can be shifted by 01632/48 bits. Used with MOVZ,MOVN, MOVK See Note [Aarch64 immediates]Arithmetic(immediate) Allows for 12bit immediates which can be shifted by 0 or 12 bits. Used with ADD, ADDS, SUB, SUBS, CMP See Note [Aarch64 immediates]Logical (immediate) Allows encoding of some repeated bitpatterns Used with AND, EOR, ORR and their aliases which includes at least MOV (bitmask immediate) See Note [Aarch64 immediates]Load/store immediate. Depends on the width of the store to some extent.The register width to be used for an operation on the given width operand.3Is a given number encodable as a bitmask immediate? https://stackoverflow.com/questions/30904718/range-of-immediate-values-in-armv8-a64-assemblyInstructions to sign-extend the value in the given register from width w up to width w'.Instructions to truncate the value in the given register from width w down to width w'.Cmm StatementsResulting instructions Cmm StatementResulting Instructionswidth of loaded valueNone- Instruction instance for aarch64 - -#None +3#  abstracted over n (the node type)?Function for rewriting and analysis combined. To be used with  rewriteCmm.Currently set to work with UniqDSM monad, but we could probably abstract that away (if we do that, we might want to specialize the fixpoint algorithms to the particular monads through SPECIALIZE). abstracted over n (the node type)*The result of joining OldFact and NewFact.!Result is different than OldFact.Result is the same as OldFact.Sort the blocks into the right order for analysis. This means reverse postorder for a forward analysis. For the backward one, we simply reverse that (see Note [Backward vs forward analysis]).Construct a mapping from a Label to the block indexes that should be re-analyzed if the facts at that Label change.Note that we're considering here the entry point of the block, so if the facts change at the entry: * for a backward analysis we need to re-analyze all the predecessors, but * for a forward analysis, we only need to re-analyze the current block (and that will in turn propagate facts into its successors).After some new facts have been generated by analysing a block, we fold this function over them to generate (a) a list of block indices to (re-)analyse, and (b) the new FactBase.Returns the result of joining the facts from all the successors of the provided node or block.(Returns the joined facts for each label.Folds backward over all nodes of an open-open block. Strict in the accumulator.Folds backward over all the nodes of an open-open block and allows rewriting them. The accumulator is both the block of nodes and f> (usually dataflow facts). Strict in both accumulated parts.̣̣None+hA load mentioned in a u.5Collect all of the memory locations loaded from by a u.$Generate TSAN instrumentation for a G occurrence.We save the contents of global registers in locals and allow the register allocator to spill them to the stack around the call. We cannot use the register table for this since we would interface with {SAVE,RESTORE}_THREAD_STATE.Mirrors __tsan_memory_order https://github.com/llvm/llvm-project/blob/main/compiler-rt/include/sanitizer/tsan_interface_atomic.h#L34the applied operationresults argumentsL* a block of instrumentation, if applicablefunctionresults arguments function nameformals argumentssuccess orderingfailure orderingaddressexpected value new valueresult destinationNone+<>Specialization that only retains the keys for local variables.Local variables are mostly glorified Ints, and some parts of the compiler really don't care about anything but the Int part. So we can avoid some overhead by computing a IntSet instead of a Set LocalReg which (unsurprisingly) is quite a bit faster.:A mapping from block labels to the variables live on entry&The variables live on entry to a blockThe dataflow lattice'Calculated liveness info for a CmmGraphOn entry to the procedure, there had better not be any LocalReg's live-in. If you see this error it most likely means you are trying to use a variable without it being defined in the given scope.The dataflow latticeOn entry to the procedure, there had better not be any LocalReg's live-in.None+conflicts (r,e) node is False if and only if the assignment r = e' can be safely commuted past statement node.None&+   None+2Check for obviously out-of-bounds shift operationsAs noted in Note [Register parameter passing], the arguments and ; of a foreign call mustn't mention caller-saved registers.    None+ The result of dominator analysis. Also includes a reverse postorder numbering, which is needed for dominator analysis and for other (downstream) analyses.Invariant: Dominators, graph, and RP numberings include only *reachable* blocks.+Reverse postorder number of a node in a CFGDominator setsNode X dominates node Y if and only if every path from the entry to Y includes X. Node Y technically dominates itself, but it is never included in the *representation* of its dominator set.A dominator set is represented as a linked list in which each node points to its *immediate* dominator, which is its parent in the dominator tree. In many circumstances the immediate dominator will be the only dominator of interest.0Set of nodes dominating the immediate dominator.!Label of the immediate dominator.Use to tell if the given label is in the given dominator set. Which is to say, does the bloc with with given label _properly_ and _non-vacuously_ dominate the node whose dominator set this is?Takes linear time in the height of the dominator tree, but uses space efficiently.Intersect two dominator sets to produce a third dominator set. This function takes time linear in the size of the sets. As such it is inefficient and should be used only for things like visualizations or linters.Call this function with a  to get back the results of a dominator analysis of that graph (as well as a reverse postorder numbering). The result also includes the subgraph of the original graph that contains only the reachable blocks.Utility functionsCall  to get the mapping from  to  that is embedded in every .Use  on the result of the dominator analysis to get a mapping from the  of each reachable block to the reverse postorder number of that block.Use  on the result of the dominator analysis to get a mapping from the  of each reachable block to the dominator set (and the immediate dominator) of that block. The implementation is space-efficient: intersecting dominator sets share the representation of their intersection.2Turn a function into an array. Inspired by SML's   ? ?!     = = Tell if a  is reducible, or make it soNone#+: A "supernode" contains a single-entry, multiple-exit, reducible subgraph. The entry point is the given label, and the block with that label dominates all the other blocks in the supernode. When an entire graph is collapsed into a single supernode, the graph is reducible. More detail can be found in GHC.Data.Graph.Collapse.1Represents the result of a reducibility analysis.Given a graph, say whether the graph is reducible. The graph must be bundled with a dominator analysis and a reverse postorder numbering, as these results are needed to perform the test.Given a graph, return an equivalent reducible graph, by "splitting" (copying) nodes if necessary. The input graph must be bundled with a dominator analysis and a reverse postorder numbering. The computation is monadic because when a node is split, the new copy needs a fresh label.Use this function whenever a downstream algorithm needs a reducible control-flow graph.Split one or more nodes of the given graph, which must be irreducible.9Turn a collapsed supernode back into a control-flow graph Convert a  into an inductive graph. (The function coalesces duplicate edges into a single edge.)-Return all labels defined within a supernode.Map the given function over every use and definition of a label in the given supernode.Map the given function over every use and definition of a label in the given block.Within the given supernode, replace every defined label (and all of its uses) with a fresh label.  ,      7 7 77None 3The syntactic constructs in which Wasm code may be contained. A list of these constructs represents an evaluation context, which is used to determined what level of br$ instruction reaches a given label.1Carries the label that follows `if...end`, if anyModule : GHC.Wasm.ControlFlow.FromCmm Description : Translation of (reducible) Cmm control flow to WebAssemblyCode in this module can translate any _reducible_ Cmm control-flow graph to the structured control flow that is required by WebAssembly. The algorithm is subtle and is described in detail in a draft paper to be found at  .https://www.cs.tufts.edu/~nr/pubs/relooper.pdf.Abstracts the kind of control flow we understand how to convert. A block can be left in one of four ways:Unconditionally%Conditionally on a predicate of type e=To a location determined by the value of a scrutinee of type e Not at all.;Convert a Cmm CFG to WebAssembly's structured control flow.A CmmSwitch scrutinee may have any width, but a br_table operand must be exactly word sized, hence the extension here. (#22871)needed for offset calculationtranslator for expressions!translator for straight-line codeCFG to be translated  % None #&'+3}=*Pop the results into locals after a ccall.Make a global definition for the string, and return its labelNone&'0lower bound (inclusive), upper bound (exclusive)addToMem rep ptr n adds n to the integer pointed-to by ptr.addToMemE rep ptr n adds n to the integer pointed-to by ptr.Emit a data-segment data blockEmit a read-only data blockEmit code to add an entry to a now-overwritten pointer to the update remembered set.A bare bones InfoProvEnt for things which don't have a good source location:Convert source information collected about identifiers in    to entries suitable for placing into the info table provenance table.The initial stats given to this function will (or should) only contain stats for stack info tables skipped during generateCgIPEStub. As the fold progresses, counts of tables per closure type will be accumulated.result registeraddressaddressvalueUse signed comparisons&value of pointer which was overwritten the thunk      NoneCheck all arguments marked as cbv for the presence of a tag *at runtime*.Check all required-tagged arguments of a constructor are tagged *at compile time*.Call barf if we failed to predict a tag correctly. This is immensely useful when debugging issues in tag inference as it will result in a program abort when we encounter an invalid call/heap object, rather than leaving it be and segfaulting arbitrary or producing invalid results. We check if either: * A tag is present * Or the object is a 25 (for which zero is the proper tag)Jump to the first block if the argument closure is subject to tagging requirements. Otherwise jump to the 2nd one.None:FVS, StgArg because for thunks these can also be literals.Args(Number of arguments for a ticky counter.Ticky currently treats args to constructor allocations differently than those for functions/LNE bindings.Register a ticky counter.It's important that this does not race with other entries of the same closure, lest the ticky_entry_ctrs list may become cyclic. However, we also need to make sure that this is reasonably efficient. Consequently, we first perform a normal load of the counter's "registered" flag to check whether registration is necessary. If so, then we do a compare-and-swap to lock the counter for registration and use an atomic-exchange to add the counter to the list. if ( f_ct.registeredp == 0 ) { if (cas(f_ct.registeredp, 0, 1) == 0) { old_head = xchg(ticky_entry_ctrs, f_ct); f_ct.link = old_head; } } Predicted a pointer would be tagged correctly (GHC will crash if not so no miss case)2Pass a boolean expr indicating if tag was present.Called when for `case v of ...` we can avoid entering v based on tag inference information.FVsArgsstatic updateable Free vars updateableFree vars + functionlbl for the counterarityfun descarg desc json descinfo table lbl!size of the full header, in bytessize of the payload, in bytes    !NoneUsed to tell the various mkVirtHeapOffsets functions what kind of header the object has. This will be accounted for in the offsets of the fields returned.$Return multiple values to the sequelIf the sequel is Return  return (x,y)If the sequel is AssignTo [p,q]  p=x; q=y;emitCall conv fun args# makes a call to the entry-code of fun$, using the call/return convention conv , passing args3, and returning the results to the current sequel.*emitCallWithExtraStack conv fun args stack$ makes a call to the entry-code of fun#, using the call/return convention conv , passing args0, pushing some extra stack frames described by stack2, and returning the results to the current sequel. takes a list of function arguments and prepares them for pushing on the stack for "extra" arguments to a function which requires fewer arguments than we currently have.1Just like mkVirtHeapOffsets, but for constructorsJust like mkVirtConstrOffsets, but used when we don't have the actual arguments. Useful when e.g. generating info tables; we just need to know sizes of pointer and non-pointer fields.$$None 3Tags every binder with its  and let bindings with their s.Tags binders of an  with its  and let bindings with their s. Additionally, returns its  and the set of binder occurrences in argument and nullary application position (cf. GHC.Stg.Lift.Analysis#arg_occs).How many times will the lambda body of the RHS bound to the given identifier be evaluated, relative to its defining context? This function computes the answer in form of a ].Combines several heuristics to decide whether to lambda-lift a given let-binding to top-level. See GHC.Stg.Lift.Analysis#when for details.?The size in words of a function closure closing over the given s, including the header.The number of words a single  adds to a closure's size. Note that this can't handle unboxed tuples (which may still be present in let-no-escapes, even after Unarise), in which case   will crash."closureGrowth expander sizer f fvs> computes the closure growth in words as a result of lifting f to top-level. If there was any growing closure under a multi-shot lambda, the result will be ' . Also see GHC.Stg.Lift.Analysis#clogro.Is the binding a let-no-escape?Let body Binding group9RHS skeletons, argument occurrences and annotated bindingIs the binding a let-no-escape?Let body skeleton Argument occurrences in the body Binding groupLet skeleton, argument occurrences, scope skeleton of binding and the annotated bindingAn expander function, turning -s into -s. See  . Just abs_ids  =) This binding is beneficial to lift and abs_ids* are the variables it would abstract over:Expands outer free ids that were lifted to their free vars/Computes the closure footprint of an identifier0Binding group for which lifting is to be decidedFree vars of the whole binding group prior to lifting it. These must be available at call sites if we decide to lift the binding group.(Abstraction of the scope of the functionClosure growth. '; indicates there was growth under a (multi-shot) lambda.Noneh=Lambda lifts bindings to top-level deemed worth lifting (see ).(Mostly) textbook instance of the lambda lifting transformation, selecting which bindings to lambda lift by consulting .Just former_fvs  =( this RHS was lifted and we have to add  former_fvs. as lambda binders, discarding all free vars.ʨ˨̨ͨΨϨʨ˨̨ͨΨϨNone&'v6All the information about the breakpoints for a modulev6info about each breakpoint from the bytecode generatorv1Array pointing to cost centre for each breakpointvAn array giving the names of the declarations enclosing each breakpoint. See Note [Field modBreaks_decls]vAn array giving the names of the free variables at each breakpoint.v3An array giving the source span of each breakpoint.vThe array of flags, one per breakpoint, indicating which breakpoints are enabled.vC CostCentre typevBreakpoint indexvInformation about a breakpoint that we know at code-generation time In order to be used, this needs to be hydrated relative to the current HscEnv by hydrateCgBreakInfo. Everything here can be fully forced and that's critical for preventing space leaks (see #22530)v)Type variables in scope at the breakpointvA reference to a top-level string literal; see Note [Generating code for top-level string literal bindings] in GHC.StgToByteCode.vOnly used internally in the assembler in an intermediate representation; should never appear in a fully-assembled UnlinkedBCO. Also see Note [Allocating string literals] in GHC.ByteCode.Asm.va pointer to a breakpoint's module's BreakArray in GHCi's memoryvStatic pointer table entries which should be loaded along with the BCOs. See Note [Grand plan for static forms] in GHC.Iface.Tidy.StaticPtrTable.v5breakpoint info (Nothing if breakpoints are disabled)v"top-level strings (heap allocated)vffi blocks we allocatedv*Mapping from DataCons to their info tablesvBunch of interpretable bindingsvConstruct an empty ModBreaksvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv/v  #v  v   v  v  v   v %v  v  v v  v v v v 'v ),v .1v 37v 9=v ?v v v v w 'w ),w .1w 37w 9w w w w 'w ),w .1w 37w 9w w w w 'w ),w .1w 37w 9w w NoneY&3Objects which have yet to be linked by the compilerStatic archive file (.a)3Dynamically linked library file (.so, .dll, .dylib)Serialised core which we can turn into BCOs (or object files), or used by some other backend See Note [Interface Files with Core Definitions])A byte-code object, lives only in memory.Classify the provenance of .o products.The object is the final product for a module. When linking splices, its file extension will be adapted to the interpreter's way if needed.The object was created from generated code for foreign stubs or foreign sources added by the user. Its file extension must be preserved, since there are no objects for alternative ways available.Information we can use to dynamically link modules into the compiler!Files and chunks of code to link.The linkable module itselfTime at which this linkable was built (i.e. when the bytecodes were produced, or the mod date on the files)5See Note [Looking up symbols in the relevant objects]Like  and , but for top-level 'Addr#' literals, see Note [Generating code for top-level string literal bindings] in GHC.StgToByteCode.The current global mapping from RdrNames of DataCons to info table addresses. When a new LinkablePart is linked into the running image, or an existing module in the image is replaced, the itbl_env must be updated appropriately.>Current global mapping from closure Names to their true valuesWe need to remember the name of previous temporary DLL/.so libraries so we can link them (see #10322)The currently-loaded packages; always object code haskell libraries, system libraries, transitive dependencies8And the currently-loaded compiled modules (home package)7The currently loaded interpreted modules (home package)6Current global mapping from Names to their true valuesUnion of LinkableSets.In case of conflict, keep the most recent Linkable (as per linkableTime)Return true if the linkable only consists of native code (no BCO)"List the BCOs parts of a linkable.5This excludes the LazyBCOs and the CoreBindings parts"List the native linkable parts (.o.so.dll) of a linkable9Split linkable parts into (native code parts, BCOs parts)*List the native objects (.o) of a linkable2List the native libraries (.so/.dll) of a linkable6List the paths of the native objects and libraries (.o.so.dll)+Is the part a native object or library? (.o.so.dll)(Is the part a native library? (.so/.dll)1Get the FilePath of linkable part (if applicable)Return the paths of all object code files (.o, .a, .so) contained in this .Dependent packages, used to generate #includes for C code genForeign export stubsThe tidied main bindings, including previously-implicit bindings for record and class selectors, and data constructor wrappers. But *not* data constructor workers; reason: we regard them as part of the code-gen of tyconsAlgebraic data types (including ones that started life as classes); generate constructors and info tables. Includes newtypes, just for the benefit of External CoreModule being compiledA ModGuts is carried through the compiler, accumulating stuff as it goes There is only one ModGuts at any time, the one for the module being compiled right now. Once it is compiled, a ModIface and  ModDetails, are extracted and the ModGuts is discarded.Documentation.Do we need to trust our own package for Safe Haskell? See Note [Trust Own Package] in GHC.Rename.NamesSafe Haskell mode&Type-family instance environment for  home-package% modules (including this one); c.f. tcg_fam_inst_env Class instance environment for  home-package% modules (including this one); c.f.  tcg_inst_envBreakpoints for the module!Coverage tick boxes in the moduleComplete Matches#Annotations declared in this moduleWarnings declared in the module(Files to be compiled with the C compiler'Foreign exports declared in this moduleBindings for this moduleBefore the core pipeline starts, contains See Note [Overall plumbing for rules] in GHC.Core.Rules(Pattern synonyms declared in this module(Family instances declared in this module'Class instances declared in this module(Class defaults exported from this module=TyCons declared in this module (includes TyCons for classes)Fixities declared in this module. Used for creating interface files.Top-level lexical environmentDid we run a TH splice?$What was used? Used for interfaces.*What it depends on, directly or otherwiseWhat it exports$For error messages from inner passesWhether it's an hs-boot moduleModule being compiled++None?A full rule environment which we can apply rules from. Like a , but it also includes the set of visible orphans we use to filter out orphan rules which are not visible (even though we can see them...) See Note [Orphans] in GHC.CoreGathers a collection of _s. Maps (the name of) an  to its rules Used to make _ for an 1 defined in the module being compiled. See also A Find the "top" free names of several expressions. Such names are either: The function finally being applied to in an application chain (if that name is a GlobalId: see GHC.Types.Var#globalvslocal), orThe TyCon if the expression is a This is used for the fast-match-check for rules; if the top names don't match, the rest can'truleCantMatch tpl actual returns True only if actual definitely can't match tpl by instantiating tpl. It's only a one-way match; unlike instance matching we don't consider unification.Notice that [_$_] )ruleCantMatch [Nothing] [Just n2] = False Reason: a template variable can be instantiated by a constant Also: )ruleCantMatch [Just n1] [Nothing] = False Reason: a local variable v in the actuals might [_$_]Gather all the rules for locally bound identifiers from the supplied bindingsThe main rule matching function. Attempts to apply all (active) supplied rules to this instance of an application in a given context, returning the rule applied and the resulting expression if successful.Report partial matches for rules beginning with the specified string for the purposes of error reporting0Target; can have more elements than the template Rule optionsRule activation test Rule patternRules for an IdBindings to check inResulting check messageNone.The action to retrieve an up-to-date EPS RuleEnv See Note [Overall plumbing for rules]!Max #ticks in this simplifier runMake a join id with given type and arity but without call-by-value annotations.Size of the bindings, used to limit the number of ticks we allow            None A substitution result.Coercion optimiser optionsWhether to enable floating outWhether pre-inlining is enabledWhether case-of-case is enabledUnfolding options!Do we swizzle casts past lambdas? Whether eta-expansion is enabledWhether inlining is enabledWhether RULES are enabledName(s) of the phaseFast OutVarSet tracking which recursive RHSs we are analysing. See Note [Eta reduction in recursive RHSs] in GHC.Core.Opt.Arity.           NoneSReport the inlining of an identifier's RHS to the user, if requested. qqqqqqq qqqqqqqNone}Each of these Ids was scrutinised by an enclosing case expression, at a level deeper than its binding level.The first LibCaseLevel is the *binding level* of the scrutinised Id, The second is the level *at which it was scrutinised*. (see Note [Avoiding fruitless liberate-case]) The former is a bit redundant, since you could always look it up in lc_lvl_env, but it's just cached here-The order is insignificant; it's a bag reallyThere's one element per scrutinisation; in principle the same Id may appear multiple times, although that'd be unusual: case x of { (a,b) -> ....(case x of ...) .. }Binds *only* recursively defined ids, to their own binding group, and *only* in their own RHSsBinds all non-top-level in-scope Ids (top-level and imported things have a level of zero)Current level The level is incremented when (and only when) going inside the RHS of a (sufficiently small) recursive function.liberate case options#Options for the liberate case pass.Unfolding options?Bomb-out size for deciding if potential liberatees are too big.NoneUInitialize configuration for the liberate case Core optimization pass.None;Helps us find information about modules in the home package7Information about modules in the package being compiledThe actual artifact we would like to link to access things in this module. See Note [Home module build products] might be empty: If this is an .hs-boot moduleTemporarily during compilation if we pruned away the old linkable because it was out of date.When re-linking a module ( ), we construct the  by building a new  from the old ʑ (only).1Extra information that has been created from the ʑ/ for the module, typically during typecheckingThe basic loaded interface file: every loaded module has one of these, even if it is imported from another package$Constructs an empty HomePackageTableLike concatMap f . , but filters out all  for which f: returns the empty list before doing the sort inherent to .!! $None (Action to perform in backend compilation+Update the boot and signature file results.Recompile this module.Old interface hash for this compilation, if an old interface file exists. Pass to hscMaybeWriteIface when writing the interface to avoid updating the existing interface when the interface isn't changed.Partial interface Module info#Information for the code generator.-Status of a module in incremental compilation*Nothing to do because code already exists.Recompilation of module, or update of interface is required. Optionally pass the old interface hash to avoid updating the existing interface when it has not changed.   - -%None#None#)/Code generator for JavaScript?Generate the ingredients for the linkable units for this module+variable prefix for the nth block in moduleOutput file namethe linkable unitsNoneNone) StaticPtr datacon StaticPtrInfo dataconIds for `unpackCString[Utf8]#`Generate CStub or notTarget platform!Replaces all bindings of the form 'b = /\ ... -> makeStatic location valuewith b = /\ ... -> StaticPtr key (StaticPtrInfo "pkg key" "module" location) value3where a distinct key is generated for each binding.It also yields the C stub that inserts these bindings into the static pointer table.sptModuleInitCode module fps. is a C stub to insert the static entries of module into the static pointer table.fps is a list associating each binding corresponding to a static entry with its fingerprint.  None%ˍMƍȍčMǍMʍMÍōMMMɍ%MMMMMMMÍčōƍǍȍɍʍˍNoneNonePretty-prints a  in context: that is, if the entity is a data constructor, record selector, or class method, then the entity's parent declaration is pretty-printed with irrelevant parts omitted.Pretty-prints a .Pretty-prints a p8 (type/data family instance) with its defining location.Pretty-prints a  with its defining location.Pretty-prints the  header. For functions and data constructors the function is equivalent to  but for type constructors and classes it prints only the header part of the declaration.Like !, but adds the defining location.None  #&')3 ; Change [x] to "x", [x, y] to "x and y", [x, y, z] to "x, y, and z", and so on. The  stands for any  conjunction, which is passed in.What warning flags are associated with the given missing signature?Pretty-print a ؕ, containing a  with its enclosing ̕.Pretty-print a , with its enclosing ̕.&Whether to print explicit kinds (with -fprint-explicit-kinds ) in an  when a type mismatch occurs to due invisible parts of the types. See Note [Showing invisible bits of types in error messages])This function first checks to see if the  argument is a . If so, it first checks whether the equality is a visible equality; if it's not, definitely print the kinds. Even if the equality is a visible equality, check the expected/actual types to see if the types have equal visible components. If the  is not a 6, fall back on the actual mismatched types themselves.Directly display the given matching and unifying instances, with a header for each: `Matching instances Potentially matching instances`.Display a summary of available instances, omitting those involving out-of-scope types, in order to explain why we couldn't solve a particular constraint, e.g. due to instance overlap or out-of-scope types.To directly display a collection of matching/unifying instances, use .Display a summary of available instances, omitting out-of-scope ones.Use 3 to automatically set the pretty-printing options.Compute a message informing the user of any instances that are overlapped but were not discarded because the instance overlapping them wasn't strictly more specific.6Pretty-print an informational message, to accompany a .Expand type synonyms in given types only enough to make them as similar as possible. Returned types are the same in terms of used type synonyms.To expand all synonyms, see  .See ExpandSynsFail tests in tests testsuiteteststypecheck/should_fail for some examples of how this should work.:the type which doesn't have a fixed runtime representationIf False, only prints the why.Whether to print all potential instancesherald ' '   (     2None1'Write into a currently-empty MetaTyVar.(Works with both type and kind variables.Write into the - mutable references of a f.6zonkId is used *during* typechecking just to zonk the Id's typeCheck that a coercion is appropriate for filling a hole. (The hole itself is needed only for printing.) Always returns the checked coercion, but this return value is necessary so that the input coercion is forced only when the output is forced.Get a / that includes mappings for all vars free in the given type. Useful when tidying open types.the type varfiable to write to,the type to write into the mutable referencefor debug assertions only;#ref cell must be for the same tyvar*the type to write to the mutable reference3&None +3JSuggests a list of z" for the '.hsig' file to the user. " 4 7 7 1 11NoneA source error is an error that is caused by one or more errors in the source code. A  is thrown by many functions in the compilation pipeline. Inside GHC these errors are merely printed via  log_action, but API clients may treat them differently, for example, insert them into a list box. If you want the default behaviour, use the idiom: handleSourceError printExceptionAndWarnings $ do ... api calls that may fail ...The %s error messages can be accessed via 8. This list may be empty if the compiler failed due to -Werror (Opt_WarnIsError).See printExceptionAndWarnings for more information on what to take care of when writing a custom error handler.Perform the given action and call the exception handler if the action throws a . See  for more information.exception handleraction to perform  7 7None #Parse the imports of a source file. Throws a  if parsing fails.6Parse OPTIONS and LANGUAGE pragmas of the source file. Throws a 5 if flag parsing fails (including unsupported flags.)6Parse OPTIONS and LANGUAGE pragmas of the source file. Throws a 5 if flag parsing fails (including unsupported flags.)4Complain about non-dynamic flags in OPTIONS pragmas. Throws a  if the input list is non-empty claiming that the input flags are unknown.Parser optionsImplicit Prelude? Parse this.Filename the buffer came from. Used for reporting parse error locations.The original source filename (used for locations in the function result)The source imports and normal imports (with optional package names from -XPackageImports), and the module name. Input fileParsed options, if any. Input Buffer)Source filename. Used for location info.warnings and parsed options.NonedGiven a bag of diagnostics, turn them into an exception if any has , or print them out otherwise. Convert a PsError into a wrapped ; use it for dealing with parse errors when the driver is doing dependency analysis. Defined here to avoid module loops between GHC.Driver.Error.Types and GHC.Driver.Error.PprNoneInitialise the general configuration for printing diagnostic messages For example, this configuration controls things like whether warnings are treated like errors.Initialise the configuration for printing specific diagnostic messagesNone 6A command-line warning message and the reason it arose,This used to be own type, but now it's just  .A command-line error message4GHC flag modes describing when a flag has an effect.-The flag only affects the non-interactive GHC)The flag only affects the interactive GHC#The flag affects multiple ghc modes.This flag should not be seen in cli completion Parse an IntLooks for "433" or "=342", with no trailing gubbins * n or =n => Just n * gibberish => NothingDiscards a leading equals sign%Parse a response file into arguments.cmdline parser specargsresponse file handler++  &  "  ( NoneG:A local block label (e.g. identifying a case alternative). 9 9    1 7 7 77None+3Build a PrimOp IdAnalyse the type of a primop to determine which of its outermost forall'd type variables must be instantiated to concrete types when the primop is instantiated.These are the Levity and RuntimeRep kinded type-variables which appear in negative position in the type of the primop.Does this type variable appear in a kind in a negative position in the type?&Returns the first such position if so.NB: assumes the type is of a simple form, e.g. no foralls, no function arrows nested in a TyCon other than a function arrow. Just used to compute the set of ConcreteTyVars for a PrimOp by inspecting its type, see .Does this type variable appear in a kind in a positive position in the type?&Returns the first such position if so.NB: assumes the type is of a simple form, e.g. no foralls, no function arrows nested in a TyCon other than a function arrow. Just used to compute the set of ConcreteTyVars for a PrimOp by inspecting its type, see . z  y and x * 1 + z ==> z  x.ʐCheck if there is comparison with minBound or maxBound, that is always true or false. For instance, an Int cannot be smaller than its minBound, so we can replace such comparison with False.ːCreate an Int literal expression while ensuring the given Integer is in the target Int range̐Create an Int literal expression while ensuring the given Integer is in the target Int range͐Create an Int literal expression while ensuring the given Integer is in the target Int rangeΐCreate an unboxed pair of an Int literal expression, ensuring the given Integer is in the target Int range and the corresponding overflow flag (0#/1#) if it wasn't.ϐCreate a Word literal expression while ensuring the given Integer is in the target Word rangeАCreate a Word literal expression while ensuring the given Integer is in the target Word rangeѐCreate a Word literal expression while ensuring the given Integer is in the target Word rangeҐCreate a Word literal expression while ensuring the given Integer is in the target Word rangeӐCreate an unboxed pair of a Word literal expression, ensuring the given Integer is in the target Word range and the corresponding carry flag (0#/1#) if it wasn't.Ԑ'ambient (primop x) = x', but not necessarily 'primop (ambient x) = x'.Ր=Transform `extendWordN (narrowWordN x)` into `x .&. 0xFF..FF`֐narrow subsumes bitwise  with full mask (cf #16402):narrowN (x .&. m) m .&. (2^N-1) = 2^N-1 ==> narrowN x3e.g. narrow16 (x .&. 0xFFFF) ==> narrow16 xאMatch (op (op v e) e) or (op e (op v e)) or (op (op e v) e) or (op e (op e v)) and return the innermost (op v e) or (op e v).ؐ+Match BigNat#, Integer and Natural literalsِMatch numeric literalsڐ8Match the application of a DataCon to a numeric literal.Can be used to match e.g.: IS 123# IP bigNatLiteral W# 123##ې$Left identity rule for PrimOps like IntAddC and WordAddC, where, in addition to the result, we have to indicate that no carry/overflow occurred.ܐ%Right identity rule for PrimOps like IntSubC and WordSubC, where, in addition to the result, we have to indicate that no carry/overflow occurred.ݐIdentity rule for PrimOps like IntAddC and WordAddC, where, in addition to the result, we have to indicate that no carry/overflow occurred.ސCreate a numeric literalߐ*Create a numeric literal if it is in rangeMatch the scrutinee of a case and potentially return a new scrutinee and a function to apply to each literal alternative. Case rulesIt's important that occurrence info are present, hence the use of In* types.If the given primop is a quotRem, return the corresponding (quot,rem).Scutinee Case-binder+Alternatives in standard (increasing) order      None :Accumulated statistics about what we are putting into the !. "In" means stuff that is just read from interface files, "Out" means actually sucked in and type-checkedInformation about other packages that we have slurped in by reading their interface files7Statistics about what was loaded from external packagesThe family instances accumulated from external packages, keyed off the module that declared them The total 3 accumulated from all the external-package modules The total D3 accumulated from all the external-package modules The total RuleEnv3 accumulated from all the external-package modules The total p3 accumulated from all the external-package modules The total w3 accumulated from all the external-package modules!If an interface was written with -fwrite-if-simplified-core, this will contain an IO action that compiles bytecode from core bindings.0See Note [Interface Files with Core Definitions]Result of typechecking all the external package interface files we have sucked in. The domain of the mapping is external-package modules Cache for #. Ordinarily, we can rely on the  for this information, EXCEPT that when we do dependency analysis, we need to look at the  Dependencies of our imports to determine what their precise free holes are (moduleFreeHolesPrecise). We don't want to repeatedly reread in the interface for every import, so cache it here. When the PIT gets filled in we can drop these entries.The ʑs for modules in external packages whose interfaces we have opened. The declarations in these interface files are held in the  eps_decls, ,  and  eps_rules$ fields of this record, not in the ב, fields of the interface we have sucked in.What is in the PIT is: The ModuleFingerprint info Its exportsFixitiesDeprecations and warningsIn OneShot mode (only), home-package modules accumulate in the external package state, and are sucked in lazily. For these home-pkg modules (only) we need to record which are boot modules. We set this field after loading all the explicitly-imported interfaces, but before doing anything elseThe  part is not necessary, but it's useful for debug prints, and it's convenient because this field comes direct from  Information about the currently loaded external packages. This is mutable because packages will be demand-loaded during a compilation run as required.Helps us find information about modules in the imported packages%Constructs an empty PackageIfaceTable&Add stats for one newly-read interface%%None  Home-unitThe home package table describes already-compiled home-package modules,  excluding the module we are compiling right now. (In one-shot mode the current module is the only home-package module, so homeUnitEnv_hpt is empty. All other modules count as "external-package" modules. However, even in GHCi mode, hi-boot interfaces are demand-loaded into the external-package table.) is not mutable because we only demand-load external packages; the home package is eagerly loaded, module by module, by the compilation manager.0The HPT may contain modules compiled earlier by --make but not actually below the current module in the dependency graph.4(This changes a previous invariant: changed Jan 05.)The dynamic flag settings0Stack of unit databases for the target platform.+This field is populated with the result of .K4 means the databases have never been read from disk.Usually we don't reload the databases from disk if they are cached, even if the database flags changed!External units2GHC name/version (used for dynamic library suffix)PlatformInformation about the currently loaded external packages. This is mutable because packages will be demand-loaded during a compilation run as required. Get home-unit+Unsafe because the home-unit may not be setLookup J for every preload unit from the UnitState, for every unit used to instantiate the home unit, and for every unit explicitly passed in the given list of UnitId.Lookup J for every preload unit from the UnitState and for every unit used to instantiate the home unit.+Test if the module comes from the home unit*Rename a unit id in the internal unit env. oldUnit newUnit UnitEnv, it is assumed that the oldUnit. exists in the map, otherwise we panic. The ʄ3 associated with the home unit will have its field $ set to newUnit.     /    "-None1Locations and information the finder cares about.Should be taken from DynFlags via initFinderOpts.If we encounter unknown modules, should we suggest modules that have a similar name.Don't check that an imported interface file actually exists if it can only be at one location. The interface will be reported as  even if the file doesn't exist, so this is only useful in specific cases (e.g. to generate dependencies with `ghc -M`)When looking up a home module:M-: search interface files (e.g. in '-c' mode)J-: search source files (e.g. in '--make' mode)9Where are we allowed to look for Modules and Source files/The result of searching for an imported module.NB: FindResult manages both user source-import lookups (which can result in ) as well as direct imports for interfaces (which always result in ").The module was found The requested unit was not found"_Error_: both in multiple packages Not foundPossible mis-spelled modules,Module is in these units, but it is unusable5Module is in these units, but the *unit* is hidden7Module is in these units, but the *module* is hiddenJust p => module is in this unit's manifest, but couldn't find the .hi filePlaces where I lookedLook for the hash of a file in the cache. This should add it to the cache. If the file doesn't exist, raise an IOException.!Look for a location in the cache.1Add a found location to the cache for the module.remove all the home modules from the cache; package modules are assumed to not move around during a session; also flush the file hash cache.The  maps modules to the result of searching for that module. It records the results of searching for modules along the search path. On :load., we flush the entire contents of this cache.++None2 Create a new  from DynFlags.NoneCreates some functions that work out the best ways to format names for the user according to a set of heuristics.Creates a function for formatting modules based on two heuristics: (1) if the module is the current module, don't qualify, and (2) if there is only one exposed package which exports this module, don't qualify.Creates a function for formatting packages based on two heuristics: (1) don't qualify if the package in question is "main", and (2) only qualify with a unit id if the package ID would be ambiguous.A function which only qualifies package names if necessary; but qualifies all other identifiers.NoneX)Shared lib filename common suffix sans .so, e.g. p-ghc9.13.20241001Are we profiling yet?+Additional command line arguments for iserv/wasi-sdk sysroot libdir containing libc.so, etcLocation of dyld.mjs scriptPath to "ghc-interp.js" scriptNodeJS settingsNodeJs configurationkeep node.js (TH, GHCJSi) processes alive if they don't use more than this"extra arguments to pass to node.jsvalue of NODE_PATH environment variable (search path for Node modules; GHCJS used to provide some)location of node.js programIs the Haskell server started?Linker state of the interpreter GHCi unit-id Mutable stateStdin for the process?Common field between native external interpreter and the JS oneInstance specific extra fieldsValues that need to be freed before the next command is sent. Finalizers for ForeignRefs can append values to this list asynchronously.External interpreter process and its pipe (communication channel)5Configuration needed to spawn an external interpreter!Trace action executed after spawnHookUse Dynamic wayUse Profiling wayCommand-line optionsExternal program to run!Status of an external interpreterNot spawned yetRunning/Lock to prevent concurrent access to the streamProcess handle of the server#Pipe to communicate with the serverExternal interpreterThe external interpreter is spawned lazily (on first use) to avoid slowing down sessions that don't require it. The contents of the MVar reflects the state of the interpreter (running or not).External interpreterInternal interpreter InterpreterLookupSymbol cacheInterpreter loader)Interpreter instance (internal, external)None&'None Send a message to the interpreter process that doesn't expect a response (locks the interpreter while sending)Send a message to the interpreter that expects a response (locks the interpreter while until the response is received)Send a message to the interpreter process whose response is expected laterThis is useful to avoid forgetting to receive the value and to ensure that the type of the response isn't lost. Use receiveDelayedResponse to read it. (locks the interpreter until the response is received using )*Expect a delayed result to be received now,Send any value (requires locked interpreter);Expect a value to be received (requires locked interpreter)Wait for a Template Haskell message (requires locked interpreter)Send a 6 and receive the response from the interpreter process)Read a value from the interpreter process'Send a value to the interpreter process33None Bring the exports of a particular module (filtered by an import decl) into scopeBring into scope the entire top-level envt of of this module, including the things imported into it.Interactive context, recording information about the state of the context in which statements are executed in a GHCi session.Cache of loaded plugins. We store them here to avoid having to load them every time we switch to the interactive context.virtual CWD of the programThe function that is used for printing results of expressions in ghci and -e mode.#The monad that GHCi is executing in The stack of breakpoint contexts.The current default classes and types, set by  'default' declarations#Fixities declared in let statementsAll instances and family instances created during this session. These are grabbed en masse after each update to be sure that proper overlapping is retained. That is, rather than re-check the overlapping each time we update the context, we just take the results from the instance code that already does that.Essentially the cached 4.The GlobalRdrEnv contains everything in scope at the command line, both imported and everything in ic_tythings, with the correct shadowing.The IcGlobalRdrEnv contains extra data to allow efficient recalculation when the set of imports change. See Note [icReaderEnv recalculation]TyThings defined by the user, in reverse order of definition (ie most recent at the front). Also used in GHC.Tc.Module.runTcInteractive to fill the type checker environment. See Note [ic_tythings]The GHCi top-level scope (icReaderEnv) is extended with these importsThis field is only stored here so that the client can retrieve it with GHC.getContext. GHC itself doesn't use it, but does reset it to empty sometimes (such as before a GHC.load). The context is set with GHC.setContext.Each GHCi stmt or declaration brings some new things into scope. We give them names like interactive:Ghci9.T, where the ic_index is the '9'. The ic_mod_index is incremented whenever we add something to ic_tythings See Note [The interactive package]The ʄ: used to evaluate interactive expressions and statements.'Constructs an empty InteractiveContext.This function returns the list of visible TyThings (useful for e.g. showBindings).It picks only those TyThings that are not shadowed by later definitions on the interpreter, to not clutter :showBindings with shadowed ids, which would show up as Ghci9.foo.Some TyThings define many names; we include them if _any_ name is still available unqualified.Get the NamePprCtx function based on the flags and this InteractiveContextextendInteractiveContext is called with new TyThings recently defined to update the InteractiveContext to include them. By putting new things first, unqualified use will pick the most recently defined thing with a given name, while still keeping the old names in scope in their qualified form (Ghci1.foo).Add TyThings to the 4, earlier ones in the list shadowing later ones, and shadowing existing entries in the 4.0discard names that are only available qualified?  &NoneNone~!Linker flags collected from unitsExtra linker options,External libraries (as a list of "-lfoo...")-Haskell libraries (as a list of "-lHSfoo...")Find all the link options in these and the preload packages, returning (package hs lib options, extra library options, other flags) Either the  or  as appropriate for the way.   " "NoneHscEnv is like  , except that some of the fields are immutable. An HscEnv is used to compile a single module from plain Haskell source code (after preprocessing) to either C, assembly or C--. It's also used to store the dynamic linker state to allow for multiple linkers in the same address space. Things like the module graph don't change during a single compilation.Historical note: "hsc" used to be the name of the compiler binary, when there was a separate driver and compiler. To compile a single module, the driver would invoke hsc on the source code... so nowadays we think of hsc as the layer of the compiler that deals with compiling a single module.LLVM configuration cache.Temporary filesHooksLogger with its flags.Don't forget to update the logger flags if the logging related DynFlags change. Or better, use hscSetFlags setter which does it./Unit environment (unit state, home unit, etc.).)Initialized from the databases cached in  hsc_unit_dbs and from the DynFlags.Pluginstarget code interpreter (if any) to use for TH and GHCi. See Note [Target code interpreter]7Used for one-shot compilation only, to initialise the IfGblEnv. See   for   (. See also Note [hsc_type_env_var hack]:The cached result of performing finding in the file systemGlobal Name cache so that each Name gets a single Unique. Also track the origin of the Names.1The context for evaluating interactive statements'The module graph of the current session-The targets (or roots) of the current sessionThe dynamic flag settings:The Hsc monad: Passing an environment and diagnostic state ) )! , , & & ## ### #%#* #,#3None7Switches in the DynFlags and Plugins from the InteractiveContextA variant of runHsc that switches in the DynFlags and Plugins from the InteractiveContext before running the Hsc computation.(Retrieve the ExternalPackageState cache.Find all the instance declarations (of classes and families) from the Home Package Table filtered by the provided predicate function. Used in  tcRnImports, to select the instances that are in the transitive closure of imports from the currently compiled module.4Find instances visible from the given set of importsGet rules from modules "below" this one (in the dependency sense)Get annotations from modules "below" this one (in the dependency sense)Get things from modules "below" this one (in the dependency sense) C.f Inst.hptInstancesDeal with gathering annotations in from all possible places and combining them into a single D Find the  for the given  by using all the resources at our disposal: the compiled modules in the : and the compiled modules in other packages that live in '. Note that this does NOT look up the  in the module being compiled: you have to do that yourself, if desired Find the ʑ for a , searching in both the loaded home and external package module information$Retrieve the target code interpreter0Fails if no target code interpreter is availableUpdate the LogFlags of the Log in hsc_logger from the DynFlags in hsc_dflags. You need to call this when DynFlags are modified. Update Flags Set FlagsDiscard the contents of the InteractiveContext, but keep the DynFlags and the loaded plugins. It will also keep ic_int_print and ic_monad if their names are from external packages.44None&'Locate a module that was imported by the user. We have the module's name, and possibly a package name. Without a package name, this function will use the search path and the known exposed packages to find the module, if a package is specified then only that package is searched for the module.Locate a plugin module requested by the user, for a compiler plugin. This consults the same set of exposed packages as  , unless -hide-all-plugin-packages or -plugin-package are specified.Locate a specific 0. The purpose of this function is to create a # for a given , that is to find out where the files associated with this module live. It is used when reading the interface for a module mentioned by another interface, for example (a "system import").Given a monadic actions this and or_this, first execute this. If the returned / is successful, return it; otherwise, execute or_this. If both failed, this function also combines their failure messages in a reasonable way.Helper function for 8: this function wraps an IO action which would look up mod_name in the file system (the home package), and first consults the  cache to see if the lookup has already been done. Otherwise, do the lookup (with the IO action) and save the result in the finder cache and the module location cache (if it was successful.)Implements the search for a module name in the home package only. Calling this function directly is usually *not* what you want; currently, it's used as a building block for the following operations: When you do a normal package lookup, we first check if the module is available in the home module, before looking it up in the package database.When you have a package qualified import with package name "this", we shortcut to the home module.When we look up an exact , if the unit id associated with the module is the current home module do a look up in the home module.Some special-case code in GHCi (ToDo: Figure out why that needs to call this.)1Prepend the working directory to the search path..Search for a module in external packages only.2Look up the interface file associated with module mod. This function requires a few invariants to be upheld: (1) the  in question must be the module identifier of the *original* implementation of a module, not a reexport (this invariant is upheld by GHC.Unit.State) and (2) the J, must be consistent with the unit id in the . The redundancy is to avoid an extra lookup in the package state for the appropriate config.Constructs the filename of a .o file for a given source file. Does not! check whether the .o file existsConstructs the filename of a .dyn_o file for a given source file. Does not% check whether the .dyn_o file existsConstructs the filename of a .hi file for a given source file. Does not" check whether the .hi file existsConstructs the filename of a .dyn_hi file for a given source file. Does not& check whether the .dyn_hi file existsConstructs the filename of a .hie file for a given source file. Does not# check whether the .hie file existsCompute the file name of a header file for foreign stubs, using either the directory explicitly specified in the command line option -stubdir0, or the directory of the module's source file.6When compiling bytecode from interface Core bindings,  ModLocation does not contain a source file path, so the header isn't written. This doesn't have an impact, since we cannot support headers importing Haskell symbols defined in bytecode for TH whatsoever at the moment.99NoneNone2-A function called to log warnings and errors.A monad transformer to add GHC specific features to another monad.Note that the wrapped monad must support IO and handling of exceptions.The Session is a handle to the complete state of a compilation session. A compilation session consists of a set of modules constituting the current program or library, the context for interactive evaluation, and various caches.A minimal implementation of a . If you need a custom monad, e.g., to maintain additional state consider wrapping this monad or using .:A monad that has all the features needed by GHC API calls.In short, a GHC monadallows embedding of IO actions,can log warnings,/allows handling of (extensible) exceptions, andmaintains a current session.If you do not use  or , make sure to call  5 before any call to the GHC API functions can occur.+Call the argument with the current session.#Grabs the DynFlags from the SessionSet the current session to the result of applying the current session to the argument.Set the current session to the result of applying the current session to the argument.3Call an action with a temporarily modified Session.Modify the loggerPush a log hook on the stackPop a log hook from the stackPut a log messagePut a log messageTime an action+A monad that allows logging of diagnostics.Reflect a computation in the  monad into the D monad.>You can use this to call functions returning an action in the  monad inside an D action. This is needed for some (too restrictive) callback arguments of some library functions: libFunc :: String -> (Int -> IO a) -> IO a ghcFunc :: Int -> Ghc a ghcFuncUsingLibFunc :: String -> Ghc a -> Ghc a ghcFuncUsingLibFunc str = reifyGhc $ \s -> libFunc $ \i -> do reflectGhc (ghcFunc i) sPrint the all diagnostics in a '. Useful inside exception handlers.          /  )  +     !* ,4 6        !* ,4 6   NoneThe monad used by Core-to-Core passes to register simplification statistics. Also used to have common state (in the form of UniqueSupply) for generating Uniques.Float join points to top level if possible See Note [Floating join point bindings] in GHC.Core.Opt.SetLevels%Allow floating to the top level only.True  = float out over-saturated applications based on arity information. See Note [Floating over-saturated applications] in GHC.Core.Opt.SetLevelsTrue  = float constants to top level, even if they do not escape a lambdaJust n  = float lambdas to top level, if doing so will abstract over n or fewer value variables Nothing  = float all lambdas to top level, regardless of how many free variables Just 0 is the vanilla case: float a lambda iff it has no free varsLift an  operation into Lift an D operation into  while consuming its 2Adjust the dyn flags passed to the argument actionDrop the single count of the argument action so it doesn't effect the total.Get all annotations of a given type. This happens lazily, that is no deserialization will take place until the [a] is actually demanded and the [a] can also be empty (the UniqFM is not filtered).This should be done once at the start of a Core-to-Core pass that uses annotations.See Note [Annotations]Get at most one annotation of a given type per annotatable item.%Output a String message to the screenOutput a message to the screenOutput an error to the screen. Does not cause the compiler to die.Output a fatal error to the screen. Does not cause the compiler to die.Output a fatal error to the screen. Does not cause the compiler to die.8Output a string debugging message at verbosity level of -v or higher2Outputs a debugging message at verbosity level of -v or higherddump-simpl-statsMask"Ʉ$"$Ʉ  %                   None A  is a binding along with a cached set containing its free variables (both type variables and dictionaries). We need this set in splitDictBinds, when filtering bindings to decide which are captured by a binderThe binders of . Caches a superset of the expression `mkVarSet (bindersOfDictBinds fdb_binds))` for later addition to an InScopeSetAn argument that we might want to specialise. See Note [Specialising Calls] for the nitty gritty details.Type arguments that should be specialised, due to appearing free in the type of a ..Type arguments that should remain polymorphic.Dictionaries that should be specialised. mkCallUDs ensures that only "interesting" dictionary arguments get a SpecDict; see Note [Interesting dictionary arguments]/Value arguments that should not be specialised.Specialise calls to type-class overloaded functions occurring in a program..Specialise a set of calls to imported bindingsReturns whether or not to show a missed-spec warning. If -Wall-missed-specializations is on, show the warning. Otherwise, if -Wmissed-specializations is on, only show a warning if there is at least one imported function being specialized, and if all imported functions are marked with an inline pragma Use the most specific warning as the reason.(Given binders from an original function f , and the s corresponding to its usage, compute everything necessary to build a specialisation.?We will use the running example from Note [Specialising Calls]:=f :: forall a b c. Int -> Eq a => Show b => c -> Blah f a b @c i dEqA dShowB x = blah c -> Blah $sf = SUBST[a :-> T1, b :-> T2, dEqA :-> dEqT1, dShowB :-> dShow1] (@c i x -> blah)?where dShow1 is a floated binding created by bindAuxiliaryDict.The cases for  below are presented in the same order as this running example. The result of  for this example is as follows:( -- Returned arguments env + [a :-> T1, b :-> T2, dEqA :-> dEqT1, dShowB :-> dShow1] , [x]- RULE helpers , [c, i, d1, d2] , [T1, T2, c, i, d1, d2]- Specialised function helpers , [c, i, x] , [dShow1 = $dfShow dShowT2] , [T1, T2, c, i, dEqT1, dShow1] )Binds a dictionary argument to a fresh name, to preserve sharing Construct a  from a _!Identify the free variables of a _Flatten a set of "dumped" s, and some other binding pairs, into a single recursive binding.rr     %         !None 3Options for Specializing over constructors in Core.Specialise on arguments that are known constructors, even if they are not scrutinised in the body. See Note [Making SpecConstr keener].Max # of specialisations over recursive type. Stops ForceSpecConstr from diverging.Max # of specialisations for any one function. Nothing => no limit. See Note [Avoiding exponential blowup] and decreaseSpecCount#Size threshold: Nothing => no limit&The name of the module being processedUnfolding options"Whether to print debug informationThe threshold at which a worker-wrapper transformation used as part of this pass will no longer happen even if a SPEC arg was used to force specialization. Measured in the number of arguments. See Note [Forcing specialisation]The threshold at which a worker-wrapper transformation used as part of this pass will no longer happen, measured in the number of arguments.:Does this occurrence represent one worth specializing for.Substitute the free variables captured by a breakpoint. Variables are dropped if they have a non-variable substitution, like in  .wildCardPats are always boring           $NoneB5Clone the binders bound by a single-alternative case.      None  None DDDDDDDDD DDDDDDDDDNone?%In which ghc mode the flag has effectExtra action to run when the flag is found Typically, emit a warning or errorFlag in internal formFlag in string form "unbuild" a I from a ʄ. This shouldn't be needed in the vast majority of code. But GHCi questionably uses this to produce a default ʄ1 from which to compute a flags diff for printing.(Set the Haskell language standard to useIs the -fpackage-trust mode on9Is Safe Haskell on in some way (including inference mode)(Is the Safe Haskell safe language in use.Is the Safe Haskell safe inference mode active(Test if Safe Imports are on in some formSet a 'Safe Haskell' flagAre all direct imports required to be safe for this Safe Haskell mode? Direct imports are when the code explicitly imports a moduleAre all implicit imports required to be safe for this Safe Haskell mode? Implicit imports are things in the prelude. e.g System.IO when print is used.Combine two Safe Haskell modes correctly. Used for dealing with multiple flags. This makes Safe Haskell very much a monoid but for now I prefer this as I don't want to export this functionality from the module but do want to export the type constructors.A list of unsafe flags under Safe Haskell. Tuple elements are: * name of the flag * function to get srcspan that enabled the flag * function to test if the flag is on * function to turn the flag offA list of unsafe flags under Safe Haskell. Tuple elements are: * name of the flag * function to get srcspan that enabled the flag * function to test if the flag is on * function to turn the flag off3Retrieve the options corresponding to a particular opt_* field in the correct orderGets the verbosity flag for the current verbosity level. This is fed to other tools, so GHC-specific verbosity flags like  -ddump-most are not included Sets the ʄ to be appropriate to the optimisation level and signals if any changes took place Sets the ʄ, to be appropriate to the optimisation levelParse dynamic flags from a list of command line arguments. Returns the parsed ʄ=, the left-over arguments, and a list of warnings. Throws a  if errors occurred during parsing (such as unknown flags or missing arguments).Like  but does not allow the package flags (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db). Used to parse flags set in a modules pragma.A helper to parse a set of flags from a list of command-line arguments, handling response files.Parses the dynamically set flags for GHC. This is the most general form of the dynamic flag parser that the other methods simply wrap. It allows saying which flags are valid flags and indicating if we are parsing arguments from the command line or from a file pragma.Check (and potentially disable) any extensions that aren't allowed in safe mode.The bool is to indicate if we are parsing command line flags (false means file pragma). This allows us to generate better warnings.Produce a list of suggestions for a user provided flag that is invalid.All dynamic flags option strings without the deprecated ones. These are the user facing strings for enabling and disabling options.4All flags with possibility to filter deprecated ones;Warnings have both new-style flags to control their state (-W, -Wno-, -Werror=, -Wwarn=) and old-style flags (-fwarn-,  -fno-warn-). We define these uniformly for individual warning flags and groups of warnings.This is where we handle unrecognised warning flags. If the flag is valid as an extended warning category, we call the supplied action. Otherwise, issue a warning if -Wunrecognised-warning-flags is set. See #11429 for context. See Note [Warning categories] in GHC.Unit.Module.Warnings.Make a list of flags for shell completion. Filter all available flags into two groups, for interactive GHC vs all other.Define a new flag.!Define a new flag with an effect.Define a warning flag.%Define a warning flag with an effect.,Define a new deprecated flag with an effect.Define a new deprecated flag.!Define a deprecated warning flag.8Define a deprecated warning name substituted by another.Define a new deprecated flag with an effect where the deprecation message depends on the flag valueDefine a new deprecated flag where the deprecation message depends on the flag valueDefine a new flag for GHCi.*Define a new flag for GHCi with an effect..Define a new flag invisible to CLI completion.=Define a new flag invisible to CLI completion with an effect.Hide a  from being displayed in --show-options.This is for example useful for flags that are obsolete, but should not (yet) be deprecated for compatibility reasons. Find the  for a .These -W flags can all be reversed with  -Wno-These - flags can all be reversed with  -no-These -d flags can all be reversed with  -dno-These -f flags can all be reversed with  -fno-These -f flags have to do with the typed-hole error message or the valid hole fits in that message. See Note [Valid hole fits include ...] in the GHC.Tc.Errors.Hole/ module. These flags can all be reversed with  -fno-These -f flags can all be reversed with  -fno-These -X blah# flags cannot be reversed with -XNo blahThese -X blah# flags cannot be reversed with -XNo blah They are used to place hard requirements on what GHC Haskell language features can be used.These -X blah$ flags can all be reversed with -XNo blahThings you get with `-dlint`.1Resolve any internal inconsistencies in a set of ʄ. Returns the consistent ʄ6 as well as a list of warnings to report to the user.,Indicate if cost-centre profiling is enabled1Indicate whether we need to generate source notesShould we use `-XLinker -rpath` when linking or not? See Note [-fno-use-rpaths]/Pretty-print the difference between 2 DynFlags.For now only their general flags but it could be extended. Useful mostly for debugging.ʄ to retrieve the options from%Relevant record accessor: one of the opt_* accessors#Correctly ordered extracted optionsUpdated ʄ-, left-over arguments, and list of warnings.Updated ʄ-, left-over arguments, and list of warnings.valid flags to match against current statearguments to parse(leftovers, errors, warnings)valid flags to match against(are the arguments from the command line?current dynamic flagsarguments to parseSet the warningUnset the warningMake the warning an errorClear the error statusTrue  = it should be turned onThe flag prefix!What to do when the flag is found&Specification of this particular flag!!!!!!!!+IIIJIIIIIJIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJIIƄDŽʄ˄ڄل؄ׄքՄɅۄބ̄Å݅΅ׅDžԄօ…ͅ΄݄ȅąŅƅ߅τӄ҄фЅӅՅۅхԅ؅߄҅Єڅ܅υ˅ʅ̅܄م̈́ޅńÄĄȄɄ„ !!!!!!!!!!! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                                   !!!!!!+++++++IIIIIIIIIIIIIIIIIIIҁ !!!!!!!!!!! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                                   ҁҁ!!!!!ńÄĄ!„ʄ˄ڄل؄ׄքՄɅۄބ̄Å݅΅ׅDžԄօ…ͅ΄݄ȅąŅƅ߅τӄ҄фЅӅՅۅхԅ؅߄҅Єڅ܅υ˅ʅ̅܄م̈́ޅȄɄƄDŽ!!IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJIIIIIIIIIII+++++++!!!!!!+  "    None(See the Note [Preprocessing invocations]Use the ordinary C preprocessorUse the Haskell C preprocessor (don't remove C comments, don't break on names including single quotes)Use the JavaScript preprocessor (don't remove jsdoc and multiline comments)7Use the C-- preprocessor (don't emit debug information)Prepend the working directory to the search path. Note [Filepaths and Multiple Home Units]>Discard some harmless warnings from gcc that we can't turn offRun source code preprocessor. See also Note [Preprocessing invocations] in GHC.SysTools.CppRun compiler of C-like languages and raw objects (such as gcc or clang).8Run the linker with some arguments and return the outputRun the LLVM OptimiserRun the LLVM CompilerRun the LLVM Assembler
Initialize the Llvm code generator configuration from DynFlagsNoneSee Note [Initializers and finalizers in Cmm] in GHC.Cmm.InitFini for details.(Generate code to initialise cost centresGenerate code to initialise info pointer origin See Note [Mapping Info Tables to Source Positions] 3additional files to be compiled with the C compiler  Dependencies The deterministic unique supply to run the CgStream. See Note [Deterministic Uniques in the CG]  Compiled C--The deterministic uniq supply to run the CgStream See Note [Deterministic Uniques in the CG]The deterministic uniq supply to run the CgStream See Note [Deterministic Uniques in the CG]The deterministic uniq supply to run the CgStream See Note [Deterministic Uniques in the CG]None .The profiling header words in a static closure+Profiling header words in a dynamic closure1Initialise the profiling field of an update frameRecord the allocation of a closure. The CmmExpr is the cost centre stack to which to attribute the allocation.Record the allocation of a closure (size is given by a CmmExpr) The size must be in words, because the allocation counter in a CCS counts in words. 0) - Initialise to the LDV word * When eras profiling is enabled (user_era > 0) - Initialise to current user_eraCalled when a closure is entered, marks the closure as having been "used". The closure is not an "inherently used" one. The closure is not IND2 because that is not considered for LDV profiling.Takes the address of a closure, and returns the address of the prof header word in the closure (this is used to store LDV info, retainer profiling info and eras profiling info).NoneL!Low-level heap object allocation.Make a static closure, adding on any extra padding needed for CAFs, and adding a static link field if necessary.lower-level version for GHC.Cmm.Parser/The generic GC procedure; no params, no results;Create a CLabel for calling a garbage collector entry pointrepresentation of the object info pointer cost centrepayload!returns the address of the objectPayloadExtra non-pointers that go to the end of the closure. See Note [unpack_cstring closures] in StgStdThunks.cmm.None #&'+Maps labels from  to the final CLabel that will appear in the SRT. - closures with singleton SRTs resolve to their single entry - closures with larger SRTs map to the label for that SRT - CAFs must not map to anything! - if a labels maps to Nothing, we found that this label's SRT is empty, so we don't need to refer to it from other SRTs.The reverse mapping, so that we can remove redundant entries. e.g. if we have an SRT [a,b,c], and we know that b points to [c,d], we can omit c and emit [a,b]. Used to implement the [Filter] optimisation.previous SRTs we've emitted, so we can de-duplicate. Used to implement the [Common] optimisation.Current module being compiled. Required for calling labelDynamic.;Records the CAFfy references of a set of static data decls.The label of a CAFfy thing.Labels that come from  can be: - _closure labels for static functions, static data constructor applications, or static thunks - _info= labels for dynamic functions, thunks, or continuations - _entry labels for functions or thunks-Meanwhile the labels on top-level blocks are _entry labels.To put everything in the same namespace we convert all labels to closure labels using o. Note that some of these labels will not actually exist; that's ok because we're going to map them to SRTEntry later, which ranges over labels that do exist.)Collect possible CAFfy references from a ƻ decl.For each code block: - collect the references reachable from this code block to FUN, THUNK or RET labels for which hasCAF == TrueThis gives us a -: a mapping from code block to sets of labels Return a (Label,CLabel)# pair for each labelled block of a », where the label is - the info label for a continuation or dynamic closure - the closure label for a top-level function (not a CAF)Put the labelled blocks that we will be annotating with SRTs into dependency order. This is so that we can process them one at a time, resolving references to earlier blocks to point to their SRTs. CAFs themselves are not included here; see  below.Get )(Maybe Label, CAFfyLabel, Set CAFfyLabel) for each CAF block. The Set CAFfyLabel represents the set of CAFfy things which this CAF's code depends upon.The ; represents the entry code of the closure. This may be K( if it is a standard closure type (e.g. stg_unpack_cstring>; see Note [unpack_cstring closures] in StgStdThunks.cmm).The CAFLabel! is the label of the CAF closure.The  Set CAFLabel is the set of CAFfy closures which should be included in the closure's SRT.Note that CAFs are treated differently from other labelled blocks:we never shortcut a reference to a CAF to the contents of its SRT, since the point of SRTs is to keep CAFs alive.CAFs therefore don't take part in the dependency analysis in depAnalSRTs. instead we generate their SRTs after everything else.Get the list of blocks that correspond to the entry points for  FUN_STATIC closures. These are the blocks for which if we have an SRT we can merge it with the static closure. [FUN]Given  of a module, returns the set of non-CAFFY names in the module. Any Names not in the set are CAFFY.Resolve a CAFfyLabel to its  using the .&Attach SRTs to all info tables in the »$s, and add SRT declarations to the .;Build the SRT for a strongly-connected component of blocks. Build an SRT for a set of blocksBuild a static SRT object (or a chain of objects) from a list of s.Update info tables with references to their SRTs. Also generate static closures, splicing in SRT fields as necessary.The blocks representing continuations, ie. those that will get RET info tables. These labels will get their own SRTs, so we don't aggregate CAFs from references to these labels, we just use the label.The top label of the proc for procedures. From .CAFEnv for statics. Maps statics to the set of the CAFfy things which they refer to. From .the decls to analyse.s and »s for code blocksstatic data decls and their s-which blocks are static function entry points static data-which blocks are static function entry pointsblocks in this setlabels for those blocksTrue  = this SRT is for a CAFSRT for this setSRT labels for each block&SRTs to merge into FUN_STATIC closures.Whether the CmmDecl's group has CAF references   =             None  Emit code for a foreign call, and return the results to the sequel. Precondition: the length of the arguments list is the same as the arity of the foreign function.1Produce code to save the current thread state to  CurrentTSOSave STG registersSTG registers must be saved around a C call, just in case the STG register is mapped to a caller-saves machine register. Normally we don't need to worry about this the code generator has already loaded any live STG registers into variables for us, but in hand-written low-level Cmm code where we don't know which registers are live, we might have to save them all.Restore STG registers (see )Push a subset of STG registers onto the stack, specified by the bitmapSometimes, a "live" subset of the STG registers needs to be saved on the stack, for example when storing an unboxed tuple to be used in the GHCi bytecode interpreter.The "live registers" bitmap corresponds to the list of registers given by , with the least significant bit indicating liveness of the first register in the list.Each register is saved to a stack slot of one or more machine words, even if the register size itself is smaller.The resulting Cmm code looks like this, with a line for each real or virtual register used for returning tuples:... if((mask & 2) != 0) { Sp_adj(-1); Sp(0) = R2; } if((mask & 1) != 0) { Sp_adj(-1); Sp(0) = R1; })See Note [GHCi and native call registers]2Pop a subset of STG registers from the stack (see )closeNursery dflags tso produces code to close the nursery. A local register holding the value of  CurrentTSO is expected for efficiency.6Closing the nursery corresponds to the following code:  tso = CurrentTSO; cn = CurrentNuresry; // Update the allocation limit for the current thread. We don't // check to see whether it has overflowed at this point, that check is // made when we run out of space in the current heap block (stg_gc_noregs) // and in the scheduler when context switching (schedulePostRunThread). tso->alloc_limit -= Hp + WDS(1) - cn->start; // Set cn->free to the next unoccupied word in the block cn->free = Hp + WDS(1); 3Produce code to load the current thread state from  CurrentTSOopenNursery profile tso produces code to open the nursery. A local register holding the value of  CurrentTSO is expected for efficiency.6Opening the nursery corresponds to the following code:  tso = CurrentTSO; cn = CurrentNursery; bdfree = CurrentNursery->free; bdstart = CurrentNursery->start; // We *add* the currently occupied portion of the nursery block to // the allocation limit, because we will subtract it again in // closeNursery. tso->alloc_limit += bdfree - bdstart; // Set Hp to the last occupied word of the heap block. Why not the // next unoccupied word? Doing it this way means that we get to use // an offset of zero more often, which might lead to slightly smaller // code on some architectures. Hp = bdfree - WDS(1); // Set HpLim to the end of the current nursery block (note that this block // might be a block group, consisting of several adjacent blocks. HpLim = bdstart + CurrentNursery->blocks*BLOCK_SIZE_W - 1; None 'Out of line fake primop that's actually just a foreign call to other (presumably) C--.‘#Real primop turned into inline C--.ÑInterpret the argument as an unsigned value, assuming the value is given in two-complement form in the given width. Example: asUnsigned W64 (-1) is 18446744073709551615.This function is used to work around the fact that many array primops take Int# arguments, but we interpret them as unsigned quantities in the code gen. This means that we have to be careful every time we work on e.g. a CmmInt literal that corresponds to the array size, as it might contain a negative Integer value if the user passed a value larger than 2^(wORD_SIZE_IN_BITS-1) as the Int# literal.đ*The big function handling all the primops.In the simple case, there is just one implementation, and we emit that.In more complex cases, there is a foreign call (out of line) fallback. This might happen e.g. if there's enough static information, such as statically known arguments.ő1Implements branchless recovery of the carry flag c/ by checking the leftmost bits of both inputs a and b and result  r = a + b:  c = a&b | (a|b)&~r  https://brodowsky.it-sky.net/2015/04/02/how-to-recover-the-carry-bit/Ƒ1Implements branchless recovery of the carry flag c/ by checking the leftmost bits of both inputs a and b and result  r = a - b:  c = ~a&b | (~a|b)&r  https://brodowsky.it-sky.net/2015/04/02/how-to-recover-the-carry-bit/Ǒ?Translate byte array prefetch operations into proper primcalls.ȑTranslate mutable byte array prefetch operations into proper primcalls.ɑ, but check for range overlap when -fcheck-prim-bounds is on.Emit a call to memmove.Emit a call to memset9. The second argument must fit inside an unsigned char.Write barrier for MUT_VAR modification.Push a range of pointer-array elements that are about to be copied over to the update remembered set.đ The primopThe primop arguments element type index typeבreturn registerrepresentation of the array info pointerheader payload array sizeinitial element copy function source arrayoffset in source arraydestination arrayoffset in destination arraynumber of elements to copy copy function source arrayoffset in source arraydestination arrayoffset in destination arraynumber of elements to copyݑ Result regAtomic op (e.g. add)MutableByteArray#Index(Type of element by which we are indexing Op argument (e.g. amount to add) Result regAtomic op (e.g. add)Addr#Pointed value type Op argument (e.g. amount to add)ޑ Result regMutableByteArray#Index(Type of element by which we are indexingߑ Result regAddr#(Type of element by which we are indexingMutableByteArray#Index(Type of element by which we are indexingValue to writeAddr#(Type of element by which we are indexingValue to write Result regMutableByteArray#Index(Type of element by which we are indexing Old value New valueaccessed indexarray size (in elements)first accessed index%number of accessed indices (non-zero)array size (in elements)accessed index (in bytes) pointer to  StgMutArrPtrsaccessed index (in bytes) pointer to  StgMutArrPtrsaccessed index (in elements) pointer to  StgArrBytes indexing type element typearray header size (in bytes)destination array&offset in destination array (in words)number of elements to copyNone&'+S regs on the stackNumber of words of stack that we do not describe with an info table, because it contains an update frame.the number of bytes of arguments in the area for this block Defn: the offset of young(L) relative to the base is given by (sm_sp - sm_args) of the StackMap for block L.>the offset of Sp relative to the base on entry to this block.create a sequence of assignments to establish the new StackMap, given the old StackMap.Given a set of live registers and a StackMap, save all the registers on the stack and return the new StackMap and the assignments to do the saving.Manifest Sp: turn all the CmmStackSlots into CmmLoads from Sp. The block looks like this:middle_pre -- the middle nodes Sp = Sp + sp_off -- Sp adjustment goes here last -- the last nodeAnd we have some extra blocks too (that don't contain Sp adjustments)The adjustment for middle_pre will be different from that for middle_post, because the Sp adjustment intervenes.,Determine whether a stack check cannot fail.Eliminate stores of the formSp[area+n] = rwhen we know that r is already in the same slot as Sp[area+n]. We could do this in a later optimisation pass, but that would involve a separate analysis and we already have the information to hand here. It helps clean up some extra stack stores in common cases.Note that we may have to modify the StackMap as we walk through the code using procMiddle, since an assignment to a variable in the StackMap will invalidate its mapping there.   NoneH!Top level driver for C-- pipelineConverts C-- with an implicit stack and native C-- calls into optimized, CPS converted and native-call-less C--. The latter C-- can be used to generate assembly.The Cmm pipeline for a single » . Returns:in the case of a Ż: N3 of the resulting (possibly proc-point-split) » s and their CafEnv. CAF analysis necessarily happens *before* proc-point splitting, as described in Note [SRTs].in the case of a ƻ, the unmodified » and a  containingNoney Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone# -Retrieve library directories provided by the UnitId in  UnitState0Retrieve the names of the libraries provided by UnitId?A constant holding the JavaScript executable Filename extension5CPP definitions that are inserted into every .pp fileCPP definitions for normal operation and profiling. Use CAFs for commonCppDefs_* so that they are shared for every CPP fileCPP definitions for normal operation and profiling. Use CAFs for commonCppDefs_* so that they are shared for every CPP file,Generate macros MK_TUP* for tuples sized 2+.Generate CPP Definitions depending on a profiled or normal build. This occurs at link time.Construct the Filename for the "binary" of Haskell code compiled to JavaScript."(c) The University of Glasgow 2001 BSD-style (see the file LICENSE)Jeffrey Young Luite Stegeman Sylvain Henry Josh Meredith  experimentalNone#/ #)ModuleCode after link with other modules.It contains less information than ModuleCode because they have been commoned up into global "metadata" for the whole link.rendered exportsCompiled modulerendered exportsCc objects to linkJS objects to linkHS objects to link&Extra root functions from loaded units>Predicate for exported functions in objects to declare as rootnumber of bytes for metadata!number of bytes linked per module/link and write result to disk (jsexe directory)Given a base0 link plan (assumed to be already linked) and a new0 link plan, compute `(diff, total)` link plans.diff* is the incremental link plan to get from base to totaltotal is the total link plan as if base and new were linked at once9Output JS statements and return the output size in bytes.8Link modules and pretty-print them into the given HandleRender linker statsCombine rts.js, lib.js, out.js to all.js that can be run directly with node.js or SpiderMonkey jsshellwrite the index.html file that loads the program if it does not exitwrite the runmain.js file that will be run with defer so that it runs after index.html is loaded3Get all block dependencies for a given set of roots2Returns the updated block info map and the blocks.'collect dependencies for a set of rootsLoad an archive in memory and store it in the cache for future loads.8dependencies for the RTS, these need to be always linkedExport the functions in  ghc-internalExport the Prim functionsGiven a UnitId, a module name, and a set of symbols in the module, package these into an  ExportedFun.Given a Module< and a set of symbols in the module, package these into an  ExportedFun.4read all dependency data from the to-be-linked files(Load dependencies for the Linker from Arread block info from an object that might have already been into memory pulls in all Deps from an archive(Embed a JS file into a JS object .o fileJS files may contain option pragmas of the form: //#OPTIONS: One of those is //#OPTIONS:CPP. When it is set, we append some common CPP definitions to the file and call cpp on it.Other options (e.g. EMCC additional flags for link time) are stored in the JS object header. See JSOptions.Link module codes.Performs link time optimizations and produces one JStat per module plus some commoned up initialization code./Only keep a single StaticInfo with a given nameInitialize a global object.>All global objects have to be declared (staticInfoDecl) first.declare and do first-pass init of a global object (create JS object for heap objects)output file/directory+should we render readable JS for debugging?linked code per moduleoutput directoryoutput directorySettingsOutput directoryBlock info per module"Used to load block info if missing start hereand also link theseobject files to link  None+/M Start NodeJS interactively with "ghc-interp.js" script loaded inSpawn a JS interpreterRun NodeJS with "ghc-interp.js" loaded in. Then load GHCi.Server and its deps (including the rts) and run GHCi.Server.defaultServer. Link JS RTSLink JS interpreterLink object files6Link an object file using the given functions as rootsLink the given link planPerform incremental linking by removing what is already linked from the plan$Send a command to the JS interpreter!Load a JS file in the interpreter Run JS serverNone #3Run a command in the interpreter's context. With -fexternal-interpreter, the command is serialized and sent to an external iserv process, and the response is deserialized (hence the Binary constraint). With -fno-external-interpreter' we execute the command directly here.Grab a lock on the  and do something with it. Overloaded because this is used from TcM as well as IO.Spawn JS interpreter if it isn't already running and execute the given actionUpdate the interpreter state.Spawn an interpreter if not already running according to the status in the MVar. Update the status, free pending heap references, and return the interpreter instance.This function is generic to support both the native external interpreter and the JS one.Execute an action of type IO [a] , returning s for each of the results.Execute an action of type IO ()Execute an action of type  IO StringExecute an action of type String -> IO StringAllocate and store the given bytes in memory, returning a pointer to the memory in the remote process.4Create a set of BCOs that may be mutually recursive.Send a Seq message to the iserv process to force a value #2950Process the result of a Seq or ResumeSeq message. #2950 tries to find a symbol in the  which maps symbols to the address where they are loaded. When there's a cache hit we simply return the cached address, when there is a miss we run the action which determines the symbol's address and populate the cache with the answer.loadDLL loads a dynamic library using the OS's native linker (i.e. dlopen() on Unix, LoadLibrary() on Windows). It takes either an absolute pathname to the file, or a relative filename (e.g. "libfoo.so" or "foo.dll"). In the latter case, loadDLL searches the standard locations for the appropriate library.Spawn an external interpreterStop the interpreter Creates a & that will automatically release the ! when it is no longer referenced. Convert a  to the value it references directly. This only works when the interpreter is running in the same process as the compiler, so it fails when -fexternal-interpreter is on. Convert an  to the value it references directly. This only works when the interpreter is running in the same process as the compiler, so it fails when -fexternal-interpreter is on.Interpreter uses Profiling wayInterpreter uses Dynamic way)The symbol we are looking up in the cacheAn action which determines the address of the symbol we are looking up in the cache, which is run if there is a cache miss. The result will be cached.None On macOS we rely on the linkers -dead_strip_dylibs flag to remove unused libraries from the dynamic library. We do this to reduce the number of load commands that end up in the dylib, and has been limited to 32K (32768) since macOS Sierra (10.14).-dead_strip_dylibs does not dead strip -rpath entries, as such passing -l and -rpath to the linker will result in the unnecessary libraries not being included in the load commands, however the -rpath entries are all forced to be included. This can lead to 100s of -rpath entries being included when only a handful of libraries end up being truly linked.Thus after building the library, we run a fixup phase where we inject the -rpath for each found library (in the given library search paths) into the dynamic library through  -add_rpath.#See Note [Dynamic linking on macOS]None&' Enabled waysOptions for diagnostics Use bytecode rather than objects$Rendering options for error messagesIs the driver in one-shot mode?Always use .dyn_o?Suffix of .o filesFind all the packages and linkables that a set of modules depends onReturn the module and package dependencies for the needed modules. See Note [Object File Dependencies]8Fails with an IO exception if it can't find enough filesNonerInitialize memory for breakpoint data that is shared between the bytecode generator and the interpreter.Since GHCi and the RTS need to interact with breakpoint data and the bytecode generator needs to encode this information for each expression, the data is allocated remotely in GHCi's address space and passed to the codegen as foreign pointers.NoneNone&'pFinds external references. Remember to remove the names defined by this group of BCOs themselves      None&' Next index for breakInfo arrayInfo at breakpoint occurrence. Indexed with breakpoint *info* index. See Note [Breakpoint identifiers] in GHC.Types.BreakpointMaps Ids to their stack depth. This allows us to avoid having to mess with it after each push/pop.see Note [Generating code for top-level string literal bindings]Introduce break instructions for ticked expressions. If no breakpoint information is available, the instruction is omitted.Determine the GHCi-allocated  BreakArray and module pointer for the module from which the breakpoint originates. These are stored in v as remote pointers in order to allow the BCOs to refer to pointers in GHCi's address space. They are initialized in   , called by  . value. We only base the finger print on important fields in DynFlags= so that the recompilation checker can use this fingerprint.NB: The  parameter is the 3 recorded by the *interface* file, not the actual  according to our ʄ.NoneNone+lGiven: * an initial mapping from info tables to possible source locations, * initial  , * a Ȼ,#map every info table listed in the Ż>s of the group to their possible source locations and update  for skipped stack info tables (in case both -finfo-table-map and -fno-info-table-map-with-stack were given). See: Note [Stacktraces from Info Table Provenance Entries (IPE based stack unwinding)]Note: While it would be cleaner if we could keep the recursion and accumulation internal to this function, this cannot be done without separately traversing stream of Ȼ in   . The initial implementation of this logic did such a thing, and code generation performance suffered considerably as a result (see #23103).See Note [Stacktraces from Info Table Provenance Entries (IPE based stack unwinding)]See Note [Stacktraces from Info Table Provenance Entries (IPE based stack unwinding)]If the CmmInfoTables map refer Cmm symbols which were deterministically renamed, the info table provenance map must also be accordingly renamed.NoneA4Initialize STG pretty-printing options from DynFlagsNone2%Extracts the flags needed for parsingNoneNone:-Initialize linker configuration from DynFlagsNone7Some platforms require that we explicitly link against libm if any math-y things are used (which we assume to include all programs). See #14022.NoneLinking a static lib will not really link anything. It will merely produce a static archive of all dependent static libraries. The resulting library will still need to be linked with any remaining link flags.NoneY)Initialize StgToJS settings from DynFlagsDefault linker configurationNoneNone s*s that should be treated as being in scopeLinting the result of this passTarget platformDiagnostics optsAllow  makeStatic to occur anywhere.Allow  makeStatic calls at the top-level only. Reject any  makeStatic occurrence.See Note [Linting linearity],See Note [Linting type synonym applications]See Note [Checking StaticPtrs]Target platformTarget platformConfiguration for boilerplate operations at the end of a compilation pass producing Core./Whether we should lint the result of this pass.Whether core bindings should be dumped with the size of what they are binding (i.e. the size of the RHS of the binding). Type-check a _!. See Note [Core Lint guarantee].1Checks the RHS of bindings. It only differs from 8 in that it doesn't reject occurrences of the function  makeStatic( when they appear at the top level and 'lf_check_static_ptrs == AllowAtTopLevel, and for join points, it skips the outer lambdas that take arguments to the join point.See Note [Checking StaticPtrs].9Lint the RHS of a join point with expected join arity of n (see Note [Join points] in GHC.Core).Lint an expression cast through the given coercion, returning the type resulting from the cast.Check representation-polymorphic invariants in an application of a built-in function or newtype constructor.7See Note [Linting representation-polymorphic builtins].Compute the 1-indexed positions in the outer forall'd quantified type variables of the type in which the concrete type variables occur.See Note [Representation-polymorphism checking built-ins] in GHC.Tc.Utils.Concrete.'Implements the case rules for linearitylintValApp arg fun_ty arg_ty lints an application of fun arg where  fun :: fun_ty and  arg :: arg_ty), returning the type of the application.Check to make sure that an axiom application is internally consistent. Returns the conflicting branch, if it exists Note [Conflict checking for axiom applications]This checks whether a pass correctly looks through debug annotations ( SourceNote). This works a bit different from other consistency checks: We check this by running the given task twice, noting all differences between the results.Run the given pass without annotations. This means that we both set the debugLevel setting to 0 in the environment as well as all annotations from incoming modules.If M!, display linter warnings. If J, ignore linter warnings. The source of the linted program"The linted program, pretty-printedTrue  = is a compulsory unfolding6the function (head of the application) we are checking the arguments to the application0the instantiated type of the overall applicationThe source of the linted axioms Action to run>What sort of casted thing this is ("expression" or "type").:What sort of coercion is being used ("type" or "kind").The thing being casted.,,          None) !See Note [CorePrepEnv: cpe_subst]This flag is intended to aid in debugging strictness analysis bugs. These are particularly nasty to chase down as they may manifest as segmentation faults. When this flag is enabled we instead produce an i expression to catch the case where a function we think should bottom unexpectedly returns."Configuration for arity analysis (q<). See Note [Eta expansion of arguments in CorePrep] When K# (e.g., -O0, -O1), use the cheaper q instead/Whether to generate a default alternative with i in these cases. This is helpful when debugging demand analysis or type checker bugs which can sometimes manifest as segmentation faults.Anything that can be bound at top-level, such as arbitrary lifted bindings or anything that responds True to q, such as literals or saturated DataCon apps where unlifted or strict args are values.Anything that can be floated out of a lazy context. In addition to any  things, this includes (unlifted) bindings that are ok-for-spec that we intend to case-bind.Anything that can be floated out of a strict evaluation context. That is possible for all bindings; this is the Top element of ’.ÒA strict bindingĒA lazy or value bindingŒ Convert a  so it satisfies ƒ, without producing any floats (any generated floats are immediately let-bound using ǒ). Generally you want this, esp. when you've reached a binding form (e.g., a lambda) and floating any further would be incorrect.Ȓ Convert a  so it satisfies ƒ; also produce a list of ɒ which are being propagated upwards. In fact, this function is used in only two cases: to implement Œ (which is what you usually want), and in the case when a let-binding is in a case scrutinee--here, we can always float out:case (let x = y in z) of ... ==> let x = y in case z of ...ʒSee Note [Eta expansion of arguments in CorePrep] Returning 0 means "no eta-expansion"; see cpeEtaExpand˒/Identify the cases where we'd generate invalid ̒s as described in Wrinkle (EA1) of Note [Eta expansion of arguments in CorePrep]͒ Append a Β b to a ɒ telescope bs( that may reference any binding of the ɒ.ϒCons a Β b to a ɒ telescope bs which scopes over b.В9Append two telescopes, nesting the right inside the left.ђ Zip up two ɒ$, none of which scope over the otherҒђ# a bunch of independent telescopes.ǒ Wrap floats around an expressionӒPut floats at top-levelԒ+Like wrapFloats, but only wraps tick floatsՒ2Converts Bignum literals into their final CoreExpr          !      None&Add late cost centres directly to the . This is used inside the core pipeline with the -fprof-late-inline flag. It should not be used after tidy, since it does not manually track inserted cost centers. See Note [Collecting late cost centres].Insert cost centres on top-level bindings in the module, depending on whether or not they satisfy the given predicate.None&'3Late cost center insertion logic used by the driverLoggerLate cost center configuration The programNone Stop[e] = e֒Describes how the  will evaluate the hole as a ]. This can be more insightful than the limited syntactic context that  provides, because the # constructor might carry a useful ].. For example, when simplifying the argument e in `f e` and f has the demand signature ` MP(S,A)?`, this function will give you back `P(S,A)` when simplifying e.PRECONDITION: Don't call with . We haven't thoroughly thought about what to do then and no call sites so far seem to care. Type of the holeTells if there is something interesting about the syntactic context, and hence the inliner should be a bit keener (see interestingCallContext) Specifically: This is an argument of a function that has RULES Inlining the call might allow the rule to fire Never ValAppCxt (use ApplyToVal instead) or CaseCtxt (use Select instead)The evaluation context of e. Tells how e is evaluated. This fuels eta-expansion or eta-reduction without looking at lambda bodies, for example.See Note [Eta reduction based on evaluation context] The evaluation context for other SimplConts can be reconstructed with ֒        None גPush a TickIt context outwards past applications and cases, as long as this is a non-scoping tick, to let case and application optimisations apply.ؒ.A "friendly name" to build the new binder fromْ(Type of the function applied to this argJust  = This arg ai occurs in an app `f a1 ... an` where we have ArgInfo on how f uses ai/, affecting the Stop continuation passed to ڒExpression with its static envtNoneConfiguration record for #. The values of this datatype are only( driven by the demands of that function.Configuration record for #. The values of this datatype are only( driven by the demands of that function.NoneWThe core-to-core simplifier.'A description of the plugin pass itself NoneC Type-check a _!. See Note [Core Lint guarantee].None+0The current collection of docs that Template Haskell has built up via putDoc.This is a mirror of Template Haskell's DocLoc, but the TH names are resolved to GHC names.$A plugin for controlling defaulting.9Clean up after the plugin, when exiting the type-checker.Default some types.Initialize plugin, when entering type-checker.A collection of candidate default types for sets of type variables.3The constraints against which defaults are checked.%The type variable assignments to try.8The plugin does not rewrite the type family application.The plugin rewrites the type family application providing a rewriting together with evidence: a `5, which contains the rewritten type together with a Coercion3 whose right-hand-side type is the rewritten type.7The plugin can also emit additional Wanted constraints."Result of running a solver plugin./New constraints that the plugin wishes to emit.%These will be added to the work list.1Solved constraints, together with their evidence.These are removed from the inert set, and the evidence for them is recorded.*Insoluble constraints found by the plugin.These constraints will be added to the inert set, and reported as insoluble to the user.9Clean up after the plugin, when exiting the type-checker.+Rewrite saturated type family applications.The plugin is expected to supply a mapping from type family names to rewriting functions. For each type family , the plugin should provide a function which takes in the given constraints and arguments of a saturated type family application, and return a possible rewriting. See + for the expected shape of such a function.Use  \ _ -> emptyUFM 4 if your plugin does not provide this functionality.Solve some constraints.This function will be invoked at two points in the constraint solving process: once to simplify Given constraints, and once to solve Wanted constraints. In the first case (and only in the first case), no Wanted constraints will be passed to the plugin.The plugin can either return a contradiction, or specify that it has solved some constraints (with evidence), and possibly emit additional constraints. These returned constraints must be Givens in the first case, and Wanteds in the second.Use & \ _ _ _ _ -> pure $ TcPluginOk [] [] 5 if your plugin does not provide this functionality..Initialize plugin, when entering type-checker.5 is the monad in which type-checking plugins operate.For rewriting type family applications, a type-checking plugin provides a function of this type for each type family .The function is provided with the current set of Given constraints, together with the arguments to the type family. The type family application will always be fully saturated.The solve function of a type-checking plugin takes in Given and Wanted constraints, and should return a  indicating which Wanted constraints it could solve, or whether any are insoluble. describes the top-level of the module at the point at which the typechecker is finished work. It is this structure that is handed on to the desugarer For state that needs to be updated during the typechecking phase and returned at end, use a  (= ).2See Note [Generating fresh names for FFI wrappers],Tracking indices for cost centre annotationsWanted constraints of static forms. See Note [Constraints in static forms].%The RealSrcSpan this module came from8A list of user-defined plugins for hole fit suggestions.;A list of user-defined plugins for type defaulting plugins.A collection of all the user-defined type-checking plugins for rewriting type family applications, collated by their type family s.A list of user-defined type-checking plugins for constraint solving.Unreported reasons why tcg_safe_infer is False. INVARIANT: If this Messages is non-empty, then tcg_safe_infer is False. It may be that tcg_safe_infer is False but this is empty, if no reasons are supplied (#19714), or if those reasons have already been reported by GHC.Driver.Main.markUnsafeInferHas the typechecker inferred this module as -XSafe (Safe Haskell)? See Note [Safe Haskell Overlapping Instances Implementation], although this is used for more than just that failure case.The Name of the main function, if this module is the main module.5Whether this module has a corresponding hi-boot fileTrue if any part of the prog uses hpc instrumentation. NB. BangPattern is to fix a leak, see #151117Maybe Haddock header docs and Maybe located module name#Docs added in Template Haskell via putDoc.Template Haskell state,Core plugins added by Template Haskell code.#Template Haskell module finalizers.+They can use particular local environments.>Exact names bound in top-level declarations in tcg_th_topdeclsForeign files emitted from TH.'Top-level declarations from addTopDecls"dependencies from addDependentFileRenamed decls, maybe. Nothing! <=> Don't retain renamed decls.The requirements we merged with; we always have to recompile if any of these changed.A source of unique identities for ZonkAny instances See Note [Any types] in GHC.Builtin.Types, wrinkle (Any4)&Allows us to choose unique DFun names.The set of runtime dependencies required by this module See Note [Object File Dependencies]True( <=> A Template Haskell splice was used.2Splices disable recompilation avoidance (see #481)True" <=> Template Haskell syntax used.We need this so that we can generate a dependency on the Template Haskell package, because the desugarer is going to emit loads of references to TH symbols. The reference is implicit rather than explicit, so we have to zap a mutable variable.INVARIANT: all these GREs were imported; that is, they all have a non-empty gre_imp field.Information about what was imported from where, including things bound in this module. Also store Safe Haskell info here about transitive trusted package requirements.There are not many uses of this field, so you can grep for all them.The ImportAvails records information about the following things: 6All of the modules you directly imported (tcRnImports)The orphans (only!) of all imported modules in a GHCi session (runTcInteractive)(The module that instantiated a signature%Each of the signatures that merged inIt is used in the following ways: - imp_orphs is used to determine what orphan modules should be visible in the context (tcVisibleOrphanMods) - imp_finsts is used to determine what family instances should be visible (tcExtendLocalFamInstEnv) - To resolve the meaning of the export list of a module (tcRnExports) - imp_mods is used to compute usage info (mkIfaceTc, deSugar) - imp_trust_own_pkg is used for Safe Haskell in interfaces (mkIfaceTc, as well as in GHC.Driver.Main) - To create the Dependencies field in interface (mkDependencies)What is exportedAnd for annotationsDitto for family instances NB. BangPattern is to fix a leak, see #15111Instance envt for all  home-package modules; Includes the dfuns in tcg_insts NB. BangPattern is to fix a leak, see #15111Global type env for the module we are compiling now. All TyCons and Classes (for this module) end up in here right away, along with their derived constructors, selectors.(Ids defined in this module start in the local envt, though they move to the global envt during zonking)NB: for what "things in this module" means, see Note [The interactive package] in GHC.Runtime.ContextJust for things in this module+All class defaults exported from the module)All class defaults in scope in the module$Top level envt; used during renaming4What kind of module (regular Haskell, hs-boot, hsig)If a signature, the backing module See also Note [Identity versus semantic module]Module being compiled describes the result of running the frontend of a Haskell module. Currently one always gets a , since running the frontend involves typechecking a program. hs-sig merges are not handled here.This data type really should be in GHC.Driver.Env, but it needs to have a TcGblEnv which is only defined here.A  carries the necessary context for performing rewrites (i.e. type family reductions and following filled-in metavariables) in the solver."See Note [Wanteds rewrite Wanteds]At what role are we rewriting? See Note [Rewriter EqRels] in GHC.Tc.Solver.Rewrite"In which context are we rewriting?Type-checking plugins might want to use this location information when emitting new Wanted constraints when rewriting type family applications. This ensures that such Wanted constraints will, when unsolved, give rise to error messages with the correct source location.0Historical "type-checking monad" (now it's just ).+Historical "renaming monad" (now it's just ).A  is a substitution on s that can be used to refine the identities of a hole while we are renaming interfaces (see GHC.Iface.Rename). Specifically, a  for ns_module_name A, defines a mapping from {A.T} (for some  T) to some arbitrary other ."The most intriguing thing about a (, however, is how it's constructed. A  is *implied* by the exported 3s of the implementor of an interface: if an implementor of signature  exports M.T-, you implicitly define a substitution from {H.T} to M.T. So a  is computed from the list of 3s that are exported by the implementation of a module, or successively merged together by the export lists of signatures which are joining together.It's not the most obvious way to go about doing this, but it does seem to work!NB: Can't boot this and put it in NameShape because then we start pulling in too many DynFlags things.no user import listThe import specification as written by the user, including the list of explicitly imported names. Used in ModIface to allow GHCi to reconstruct the top level environment on demand.This is distinct from 3 because we don't want to store the list of explicitly imported names along with each 4We don't want to store the entire GlobalRdrEnv for modules that are imported without explicit export lists, as these may grow to be very large. However, GlobalRdrEnvs which are the result of explicit import lists are typically quite small.Why do we not store something like (Maybe (ImportListInterpretation, [IE GhcPs]) in such a case? Because we don't want to store source syntax including annotations in interface files.,The plugin has not found any contradictions,The first field is for constraints that were solved. The second field contains new work, that should be processed by the constraint solver.The plugin found a contradiction. The returned constraints are removed from the inert set, and recorded as insoluble.7The returned list of constraints should never be empty.Get target platformUnion two ImportAvailsThis function is a key part of Import handling, basically for each import we create a separate ImportAvails structure and then union them all together with this function.;This function provides an escape for direct access to the TcM: monad. It should not be used lightly, and the provided  API should be favoured instead. Check the  for consistency. Currently, only checks axioms, but should check other aspects, too.Rewriter environmentGivenstype family argumentsGivensWantedsXXߗXXXXXXXXX̍ЍҍӍэ΍ύ͍܍ݍߍލԍՍٍ֍؍׍ۍڍ‡‡ԍՍٍ֍؍׍ۍڍXXXXXXXXXЍҍӍэ͍̍΍ύXX܍ݍߍލߗ   <  &  %  (  '  !  ) +0 2;   None&'6-*Setup the initial typechecking environmentRun a & action in the context of an existing GblEnv.Do it flag is trueUpdate the external package state. Returns the second result of the modifier function.This is an atomic operation and forces evaluation of the modified EPS in order to avoid space leaks."Update the external package state.This is an atomic operation and forces evaluation of the modified EPS in order to avoid space leaks."A convenient wrapper for taking a MaybeErr SDoc a. and throwing an exception if it is an error.ے3Trace when a certain flag is enabled. This is like  but accepts a string as a label and formats the trace message uniformly.Dump if the given   is set.&Unconditionally dump some trace outputCertain tests (T3017, Roles3, T12763 etc.) expect part of the output generated by `-ddump-types` to be in  style. However, generally we want all other debugging output to use  style. We  style if  useUserStyle is True.ܒAdd current location if -dppr-debug (otherwise the full location is usually way too much)*Like logInfoTcRn, but for user consumption?Mark the inner computation as being done inside generated code.+See Note [Error contexts in generated code]Add a fixed message to the error context. This message should not do any tidying.Add a message to the error context. This message may do tidying.Add a fixed landmark message to the error context. A landmark message is always sure to be reported, even if there is a lot of context. It also doesn't count toward the maximum number of contexts reported. Variant of 1 that allows for monadic operations and tidying.tcCollectingUsage thing_inside runs  thing_inside and returns the usage information which was collected as part of the execution of  thing_inside . Careful: tcCollectingUsage thing_inside itself does not report any usage information, it's up to the caller to incorporate the returned usage information into the larger context appropriately. tcScalingUsage mult thing_inside runs  thing_inside* and scales all the usage information by mult.Drop elements of the input that fail, so the result list can be shorter than the argument listApply the function to all elements on the input list If all succeed, return the list of results Otherwise fail, propagating all errors2The accumulator is not updated if the action fails(Display a warning if a condition is met.(Display a warning if a condition is met.+Display a diagnostic if a condition is met.,Display a diagnostic in the current context.(Display a diagnostic in a given context.A variation of $ that takes a function to produce a  TcRnDsMessage5 given some additional context about the diagnostic.Display a diagnostic for the current source location, taken from the  monad.1Display a diagnostic for a given source location.ݒDisplay a diagnostic, with an optional flag, for the current source location.Creates an EvBindsVar incapable of holding any bindings. It still tracks covar usages (see comments on ebv_tcvs in GHC.Tc.Types.Evidence!), thus must be made monadically5Throw out any constraints emitted by the thing_insideThe name says it all. The returned TcLevel is the *inner* TcLevel.Adds the given modFinalizers to the global environment and set them to use the current local environment.Mark that safe inference has failed See Note [Safe Haskell Overlapping Instances Implementation] although this is used for more than just that failure case..Figure out the final correct safe haskell mode9Switch instances to safe instances if we're in Safe mode.Run an = (top-level interface monad) computation inside an existing ; (typecheck-renaming monad) computation by initializing an  based on .? can be used when there's no chance that the action will call typecheckIface% when inside a module loop and hence  tcIfaceGlobal.'This is used when we are doing to call typecheckModule on an ModIface, if it's part of a loop with some other modules then we need to use their IORef TypeEnv vars when typechecking but crucially not our own..Initialize interface typechecking, but with a ' to apply when typechecking top-level s (see lookupIfaceTop)Run thing_inside in an interleaved thread. It shares everything with the parent thread, so this is DANGEROUS.+It throws an error if the computation failsIt's used for lazily type-checking interface signatures, which is pretty benign.&See Note [Masking exceptions in forkM]]:B. We need a *specific* ModIface, e.g. p[A=q():A]:B (or maybe even p[A=]:B) which we load up (either to merge it, or to just use during typechecking).Suppose we have:p[A=]:M ==> p[A=q():A]:MSubstitute all occurrences of with q():A (renameHoleModule). Then, for any Name of form {A.T}, replace the Name with the Name according to the exports of the implementing module. This works even for p[A=]:M, since we just read in the exports of B.hi, which is assumed to be ready now. This function takes an optional , which can be used to further refine the identities in this interface: suppose we read a declaration for {H.T} but we actually know that this should be Foo.T; then we'll also rename this (this is used when loading an interface to merge it into a requirement.)Rename just the exports of a ʑ?. Useful when we're doing shaping prior to signature merging.Run a computation in the  monad.The key function. This gets called on every Name embedded inside a ModIface. Our job is to take a Name from some generalized unit ID p[A=, B=], and change it to the correct name for a (partially) instantiated unit ID, e.g. p[A=q[]:A, B=].%There are two important things to do:If a hole is substituted with a real module implementation, we need to look at that actual implementation to determine what the true identity of this name should be. We'll do this by loading that module's interface and looking at the mi_exports.However, there is one special exception: when we are loading the interface of a requirement. In this case, we may not have the "implementing" interface, because we are reading this interface precisely to "merge it in".External case: p[A=]:A (and thisUnitId is something else) We are loading this in order to determine B.hi! So don't load B.hi to find the exports.Local case: p[A=]:A (and thisUnitId is p[A=]) This should not happen, because the rename is not necessary in this case, but if it does we shouldn't load A.hi!Compare me with  tcIfaceGlobal!Rename an implicit name, e.g., a DFun or coercion axiom. Here is where we ensure that DFuns have the correct module as described in Note [rnIfaceNeverExported]. Rename an s?, with special handling for an associated dictionary function.None NoneG7A HoleFitPlugin is a pair of candidate and fit plugins.HoleFitPluginR adds a TcRef to hole fit plugins so that plugins can track internal state. Note the existential quantification, ensuring that the state cannot be modified from outside the plugin.7Cleanup of state, guaranteed to be called even on error'The function defining the plugin itself0Initializes the TcRef to be passed to the plugin=A plugin for modifying hole fits *after* they've been found.A plugin for modifying the candidate hole fits *before* they're checked.  NoneNone ) Extract docs from renamer output. This is monadic since we need to be able to read documentation added from Template Haskell's putDoc, which is stored in .If we have an explicit export list, we extract the documentation structure from that. Otherwise we use the renamed exports and declarations.Figure out the documentation structure by correlating the module exports with the located declarations.Extract named documentation chunks from the renamed declarations.If there is no explicit export list, we simply return an empty map since there would be no way to link to a named chunk.Create decl and arg doc-maps by looping through the declarations. For each declaration, find its names, its subordinates, and its doc strings.The "OccEnv Name" is the default method environment for this module Ultimately, the a special "defaultMethodOcc" name is used for the signatures on bindings for default methods. Unfortunately, this name isn't generated until typechecking, so it is not in the renamed AST. We have to look it up from the ) parameter constructed from the typechecked AST. See also Note [default method Name] in GHC.Iface.RecompGet all subordinate declarations inside a declaration, and their docs. A subordinate declaration is something like the associate type or data family of a type class.Extract constructor argument docs from inside constructor decls.All the sub declarations of a class (that we handle), ordered by source location, with documentation attached if it exists.;Extract function argument docs from inside top-level decls.1Extract function argument docs from inside types.1Extract function argument docs from inside types.The top-level declarations of a module that we care about, ordered by source location, with documentation attached if it exists.Take all declarations except pragmas, infix decls, rules from an :.7Collect docs and attach them to the right declarations.;A declaration may have multiple doc strings attached to it.This is an example.7Filter out declarations that we don't handle in HaddockGo through all class declarations and filter their sub-declarations%Was this signature given by the user?Take a field of declarations from a data structure and create HsDecls using the given constructorExtracts out individual maps of documentation added via Template Haskell's putDoc.Unions together two  ArgDocMaps (or ArgMaps in haddock-api), such that two maps with values for the same key merge the inner map as well. Left biased so unionArgMaps a b prefers a over b.  Module headerDocs on top level declarationsDocs on argumentsThe current moduleImportsExplicit export list All exportsDefault MethodsThe current moduleExplicit export listThe default method environmentAll exports, unordered#Do we have an explicit export list?Default method environment for this module. See Note [default method Name] in GHC.Iface.RecompThe default method environmentNone'G is the compiler plugin data type. Try to avoid constructing one of these directly, and just modify some fields of  instead: this is to try and preserve source-code compatibility when we add fields to this.Nonetheless, this API is preliminary and highly likely to change in the future.A static plugin with its arguments. For registering compiled-in plugins through the GHC API.>A plugin with its arguments. The result of loading the plugin.The object files required by the loaded plugins See Note [Plugin dependencies]Plugins dynamically loaded after processing arguments. What will be loaded here is directed by DynFlags.pluginModNames. Arguments are loaded from DynFlags.pluginModNameOpts.The purpose of this field is to cache the plugins so they don't have to be loaded each time they are needed. See  .External plugins loaded directly from libraries without loading module interfaces.Static plugins which do not need dynamic loading. These plugins are intended to be added by GHC API users directly to this list.;To add dynamically loaded plugins through the GHC API see addPluginModuleName instead.has this plugin been initialised (i.e. driverPlugin has been run)9the actual plugin together with its commandline argumentsExternal plugin loaded directly from a library without loading module interfaces Module nameUnitIdPlugin with its arguments the module containing the plugin9the actual plugin together with its commandline arguments%command line arguments for the pluginthe actual callable plugin>Modify an interface that have been loaded. This is called by GHC.Iface.Load when an interface is successfully loaded. Not applied to the loading of the plugin interface. Tools that rely on information from modules other than the currently compiled one should implement this function.4Modify the TH splice or quasiqoute before it is run.Modify the module when it is type checked. This is called at the very end of typechecking.Modify each group after it is renamed. This is called after each : has been renamed.8Modify the module when it is parsed. This is called by GHC.Driver.Main when the parser has produced no or only non-fatal errors. Compilation will fail if the messages produced by this function contain any errors.3Specify how the plugin should affect recompilation.ghc A plugin that runs after interface creation and after late cost centre insertion. Useful for transformations that should not impact interfaces or optimization at all.ghc An optional plugin to update , right after plugin loading. This can be used to register hooks or tweak any field of DynFlags' before doing actual work on a module.An optional plugin to handle hole fits, which may re-order or change the list of valid hole fits and refinement hole fits.An optional defaulting plugin, which may specify the additional type-defaulting rules.An optional typechecker plugin, which may modify the behaviour of the constraint solver.Modify the Core pipeline that will be used for compilation. This is called as the Core pipeline is built for every module being compiled, and plugins get the opportunity to modify the pipeline in a nondeterministic order.2Result of running the parser and the parser pluginWarnings and errors from parser, potentially modified by a plugin/Parsed module, potentially modified by a plugin*Errors and warnings produced by the parserCommand line options gathered from the -PModule.Name:stuff syntax are given to you as this typeDefault plugin: does nothing at all, except for marking that safe inference has failed unless -fplugin-trustworthy is passed. For compatibility reason you should base all your plugin definitions on this default value.A renamer plugin which mades the renamed source available in a typechecker plugin.9Perform an operation by using all of the plugins in turn.Perform a constant operation by using all of the plugins in turn.Load external pluginsHGGH     #  $None+E8A wrapper around the interpretation function for phases.None  Hooks can be used by GHC API clients to replace parts of the compiler pipeline. If a hook is not installed, GHC uses the default built-in behaviourActual type: Maybe ([LForeignDecl GhcTc] -> DsM (ForeignStubs, OrdList (Id, CoreExpr)))None Desugaring monad. See also TcM.>Local state of the desugarer, extended as we lexically descendSee Note [Desugaring non-canonical evidence]: this field collects all un-specialisable evidence variables in scope.(See Note [Long-distance information] in GHC.HsToCore.Pmc. The set of reaching values Nablas is augmented as we walk inwards, refined through each pattern match in turn%To put in pattern-matching error msgsTemplate Haskell bindingsGlobal read-only context and state of the desugarer. The statefulness is implemented through s.2See Note [Generating fresh names for FFI wrappers] !NoneNoneNone2#The source of the linted expressionNoneNoneLook up the address of a Haskell symbol in the currently loaded units.6See Note [Looking up symbols in the relevant objects].NoneThis list is used to ensure that when you say "Prelude.map" in your source code, or in an interface file, you get a Name with the correct known key (See Note [Known-key names] in GHC.Builtin.Names).Check the known-key names list of consistency.Given a  lookup its associated ) if it corresponds to a known-key thing.Is a  known-key?Maps s to known-key names. The type is UniqFM Name Name to denote that the s used in the domain are s associated with *s (as opposed to some other namespace of s).Given a  lookup any associated arbitrary SDoc's to be displayed by GHCi's ':info' command.NoneNone Generate Cmm code for a tick. Depending on the type of Tickish, this will either generate actual Cmm instrumentation code, or simply pass on the annotation as a  CmmTickish.NoneNoneGenerate a source note spanning from "a" to "b" (inclusive), then proceed with parsing. This allows debugging tools to reason about locations in Cmm code.addressvalueNone3None#7Entity information  is a simplified version of  and richer version than  Namespace in ,. It state the kind of the entity, such as Variable,  TypeVariable, DataConstructor, etc..'s get converted into 's before being written into .hie files. See  and  fromHieName6 for logic on how to convert between these two types.Scope of a type variable.%This warrants a data type apart from 6 because of complexities introduced by features like -XScopedTypeVariables and -XInstanceSigs. For example, consider: "foo, bar, baz :: forall a. a -> a Here a' is in scope in all the definitions of foo, bar, and baz, so we need a list of scopes to keep track of this. Furthermore, this list cannot be computed until we resolve the binding sites of foo, bar, and baz.Consequently, a starts with an  [foo, bar, baz] Nothing# which later gets resolved into a .4Unresolved scopes should never show up in the final .hie filetype or data family type synonymdata declarationconstructor declarationpattern synonymclass declarationinstance declarationTypes of imports and exportsEq/Ord instances compare on the converted HieName, as non-exported names may have different uniques after a roundtripbound by a pattern matchbound by a type signaturebound by a hswrapperbound by an implicit variable%Bound by some instance of given classA direct let binding0Different contexts under which identifiers existregular variable import/export Value bindingPattern bindingThis case is tricky because the bound identifier can be used in two distinct scopes. Consider the following example (with -XViewPatterns) 'do (b, a, (a -> True)) <- bar foo a The identifier a% has two scopes: in the view pattern  (a -> True) and in the rest of the do -block in foo a. Declaration Type variable Record field/Constraint/Dictionary evidence variable bindingUsage of evidence variable,Information associated with every identifierWe need to include types with identifiers because sometimes multiple identifiers occur in the same span(Overloaded Record Fields and so on)'The information stored in one AST node.The type parameter exists to provide flexibility in representation of types (see Note [Efficient serialization of redundant type info]).%All the identifiers and their details'The Haskell types of this node, if any. AnnotationsA node annotationname of the AST node Type name of the AST node constructorSource of node infoNodeInfos grouped by source/Mapping from filepaths to the corresponding ASTA list of type arguments along with their respective visibilities (ie. is this an argument that would return M for isVisibleForAllTyFlag?).(Roughly isomorphic to the original core .A flattened version of .9See Note [Efficient serialization of redundant type info]type with constraint: t1 => t2 (see  IfaceDFunTy)GHC builds up a wealth of information about Haskell source as it compiles it. .hie files are a way of persisting some of this information to disk so that external tools that need to work with haskell source don't need to parse, typecheck, and rename all over again. These files contain:a simplified AST3nodes are annotated with source positions and types0identifiers are annotated with scope information+the raw bytes of the initial Haskell source#Besides saving compilation cycles, .hie; files also offer a more stable interface than the GHC API.Entity information for each  in the 'Raw bytes of the initial Haskell source"The names that this module exports$Type-annotated abstract syntax treesTypes referenced in the .9See Note [Efficient serialization of redundant type info]The module this HIE file is for Initial Haskell source file pathCurrent version of .hie filesGet the  for an Get the  for a 3names of the definitions over which the scope spansthe location of the instance/class declaration for the case where the type variable is declared in a method type signature,whether or not the binding is in an instance#scope over which the value is boundspan of entire bindingscope in the pattern9 (the variable bound can be used further in the pattern)%rest of the scope outside the patternspan of entire bindingtype of declarationspan of entire binding!how did this bind come into being#scope over which the value is boundspan of the binding site  $  $        #                      $                       .  &  )  :  1  %  8  ,  /  #  0  $                       +  " $/     +  " $/   $ &1                                  "- /1     + -/None#)>One must contain the other. Leaf nodes cannot contain anything/Insert an AST in a sorted list of disjoint AstsMerge two nodes together.,Precondition and postcondition: elements in  are ordered.Merge two sorted, disjoint lists of ASTs, combining when necessary.1In the absence of position-altering pragmas (ex: # line "file.hs" 3), different nodes in an AST tree should either have disjoint spans (in which case you can say for sure which one comes first) or one span should be completely contained in the other (in which case the contained span corresponds to some child node).>However, since Haskell does have position-altering pragmas it is possible for spans to be overlapping. Here is an example of a source file in which foozball and quuuuuux have overlapping spans: module Baz where # line 3 "Baz.hs" foozball :: Int foozball = 0 # line 3 "Baz.hs" bar, quuuuuux :: Int bar = 1 quuuuuux = 2 8In these cases, we just do our best to produce sensible 's. The blame should be laid at the feet of whoever wrote the line pragmas in the first place (usually the C preprocessor...).*combines and sorts ASTs using a merge sorthelps fill in  (with ))return an empty list if this is unhelpfulhelps fill in  (with ))return an empty list if this is unhelpfulhelps fill in  (with ))return an empty list if this is unhelpfultype to associate with the nodehelps fill in  (with ))return an empty list if this is unhelpfultype to associate with the node 7 '  None#wLook for any identifiers which occur outside of their supposed scopes. Returns a list of error messages.  None z'The compression/deduplication level of ʑ files.A ʑ contains many duplicated symbols and names. To keep interface files small, we deduplicate them during serialisation. It is impossible to write an interface file with *no* compression/deduplication.We support different levels of compression/deduplication, with different trade-offs for run-time performance and memory usage. If you don't have any specific requirements, then  is a good default.Perform the normal compression operations, such as deduplicating s and  sPerform some extra compression steps that have minimal impact on the run-time of ghc.This reduces the size of '.hi' files significantly in some cases and reduces overall memory usage in certain scenarios.$Try to compress as much as possible.Yields the smallest '.hi' files but at the cost of additional run-time.Read an interface file header, checking the magic number, version, and way. Returns the hash of the source file and a BinHandle which points at the start of the rest of the interface file data.Read an interface file.See Note [Deduplication during iface binary serialisation] for details.This performs a get action after reading the dictionary and symbol table. It is necessary to run this before trying to deserialise any Names or FastStrings.?Setup a BinHandle to read something written using putWithTablesReading names has the side effect of adding them into the given NameCache.Write an interface file.See Note [Deduplication during iface binary serialisation] for details. Puts the ʑ to the .!This avoids serialisation of the ʑ if the fields  contains a L/ value. This field is populated by reading the ʑ using , and not modifying it in any way afterwards.(Put a piece of data with an initialised UserData field. This is necessary if you want to serialise Names or FastStrings. It also writes a symbol table and the dictionary. This segment should be read using . Write namesymbolifacetype tables #setup the given BinHandle with Name FastStringIfaceType table handlingwrite the following - FastString table pointer - Name table pointer - IfaceType table pointer - payload - IfaceType table - Name table - FastString tableIt returns (number of names, number of FastStrings, number of IfaceTypes, payload write result)See Note [Order of deduplication tables during iface binary serialisation]Write all deduplication tables to disk after serialising the main payload.Writes forward pointers to the deduplication tables before writing the payload to allow deserialisation *before* the payload is read again.:Initial ram buffer to allocate for writing interface files %    # %) None ),B=]:B, although the free holes are A and B, B might not depend on A at all!If this is invoked on a signature, this does NOT include the signature itself; e.g. precise free module holes of p[A=,B=]:B never includes B.>Check if we need to try the dynamic interface for -dynamic-tooWrite interface file readIface tries just the one file.Failed err  => file not found, or unreadable, or illegible Succeeded iface  = successfully found and parsed'Read binary interface, and print it outShow a ModIface but don't display details; suitable for ModIfaces stored in the EPT.Show a ModIface+The UnitState is used to pretty-print units/Reason for loading the iface (used for tracing)=The unique identifier of the on-disk module we're looking forThe *actual* module we're looking for. We use this to check the consistency of the requirements of the module we read out. Looking for .hi-boot or .hi file! None Make a name for the dict fun for an instance decl. It's an *external* name, like other top-level names, and hence must be made with newGlobalBinder. mkWrapperName ref what nameBase7See Note [Generating fresh names for FFI wrappers] for ref 's purpose.ԍՍٍ֍؍׍ۍڍddddddddԍՍٍ֍؍׍ۍڍ  5  ,None+ Zonking monad for a computation that zonks to Type, reading from and extending or modifying a .See Note [Zonking to Type].Zonking monad for a computation that zonks to Type, reading from a $ but not extending or modifying it.See Note [Zonking to Type].4Confused by zonking? See Note [What is zonking?] in GHC.Tc.Zonk.Type.Is a coercion hole filled in?Retrieve the contents of a coercion hole. Panics if the hole is unfilled9Retrieve the contents of a coercion hole, if it is filledCheck whether any coercion hole in a RewriterSet is still unsolved. Does this by recursively looking through filled coercion holes until one is found that is not yet filled in, at which point this aborts.6ɩΩ̩ϩͩ˩ʩȩǩЩũé©ĩƩ  +  .None#tcCheckUsage name mult thing_inside runs  thing_inside, checks that the usage of name is a submultiplicity of mult, and removes name from the usage environment. See also Note [Coercions returned from tcSubMult] in GHC.Tc.Utils.Unify, which applies to the wrapper returned from this function..Create a new Wanted constraint with the given ..Create a new Wanted constraint with the given +, and location information taken from the  environment.-Create new Wanted constraints with the given +, and location information taken from the  environment.Emits a new Wanted. Deals with both equalities and non-equalities.Emits a new equality constraintCreates a new EvVar and immediately emits it as a Wanted. No equality predicates here.!Emit a new wanted expression hole Create a new  with as many sensible defaults for its fields as possible. Note that the , , and  fields do not have sensible defaults, so they are initialized with lazy thunks that will  if forced, so one should take care to initialize these fields after creation.This is monadic to look up the , which is used to initialize , and to set the -Winaccessible-code flag. See Note [Avoid -Winaccessible-code when deriving] in GHC.Tc.TyCl.Instance.Put a value in a coercion holeExtract a type out of an ExpType, if one exists. But one should always exist. Unless you're quite sure you know what you're doing.,Same as readExpType, but for Scaled ExpTypes4Extract a type out of an ExpType. Otherwise, panics.Extracts the expected type if there is one, or generates a new TauTv if there isn't.?Infer a type using a fresh ExpType See also Note [ExpType] in GHC.Tc.Utils.TcMTypeUse  if you require the type to have a fixed runtime representation.Like , except it ensures that the resulting type has a syntactically fixed RuntimeRep as per Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.Create a new metavariable, of the given kind, which can only be unified with a concrete type.Invariant: the kind must be concrete, as per Note [ConcreteTv]. This is checked with an assertion..Create a new flexi ty var with a specific name?Create a tyvar that can be a lifted or unlifted type. Returns alpha :: TYPE kappa , where both alpha and kappa are fresh.Note: you should use  if you also need to ensure that the representation is concrete, in the sense of Note [Concrete types] in GHC.Tc.Utils.Concrete.Like , but ensures the type variable has a syntactically fixed RuntimeRep in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.See .Like ", but for concrete type variables.Extract out the kind vars (in order) and type vars (in order) from a . The lists are guaranteed to be distinct. Keeping the lists separate is important only in the -XNoPolyKinds case.Gathers free variables to use as quantification candidates (in ). This might output the same var in both sets, if it's used in both a type and a kind. The variables to quantify must have a TcLevel strictly greater than the ambient level. (See Wrinkle in Note [Naughty quantification candidates]) See Note [CandidatesQTvs determinism and order] See Note [Dependent type variables]Like , but over a list of types The variables to quantify must have a TcLevel strictly greater than the ambient level. (See Wrinkle in Note [Naughty quantification candidates])Like , but consider every free variable to be dependent. This is appropriate when generalizing a *kind*, instead of a type. (That way, -XNoPolyKinds will default the variables to Type.)Internal function to check whether the given type has a fixed  RuntimeRep.Use  to allow rewriting, or  to perform a syntactic check.Ensure that the given type ty can unify with a concrete type, in the sense of Note [Concrete types].Returns a coercion co :: ty ~# conc_ty, where conc_ty is concrete.If the type is already syntactically concrete, this immediately returns a reflexive coercion. Otherwise, it creates a new concrete metavariable  concrete_tv# and emits an equality constraint ty ~# concrete_tv*, to be handled by the constraint solver.:Invariant: the kind of the supplied type must be concrete.We assume the provided type is already at the kind-level (this only matters for error messages).'Ensure that the given type is concrete.This is an eager syntactic check, and never defers any work to the constraint solver.Invariant: the kind of the supplied type must be concrete. Invariant: the output type is equal to the input type, up to zonking.We assume the provided type is already at the kind-level (this only matters for error messages).Try to turn the provided type into a concrete type, by ensuring unfilled metavariables are appropriately marked as concrete.Returns a zonked type which is "as concrete as possible", and a list of problems encountered when trying to make it concrete.INVARIANT: the returned type is equal to the input type, up to zonking. INVARIANT: if this function returns an empty list of NotConcreteReasons, then the returned type is concrete, in the sense of Note [Concrete types].Which type variables of this $ must be concrete when instantiated?9See Note [Representation-polymorphism checking built-ins]Context to be reported to the user if the type ends up not having a fixed  RuntimeRep.-The type to check (we only look at its kind). (co, ty') where  ty' :: ki', ki is concrete, and co :: ty ~# ty' . That is, ty' has a syntactically fixed RuntimeRep in the sense of Note [Fixed RuntimeRep].Context to be reported to the user if the type does not have a syntactically fixed  RuntimeRep.-The type to check (we only look at its kind).!The check to perform on the kind.#The context which required a fixed  RuntimeRep1, e.g. an application, a lambda abstraction, ... The type ty4 to check (the check itself only looks at its kind).Returns  (co, frr_ty) with co :: ty ~# frr_ty and frr_ty has a fixed  RuntimeRep.None& Used when  is the wired-in name for a wired-in class method, so the caller knows its type for sure, which should be of form forall a. C a =>  is supposed to instantiate just the outer type variable and constraintGiven ty::forall k1 k2. k, instantiate all the invisible forall-binders returning ty kk1  kk2 :: k[kk1k1, kk2k1] Called only to instantiate kinds, in user-written type signaturesGiven a list of [], skolemize the type variables, returning a substitution mapping the original tyvars to the skolems, and the list of newly bound skolems.Give fresh uniques to a bunch of TyVars, but they stay as TyVars, rather than becoming TcTyVars Used in  , and  Give fresh uniques to a bunch of CoVars Used in "GHC.Tc.Instance.Family.newFamInst"Check that the result type of an expression has a fixed runtime representation.'Used only for arrow operations such as arr, first, etc.why do we need this?name of the method)types with which to instantiate the classconcreteness information%How to instantiate the type variablesType to instantiate1Result (type vars, preds (incl equalities), rho)Type to instantiate it at(Standard name, user name)(Standard name, suitable expression) USED ONLY FOR CmdTop (sigh) *** See Note [CmdSyntaxTable] in  GHC.Hs.Expr&&None&' ( What to do when encountering a type-family application while processing a type equality in the pure unifier.7See Note [Family applications in canonical constraints]Options describing how to deal with a type equality in the pure unifier. See  looks for just one function arrow, returning an uninstantiated sigma-type.Invariant: the returned argument type has a syntactically fixed RuntimeRep in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.4See Note [Return arguments with a fixed RuntimeRep].Like , but used when you have an "actual" type, for example in function application.INVARIANT: the returned argument types all have a syntactically fixed RuntimeRep in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete. See Note [Return arguments with a fixed RuntimeRep].The wrapper has type: spec_ty ~> expected_ty See Note [Skolemisation] for the differences between tcSkolemiseCompleteSig and tcTopSkolemiseUse this function to split off arguments types when you have an "expected" type.*This function skolemises at each polytype.Invariant: this function only applies the provided function to a list of argument types which all have a syntactically fixed RuntimeRep in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete. See Note [Return arguments with a fixed RuntimeRep].Fill an f with the given type.If !co = fillInferResult t1 infer_res, then co :: t1 ~# t2 , where t2 is the type stored in the f field of  infer_res.0This function enforces the following invariants:%Level invariant. The stored type t2* is at the same level as given by the f field. FRR invariant. Whenever the f field is not Nothing, t2 is guaranteed to have a syntactically fixed RuntimeRep, in the sense of Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete.-Breaks apart a function kind into its pieces.checkTopShape checks (TYVAR-TV) Note [Unification preconditions]; returns True if these conditions are satisfied. But see the Note for other preconditions, too.'If present, the thing that has type ty1)See Note [Herald for matchExpectedFunTys]The thing with type TcSigmaTypeTotal number of value args in the call, and the original function type (Both are used only for error messages)Type to analyse: a TcRhoType)See Note [Herald for matchExpectedFunTys]ActualExpectedUsed when instantiatingUsed when skolemisingThe expression that has type actual (if known) Actual type Expected typetype, only for errorsn: number of desired arrowsfun_kind-co :: fun_kind ~ (arg1 -> ... -> argn -> res)  (    "         #  "None &'&A monad within which we will generate KindRep+s. Here we keep an environment containing KindReps which we've already generated so we can re-use them opportunistically.Maps kinds to KindRep bindings. This binding may either be defined in some other module (in which case the Maybe (LHsExpr Id will be K) or a binding which we generated in the current module (in which case it will be L the RHS of the binding). To construct TrName,s The various TyCon and DataCons of KindRepof TyConTarget platform A group of s in need of type-rep bindings.Build exported KindRep% bindings for the given set of kinds.The s in need of bindings kindsModule name fingerprintPackage name fingerprintModule's typerep bindingInformation we need about a / to generate its representation. We carry the 4 in order to share it between the generation of the TyCon and KindRep bindings.Generate the Typeable bindings for a module. This is the only entry-point of this module and is invoked by the typechecker driver in  tcRnSrcDecls.&See Note [Grand plan for Typeable] in GHC.Tc.Instance.Typeable.6Generate TyCon bindings for a set of type constructors [a] -> a sumNumList [] = 0 sumNumList (x : xs) = x + sumList xsand add a breakpoint to it:ghci> break sumNumList ghci> sumNumList ([0 .. 9] :: [Int])+ghci shows us more precise types than just as:Stopped in Main.sumNumList, debugger.hs:3:23-39 _result :: Int = _ x :: Int = 0 xs :: [Int] = _&How many times to recurse for subterms Force thunks!Type of the object to reconstructObject to reconstruct‚&How many times to recurse for subtermsType to refine Refine the type using this value ‚ ‚ÂĂ NonedAttempt to convert a Template Haskell name to one that GHC can understand. Original TH names such as those you get when you use the 'foo syntax will be translated to their equivalent GHC name exactly. Qualified or unqualified TH names will be dynamically bound to names in the module being compiled, if possible. Exact TH names will be bound to the name they represent, exactly.Attempt to convert a Template Haskell name to one that GHC can understand. Original TH names such as those you get when you use the 'foo syntax will be translated to their equivalent GHC name exactly. Qualified or unqualified TH names will be dynamically bound to names in the module being compiled, if possible. Exact TH names will be bound to the name they represent, exactly.1One must be careful to consistently use the same ٣> to create identifier that might be compared. (C.f. how the   . Monad enforces that variables from separate   invocations are never intermingled; it would be valid to use the same tricks for s and ٣s.)For now, the easiest and recommended way to ensure a consistent ٣< is used it to retrieve the preexisting one from an active  . A single  is created per GHC "session", and this ensures everything in that session will get the same name cache.+@B)ee(eede)e((ee(e(eee)edeee)deee)e)e))eeeeeeddeeeefe))eeeee)d()()()()ee)eedefeeeee(eeeeeeeeeee))))))e))))eeeee((ee)eeeeeeeeeedd(((effff(ffeeeeee((eeeeeeeefeeeeeeeee())eee(e(eee(()(()eee(eeeee))e)e))e))e(e)))))))))d()()))e()eee)eee))eOOOOOOO``````_```````````````````````````_``_````````_````````````_```````````````````````````````_````_````````````[ZZZZZZZZZKZKK[[KK[K[ZZKZ[[[Z[[[KZZ[[[[KZZ[KZZZKZ[[[[[[[[[[[[ZKZZZZKZ[KZKZZZKKKZ[ZKZZZZZZZKKKZK[KK[ZZ[[KKZ[ZKZK[KZKZZZKZZZKZZZZZZZK[ZZZZZZZZ[[[[ZK[ZZZZZ[[\]]\]\\((\\(\\\\(\\\(\\\\\\\\\](\(\\\(\\((]((\\\\\\\\\]\\\\\\\((\\\\\(]]oooooooooooooooooooopoooooooooooooooooooooorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqQQQPPPPPP/QQQQQQQQPQP/PQPQQZNNNNNNNNNNNNNNNNNNNNNNQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRQQRQQRRRRRRRRQQMMMMMMMMMMMMMMMMMMMLMMMMLLMMMMMLLMMMMMMMMMMMMMMMMLLLLLLLLLLLLLMLLLLLLMLMMMMMMLMLLLLLLLLLLMMMMMMMMMLLMMMMMMMMMLMMLMMLMMMMMMLMMLRRRRS.SR.RSSRSRRRRRRRR.RSR.RSSSRSR.RSSSSSSRRRRR.RRR.SRS.RRSR.SS.RRSSSSRSSSRRSRSRRRRSRRSS.RSSS.R.SRRRRSRRRRSSSRRRR.RRR.R.RRRRS.RSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRR.RSSRRRRRRRSRR.RRSSS.SSS.SRpqppqqqpppqqqqqqqqqqqqqqqqqqqpqqpppqqqpqqqpqppppppqppppqpppppqppqqpppppppq !!!!!!!!+IIIJIIIIIJIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJIIDDDDDDD''''&''&'&&&''''&&&'&&&&&&&'''''''''''''''''&'&''''&''&&&'&'&''''&&'''&&''&'''&&'&&&&&&''&&'''&&&''''&'&'&&'&&'&''3cccccddccdcccdcccccdddcccdcdddcdccccccdccccccccccccccccccccccccccccccccccccccccccccdccccccccdccccccdcdddccccdddddcdcddcdddcddbbbccbbcbcccbcccbbbccbbbcccbbbbbcbbbcbccccccccYYYYYYYYYYYYYYYYYYYYYXXXXXXXYYYYYYYXYYYYYYYYYYYYXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYY,,,,++++++++++++++++,+++,+,,,,,+++++++++++,,,,,,,,,,,,+,,,,,,,,,,-,,--,,,,,,,,-,,,,,,,,,,,,--,,,,,,,,**))***)))*)**))***)*****)*****)**)*))***)*)*))))**)******))*****))***************))))*))*****))*)))*)))**))*)))*)))*)**))**)**)*)44454444444444444444444444444444444444554444454444444444444444444444444444444444444454444454544444445,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---------------..-..---...-..-..------------------.-----.---------------------------0/0//0////00/////0///0///000////////0/0///0/0/////0/0/0/0//////00000//0000/////0//////////////////0//0/0......./................................................./.......%%$$$$$$$$$$$$$$%%$$%%$JJJJJJJJJJJJJ$$$$$$$$$$#$$##$#$$$##$$######$$#$$$##$$####$$$#####$#$$##$$#$########̑##"####"###""""""""#"""####""####"##"##                    %ddddddd_____________________________________________________________________________________________________________________ZZZZZZZZ(\(\\\\\\\(\\\\\\\\\ooooorrrrrrrENNNMNNNNNNNNNNNNNNNMMMMMMMQQQQQLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLRRRRRRRRp ƄDŽʄ˄ڄل؄ׄքՄɅۄބ̄Å݅΅ׅDžԄօ…ͅ΄݄ȅąŅƅ߅τӄ҄фЅӅՅۅхԅ؅߄҅Єڅ܅υ˅ʅ̅܄م̈́ޅńÄĄȄɄ„ !!!!!!!!!!! ! ! ! ! ! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!                                   !!!!!!HGtt+++++++IIIIIIIIIIIIIIIIIIIaDDDDDDDDDD%%%%%%&&&&&&&%%%%&%%%%%%&&&&&&&&&&&&&&%%%%%%%%%%%%%&&&%&&&&&&&%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&%&&&&&&%%%&%%%&&&%%%&&&&&&&%%%%%%%%%%%%%%%%%%%%%&&&%%%%%&ҁЁ33333333333333bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbXXXXXXXXXXXXXXXXXXXXX+++,,))))))4444444444444444433333333333333333433333344444444444444434343333,,,,,,,,,%%%%%%%----------------------------------------////////////..........$$$$JJJJJJJJ$$$$####################ʑ‘ǑőɑȑƑÑđ֑בڑБґؑݑԑّߑϑܑ͑ޑΑۑёӑՑˑنچ܆ۆކ݆ֆ؆׆ц҆ӆԆՆ߆""""""""""""""""""""""""""""""""""""/ %%%d **))***)))*)**))***)*****)*****)**)*))***)*)*))))**)******))*****))***************))))*))*****))*)))*)))**))*)))*)))*)**))**)**)*))))))),,,,++++++++++++++++,+++,+,,,,,+++++++++++,,,,,,,,,,,,+**))***)))*)**))***)*****)*****)**)*))***)*)*))))**)******))*****))***************))))*))*****))*)))*)))**))*)))*)))*)**))**)**)*)+++))))))cccccddccdcccdcccccdddcccdcdddcdccccccdccccccccccccccccccccccccccccccccccccccccccccdccccccccdccccccdcdddccccdddddcdcddcdddcdd---.....---_-----qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqQQQQQQQQQQQQQQQQQQQ/))OQQPPPPP/QQQQQQ/PQPQQNNNNNNNNNNNNNNNNNNNQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRQQRRRRRRRRQQLRRRRS.SR.RSSRSRRRRRRRR.RSR.RSSSRSR.RSSSSSSRRRRR.RRR.SRS.RRSR.SS.RRSSSSRSSSRRSRSRRRRSRRSS.RSSS.R.SRRRRSRRRRSSSRRRR.RRR.R.RRRRS.RSSSSRRRRRRRRRRRRRRRRRRRRRRRRRRR.RSSRRRRRRRSRR.RRSSS.SSS.SR---------.---------NNNMMMMMMMQQQQRRRRRRRR--------[ZZZZZZZZZKZKK[[KK[K[ZZKZ[[[Z[[[KZZ[[[[KZZ[KZZZKZ[[[[[[[[[[[[ZKZZZZKZ[KZKZZZKKKZ[ZKZZZZZZZKKKZK[KK[ZZ[[KKZ[ZKZK[KZKZZZKZZZKZZZZZZZK[ZZZZZZZZ[[[[ZK[ZZZZZ[[QPQQPQPZNNNQQQQQQQQQRR&.-ZZZZZZZZNNNMNNNNNNNNNNNNQ&&&- Ё  None ?Options for generated static pointers, if enabled (/= Nothing).Are rules exposed or not?trim off the arity, one-shot-ness, strictness etc which were retained for the benefit of the code generatorWhich unfoldings to expose$Always true if we compile with -profDon't expose unfoldingsExpose mandatory unfoldings and those meeting inlining thresholds.Expose unfoldings useful for inlinings and those which which might be specialised. See Note [Exposing overloaded functions]Expose all unfoldingsCollect cost centres defined in the current module, including those in unfoldings.         NoneNone)+ If co :: T ts ~ rep_ty then: +instNewTyCon_maybe T ts = Just (rep_ty, co)Checks for a newtype, and for being saturated Just like Coercion.instNewTyCon_maybe, but returns a TcCoercionLike , but returns the arguments back if there is no data family to unwrap. Returns a Representational coercionConverts a data family type (eg F [a]) to its representation type (eg FList a) and returns a coercion between the two: co :: F [a] ~R FList a. gets rid of top-level newtypes, potentially looking through newtype  instances and type synonyms.It is only used by the type inference engine (specifically, when solving representational equality), and hence it is careful to unwrap only if the relevant data constructor is in scope. That's why it gets a GlobalRdrEnv argument.It is careful not to unwrap data/newtype instances nor synonyms if it can't continue unwrapping. Such care is necessary for proper error messages.It does not look through type families. It does not normalise arguments to a tycon.If the result is Just ((gres, co), rep_ty), then co : ty ~R rep_ty gres are the GREs for the data constructors that had to be in scope4Checks to make sure no two family instances overlap.Check whether a new open type family equation can be added without violating injectivity annotation supplied by the user. Returns True when this is possible and False if adding this equation would violate injectivity annotation. This looks only at the one equation; it does not look for interaction between equations. Use checkForInjectivityConflicts for that. Does checks (2)-(4) of Note [Verifying injectivity annotation] in GHC.Core.FamInstEnv.Report a list of injectivity errors together with their source locations. Looks only at one equation; does not look for conflicts *among* equations.,Is type headed by a type family application?If a RHS is a bare type variable return a set of LHS patterns that are not bare type variables.Return the set of type variables that a type family equation is expected to be injective in but is not. Suppose we have type family F a b = r | r -> a. Then any variables that appear free in the first argument to F in an equation must be fixed by that equation's RHS. This function returns all such variables that are not indeed fixed. It also returns whether any of these variables appear invisibly and whether -XUndecidableInstances would help. See Note [Coverage condition for injective type families].Report error message for a pair of equations violating an injectivity annotation. No error message if there are no branches.Report error message for equation with injective type variables unused in the RHS. Note [Coverage condition for injective type families], step 6Report error message for equation that has a type family call at the top level of RHSReport error message for equation that has a bare type variable in the RHS but LHS pattern is not a bare type variable.(Type family for which we generate errors1Currently checked equation (represented by axiom)Injectivity annotation p pNoneReport unsolved goals as errors or warnings. We may also turn some into deferred run-time errors if `-fdefer-type-errors` is on.Report *all* unsolved goals as errors, even if -fdefer-type-errors is on However, do not make any evidence bindings, because we don't have any convenient place to put them. NB: Type-level holes are OK, because there are no bindings. See Note [Deferring coercion errors to runtime] Used by solveEqualities for kind equalities (see Note [Failure in local type signatures] in GHC.Tc.Solver)Report all unsolved goals as warnings (but without deferring any errors to run-time). See Note [Safe Haskell Overlapping Instances Implementation] in  GHC.Tc.Solver,Report unsolved goals as errors or warnings.Make a report from a single . Returns True  == the SolverReportErrCtxt indicates that something is deferredShould we completely ignore this constraint in error reporting? It *must* be the case that any constraint for which this returns True somehow causes an error to be reported elsewhere. See Note [Constraints to ignore].Makes an error item from a constraint, calculating whether or not the item should be suppressed. See Note [Wanteds rewrite Wanteds] in GHC.Tc.Types.Constraint. Returns Nothing if we should just ignore a constraint. See Note [Constraints to ignore].Actually report this ĕ.#zonkTidyTcLclEnvs takes a bunch of $s, each from a Hole. It returns a ( :-> ) mapping which gives the zonked, tidied type for each Id in any of the binder stacks in the s. Since there is a huge overlap between these stacks, is is much, much faster to do them all at once, avoiding duplication.Wrap an input ߗ with additional contextual information, such as relevant bindings or valid hole fits.Pretty-print supplementary information, to add to an error report.(Display a collection of valid hole fits.'Add a "Constraints include..." message."See Note [Constraints include ...]Constructs a new hole error, unless this is deferred. See Note [Constructing Hole Errors].For all the skolem type variables in a type, zonk the skolem info and group together all the type variables with the same origin.Adds deferred bindings (as errors). See Note [Adding deferred bindings].Report a representation-polymorphism error to the user: a type is required to have a fixed runtime representation, but doesn't.See Note [Reporting representation-polymorphism errors] in GHC.Tc.Types.Origin.&Whether to report something using the FixedRuntimeRep mechanism.This function tries to reconstruct why a "Coercible ty1 ty2" constraint is left over.If the  is a type mismatch between an actual and an expected type, return the actual and expected types (in that order)./Prefer using this over manually inspecting the  datatype if you just want this information, as the datatype itself is subject to change across GHC versions.Filter the list by the given predicate, but if that would be empty, just give back the original list. We use this as we must report something for fdefer-type-errors. The main payload of the message.The context to add, after the main diagnostic but before the supplementary information. Nothing  = don't add any context.Supplementary information, to be added at the end of the message.The context we're in, i.e. the implications and the tidy environmentUnsolved simple constraintsThe holeWe return the new context with a possibly updated tidy environment, and the valid hole fits.None &'+ Whether to report deprecation warnings when registering a used GREThere is no option to only emit declaration warnings since everywhere we emit the declaration warnings we also emit export warnings (See Note [Handling of deprecations] for details)Throw an error message if a user attempts to quantify an inferred type variable in a place where specificity cannot be observed. For example, forall {a}. [a] -> [a]2 would be rejected to the inferred type variable {a}, but forall a. [a] -> [a] would be accepted. See +Note [Unobservably inferred type variables]."Examines a non-outermost type for foralls or contexts, which are assumed to be nested. For example, in the following declaration: ,instance forall a. forall b. C (Either a b) The outermost forall a is fine, but the nested forall b is not. We invoke  on the type forall b. C (Either a b) to catch the nested forall' and create a suitable error message.  returns L err_msg if such a forall# or context is found, and returns Nothing otherwise./This is currently used in the following places:In GADT constructor types (in  rnConDecl ). See Note [GADT abstract syntax] (Wrinkle: No nested foralls or contexts) in  GHC.Hs.Type."In instance declaration types (in  rnClsIntDecl and rnSrcDerivDecl in GHC.Rename.Module and  renameSig in GHC.Rename.Bind ). See 6Note [No nested foralls or contexts in instance types] in  GHC.Hs.Type.A common way to invoke .Checks to see if we need to warn for -Wunused-record-wildcards or -Wredundant-record-wildcards“Produce a warning when the `..`! pattern binds no new variables. 0 data P = P { x :: Int } foo (P{x, ..}) = x The `..`$ here doesn't bind any variables as x is already bound.Ó/Produce a warning when no variables bound by a `..` pattern are used. . data P = P { x :: Int } foo (P{..}) = () The `..` pattern binds x6 but it is not used in the RHS so we issue a warning.ēEmit a deprecation message whenever one of the implicit record wild card field binders was used in FreeVars.  module A where data P = P { x :: Int, y :: Int } {-# DEPRECATED x, y "depr msg" #-} module B where import A foo (P{..}) = x Even though both x and y have deprecations, only x will be deprecated since only its implicit variable is used in the RHS.œ$Should we report the fact that this  is unused? The  may differ from  due to DuplicateRecordFields.?Ensure that a boxed or unboxed tuple has arity no larger than .8Ensure that a constraint tuple has arity no larger than .Keeps the span given to the  for the application head only66NoneMini fixity env for the names we're about to bind, in a single binding groupIt is keyed by the *FastString*, not the *OccName*, because the single fixity decl  infix 3 T affects both the data constructor T and the type constructor TWe keep the location so that if we find a duplicate, we can report it sensiblyFixity declarations may influence names in a single namespace by using a type or data specifier, e.g. in: ) data a :*: b = a :*: b infix 3 type :*:To handle that correctly, MiniFixityEnv contains separate fields for type-level and data-level names. If no namespace specifier is provided, the declaration will populate both the type-level and data-level fields. returns (True, fixity) if it finds a   in a local environment or from an interface file. Otherwise, it returns (False, fixity) (e.g., for unbound s or .s without user-supplied fixity declarations).  None+ We couldn't find a suitable name!The child has an incorrect parentƓThis domain specific datatype is used to record why we decided it was possible that a GRE could be exported with a parent.Ǔ7The GRE could not be found, or it has the wrong parent.ȓ5The GRE has no parent. It could be a pattern synonym.ɓ,The parent of the GRE is the correct parent.ʓThe GRE is ambiguous.For example, two normal identifiers with the same name are in scope. They will both be resolved to UniqueOccurrence8 and the monoid will combine them to this failing case.˓Found an Exact Or Orig Name̓The RdrName was an Exact or Orig, but there was an error looking up the Name͓(The RdrName is neither an Exact nor OrigΓ Lookup an Exact RdrName. See Note [Looking up Exact RdrNames]. This never adds an error, but it may return one, see Note [Errors in lookup functions]5Look up the arity and record fields of a constructor.Look up an occurrence of a field in record construction or pattern matching (but not update).8If -XDisambiguateRecordFields is off, then we will pass K for the ( , i.e. we don't use the data constructor for disambiguation. See Note [DisambiguateRecordFields] and Note [NoFieldSelectors].,Used in export lists to lookup the children.ϓFind all the things the 4+ maps to, and pick the one with the right 4 .ГLook up an occurrence of a 4.Displays constructors and pattern synonyms as suggestions if it is not in scope.See Note [lookupOccRnConstr] Look up a 4% used as a variable in an expression.This may be a local variable, global variable, or one or more record selector functions. It will not return record fields created with the NoFieldSelectors) extension (see Note [NoFieldSelectors]).If the name is not in scope at the term level, but its promoted equivalent is in scope at the type level, the lookup will succeed (so that the type-checker can report a more informative error later). See Note [Promotion].ѓ Lookup a  in the 4, falling back to looking up in the type environment it if fails.lookupInfoOccRn is intended for use in GHCi's ":info" command It finds all the GREs that RdrName could mean, not complaining about ambiguity, but rather returning them all (c.f. #9881).lookupInfoOccRn is also used in situations where we check for at least one definition of the RdrName, not complaining about multiple definitions (see #17832).ғ1Look up all record field names, available in the 4, that a given 4 might refer to. (Also includes implicit qualified imports in GHCi).'Throws an error if no fields are found.0See Note [DisambiguateRecordFields for updates].ӓ Look up a 42, which might refer to an overloaded record field.Don't allow any ambiguity: emit a name-clash error if there are multiple matching GREs.Returns all possible collections of field labels for the given record update.Example:data D = MkD { fld1 :: Int, fld2 :: Bool } data E = MkE1 { fld1 :: Int, fld2 :: Bool, fld3 :: Char } | MkE2 { fld1 :: Int, fld2 :: Bool } data F = MkF1 { fld1 :: Int } | MkF2 { fld2 :: Bool }f r = r { fld1 = a, fld2 = b }This function will return:  [ D.fld1, D.fld2 -- could be a record update at type D , [ E.fld1, E.fld2 ] -- could be a record update at type E ] -- cannot be a record update at type F: no constructor has both -- of the fields fld1 and fld2?If there are no valid parents for the record update, throws a ˜ error.ԓ0Create an error message when there is no single b; which has all of the required fields for a record update.This boils down the problem to a smaller set of fields, to avoid the error message containing a lot of uninformative field names that aren't really relevant to the problem.NB: this error message should only be triggered when all the field names are in scope (i.e. each individual field name does belong to some constructor in scope).ՓLike ֓ but returning at most one name, reporting an ambiguity error if there are more than one.֓%Look up *all* the names to which the 4 may refer in GHCi (using -fimplicit-import-qualified). This will normally be zero or one, but may be more in the presence of DuplicateRecordFields. Look up the 3 associated with the given ( by looking up in the type environment.,Lookup a name in relation to the names in a ד Looks up the 4, expecting it to resolve to one of the bound names currently in scope. If not, return an appropriate error message.&See Note [Looking up signature names].Check irrefutability of a b in a 'ConPat GhcRn' (the 'Irref-ConLike' condition of Note [Irrefutability of ConPat]).Check irrefutability of the b in a 'ConPat GhcTc' (the 'Irref-ConLike' condition of Note [Irrefutability of ConPat]), given all in-scope COMPLETE pragmas ( in the typechecker,  in the desugarer).ؓ*Internal helper function: check whether a b: is the single member of a COMPLETE set without a result .Why 'without a result TyCon'? See Wrinkle [Irrefutability and COMPLETE pragma result TyCons] in Note [Irrefutability of ConPat]. parentchild we were looking for2list of possible parents | We resolved to a childthing we are looking uphow to look it up (e.g. which ) s to look in)ԓ1Field names that don't belong to a single dataconThe list of field labels for each constructor. (These are the constructors in which the first field occurs.):description of thing we're looking up, like "type family"דwhat to look upif the 4" we are looking up is in a value )2, should we also look up in the type constructor )?The standard namePossibly a non-standard name Lookup a Name that may be subject to Rebindable Syntax (RS).8When RS is off, just return the supplied (standard) NameWhen RS is on, look up the OccName of the supplied Name; return what we find, or the supplied Name if there is nothing in scopeThe standard namePossibly a non-standard namein-scope COMPLETE pragmasthe  of the bin-scope COMPLETE pragmas    %  !  &  None.Extra information about the parent instance declaration, needed when type-checking associated types. The K. is the enclosing class, the [TyVar] are the scoped* type variable of the instance decl. The  VarEnv Type. maps class variables to their instance types.Maps class tyvars to their instance types See Note [Matching in the consistent-instantiation check]The scoped6 tyvars of the instance Why scoped? See bind_me in  ٓ,Assumes that we've checked that this is the Typeable4 class, and it was applied to the correct argument.ړRepresentation for a type ty of the form  arg -> ret.ۓ >Noneł=Perform some IO, typically to interact with an external tool.Ƃ)Output useful for debugging the compiler.؂4Confused by zonking? See Note [What is zonking?] in GHC.Tc.Zonk.Type.ڂ.Create a new Wanted constraint with the given .ۂ:Create a new given constraint, with the supplied evidence.#This should only be invoked within  tcPluginSolve.܂!Create a fresh evidence variable.#This should only be invoked within  tcPluginSolve.݂Create a fresh coercion hole. This should only be invoked within  tcPluginSolve.ނBind an evidence variable.#This should only be invoked within  tcPluginSolve.'ǂтӂ҂ЂςׂȂԂ݂܂ւۂՂڂނ͂̂˂ɂ΂ʂłƂق؂'łƂǂȂɂʂ˂̂͂΂ςЂт҂ӂԂՂւׂ؂قڂۂ݂܂ނNone!&Instance dictionary function and type.2Emits the custom warning for a deprecated instance1See Note [Implementation of deprecated instances]Try to find a local quantified instance that dominates all others, i.e. which has a weaker instance context than all the others. co1) ~ ty2 (modulo a swap-flag)Call canEqSoftFailure when canonicalizing an equality fails, but if the equality is representational, there is some hope for the future.Call when canonicalizing an equality fails with utterly no hope.%Solve a reflexive equality constraint :: ty1 ~ ty2ty1 :: ty1 ~ ty1'ty2ty2, with type synonymsNone Represents collections of constraints generated by typechecker plugins"New constraints emitted by plugins,Constraints reported as insoluble by pluginsConstraints solved by pluginsOriginal inputs to the plugins with solved/bad constraints removed, but otherwise unmodified7A solved pair of constraints, with evidence for wanteds8A pair of (given, wanted) constraints to pass to pluginsExtract the (inert) givens and invoke the plugins on them. Remove solved givens from the inert set and emit insolubles, but return new work produced so that ( can feed it back into the main solver.Given a bag of (rewritten, zonked) wanteds, invoke the plugins on them and produce an updated bag of wanteds (possibly with some new work) and a bag of insolubles. The boolean indicates whether < should feed the updated wanteds back into the main solver.Starting from a pair of (given, wanted) constraints, invoke each of the typechecker constraint-solving plugins in turn and return%the remaining unmodified constraints,"constraints that have been solved,#constraints that are insoluble, and new work.Note that new work generated by one plugin will not be seen by other plugins on this pass (but the main constraint solver will be re-invoked and they will see it later). There is no check that new work differs from the original constraints supplied to the plugin: the plugin itself should perform this check if necessary. old evidence"new predicate + coercion, of type  typeof old evidence ~ new predicate>See Note [Wanteds rewrite Wanteds] in GHC.Tc.Types.ConstraintNone KAn atomic set of proposed type assignments to try applying all at once;s to be tried in sequence until the first one that succeeds8How should we choose which constraints to quantify over?Apply the monomorphism restriction, never quantifying over any constraintsSee Note [TcRnExprMode] in  GHC.Tc.Module, the :type +d case; this mode refuses to quantify over any defaultable constraintQuantify over any constraint that satisfies pickQuantifiablePredsA  action which can may solve a Type-check a thing that emits only equality constraints, solving any constraints we can and re-emitting constraints that we can't. Use this variant only when we'll get another crack at it later See Note [Failure in local type signatures]Panics if we solve any non-equality constraints. (In runTCSEqualities we use an error thunk for the evidence bindings.)Simplify top-level constraints, but without reporting any unsolved constraints nor unsafe overlapping./If an implication contains a Given of the form Unsatisfiable msg, use it to solve all Wanteds within the implication. See point (C) in Note [Implementation of Unsatisfiable constraints] in GHC.Tc.Errors.4This does a complete walk over the implication tree..Is this evidence variable the evidence for an  Unsatisfiable constraint?If so, return the variable itself together with the error message type.We have an implication with an  Unsatisfiable Given; use that Given to solve all the other Wanted constraints, including those nested within deeper implications.Create an evidence expression for an arbitrary constraint using evidence for an  Unsatisfiable Given.3See Note [Evidence terms from Unsatisfiable Givens]Default ExceptionContext constraints to emptyExceptionContext.Default any remaining  CallStack constraints to empty  CallStacks. See Note [Overview of implicit CallStacks] in GHC.Tc.Types.EvidenceReturn (Just new_inerts) if the Givens are satisfiable, Nothing if definitely contradictory.>See Note [Pattern match warnings with insoluble Givens] above.4Return True if the Wanteds are soluble, False if notNormalise a type as much as possible using the given constraints. See Note [tcNormalise].When inferring types, should we quantify over a given predicate? See Note [pickQuantifiablePreds]Like , but in the TcS monad.-Original constraints, for diagnostic purposesThe default classes and types*All constraints sharing same type variable-Original constraints, for diagnostic purposes$check these are solved by defaulting"defaulting type assignments to try-Original constraints, for diagnostic purposes$Check these are solved by defaulting%The sequences of assignment proposals$Predicate for successful assignments$check these are solved by defaulting"defaulting type assignments to try5successful substitutions, *not* reflected in ty_binds     %NoneCheck a list of binders to see if they make a valid telescope. See Note [Bad TyCon telescopes]0Information about a type being validity-checked.When validity-checking an application of a type synonym, should we check the arguments, check the expanded type, or both? See Note [Correctness and performance of type synonym validity checking]Only check the expanded type.Only check the arguments./Check both the arguments and the expanded type.Indicates whether a Č? represents type-level contexts, kind-level contexts, or both.A Č+ that only represents type-level positions.A Č+ that only represents kind-level positions.A Č8 that can represent both type- and kind-level positions.Check whether the type signature contains custom type errors, and fail if so.1Note that some custom type errors are acceptable:in the RHS of a type synonym, e.g. to allow users to define type synonyms for custom type errors with large messages (#20181),inside a type family application, as a custom type error might evaporate after performing type family reduction (#20241).Determine whether a Č can represent type-level contexts, kind-level contexts, or both.Returns M if the supplied Č is unambiguously not the context for a kind of a type. If the Č can refer to both types and kinds, this function conservatively returns M.An example of something that is unambiguously the kind of a type is the Show a => a -> a in type Foo :: Show a => a -> a'. On the other hand, the same type in foo :: Show a => a -> a is unambiguously the type of a term, not the kind of a type, so it is permitted.Returns M if the supplied Č is unambiguously not the context for a kind of a type, where the arbitrary use of constraints is currently disallowed.Returns M if the supplied Č is unambiguously not the context for a kind of a type, where all function arrows currently must be unrestricted.Returns M if the supplied Č is unambiguously not the context for the type of a term, where visible, dependent quantification is currently disallowed. If the Č can refer to both types and kinds, this function conservatively returns M.An example of something that is unambiguously the type of a term is the forall a -> a -> a in foo :: forall a -> a -> a'. On the other hand, the same type in %type family Foo :: forall a -> a -> a is unambiguously the kind of a type, not the type of a term, so it is permitted.For more examples, see  testsuitetests dependentshould_compileT16326_Compile*.hs+ (for places where VDQ is permitted) and  testsuitetests dependent should_failT16326_Fail*.hs' (for places where VDQ is disallowed).If LiberalTypeSynonyms is enabled, we start in $ mode for the reasons explained in Note [Liberal type synonyms]. Otherwise, we start in  mode.8Check for a DataKinds violation in a kind context. See Note [Checking for DataKinds].Note that emitting DataKinds errors from the typechecker is a fairly recent addition to GHC (introduced in GHC 9.10), and in order to prevent these new errors from breaking users' code, we temporarily downgrade these errors to warnings. (This is why we use  below.) See Note [Checking for DataKinds] (Wrinkle: Migration story for DataKinds typechecker errors).2See Note [Validity checking of HasField instances]#Split an instance type of the form #forall tvbs. inst_ctxt => inst_head and return (inst_ctxt, inst_head). This function makes no attempt to look through type synonyms. See (Note [Instances and constraint synonyms].Do validity checks on a type family equation, including consistency with any enclosing class instance head, termination, and lack of polytypes.See also the separate  which performs scoping checks on a type family equation. (It's separate because it expects K, which comes from a separate place e.g. for associated type defaults.).Checks that an associated type family default:  induced by an import of a particular interface, but without ‡.All the 4s associated with an 3.All the 4"s associated with a collection of 3s.Make an ) of all the imports.Complicated by the fact that associated data types and pattern synonyms can appear twice. See Note [Dealing with imports].Essentially like ,lookupGRE env (LookupOccName occ which_gres), but working with  s instead of 4s.3Given an import/export spec, appropriately set the gre_imp field for the 4s.Warn the user about top level binders that lack type signatures. Called after type inference, so that we can report the inferred type of the function>Warn the user about tycons that lack kind signatures. Called after type (and kind) inference, so that we can report the inferred kinds. Import spec&Whether this is a "hiding" import list None 3HShould GHC warn if a quantified type variable goes unused? Usually, the answer is "yes", but in the particular case of binding 7$, we avoid emitting warnings. See 8Note [Suppress -Wunused-foralls when binding LHsQTyVars].Always bind any free tyvars of the given type, regardless of whether we have a forall at the top.For pattern type sigs, we do want to bring those type variables into scope, even if there's a forall at the top which usually stops that happening, e.g: \ (x :: forall a. a -> b) -> eHere we do bring b into scope.RULES can also use #, such as in the following example: {-# RULES \"f\" forall (x :: forall a. a -> b). f x = ... b ... #-}This only applies to RULES that do not explicitly bind their type variables. If a RULE explicitly quantifies its type variables, then  is used instead. See also ,Note [Pattern signature binders and scoping] in  GHC.Hs.Type.Never bind any free tyvars. This is used for RULES that have both explicit type and term variable binders, e.g.: {-# RULES \"const\" forall a. forall (x :: a) y. const x y = x #-})The presence of the type variable binder  forall a. implies that the free variables in the types of the term variable binders x and y are not bound. In the example above, there are no such free variables, but if the user had written (y :: b) instead of y% in the term variable binders, then b5 would be rejected for being out of scope. See also ,Note [Pattern signature binders and scoping] in  GHC.Hs.Type.When the NamedWildCards extension is enabled, partition_nwcs removes type variables that start with an underscore from the FreeKiTyVars in the argument and returns them in a separate list. When the extension is disabled, the function returns the argument and empty list. See Note [Renaming named wild cards]Create new renamed type variables corresponding to source-level ones. Duplicates are permitted, but will be removed. This is intended especially for the case of handling the implicitly bound free variables of a type signature.(In what contexts are wildcards permitted>Ensures either that we're in a type or that -XPolyKinds is set(Look up the fixity for an operator name.Check for DataKinds violations in a type context, as well as "obvious" violations in kind contexts. See Note [Checking for DataKinds] in GHC.Tc.Validity for more on this.Filter out any type and kind variables that are already in scope in the the supplied LocalRdrEnv. Note that this includes named wildcards, which look like perfectly ordinary type variables at this point.Like , but keep parent class variables intact. Used with associated types. See Note [Class variables and filterInScope]Filter out any type and kind variables that are already in scope in the the environment's LocalRdrEnv. Note that this includes named wildcards, which look like perfectly ordinary type variables at this point.Like , but keep parent class variables intact. Used with associated types. See Note [Class variables and filterInScope] finds the type/kind variables of a HsType/HsKind. It's used when making the forall6s explicit. See Note [Kind and type-variable binders]Extracts the free type/kind variables from the kind signature of a HsType. This is used to implicitly quantify over k in type T = Nothing :: Maybe k. The left-to-right order of variables is preserved. See Note [Kind and type-variable binders] and Note [Ordering of implicit variables] and Note [Implicit quantification in type synonyms].Extracts free type and kind variables from types in a list. When the same name occurs multiple times in the types, all occurrences are returned.Extracts free type and kind variables from an argument in a GADT constructor, returning variable occurrences in left-to-right order. See %Note [Ordering of implicit variables].Get type/kind variables mentioned in the kind signature, preserving left-to-right order:data T a (b :: k1) :: k2 -> k1 -> k2 -> Type -- result: [k2,k1] an associated type declSurface-syntax free vars that we will implicitly bind. May have duplicates, which are removed here.name of the wildcard, or K for an anonymous wildcardL _ => an associated type declExplicitly bound herePotential implicit bindersFinal implicit binders66     &None &)<Type pattern renaming monad For the OccSet in the ReaderT, see Note [Locally bound names in type patterns] For the HsTyPatRnBuilderRn in the WriterT, see Note [Implicit and explicit type variable binders] For the CpsRn base monad, see Note [CpsRn monad] For why we need CpsRn in TPRnM see Note [Left-to-right scoping of type patterns]”Build a { out of an extension constructor, and the two components of the expansion: original and desugared patternsRename a regular (non-overloaded) record field update, disambiguating the fields if necessary.ÔTurn a Fractional-looking literal which happens to be an integer into an Integer-looking literal. We only convert numbers where the exponent is between 0 and 100 to avoid converting huge numbers and incurring long compilation times. See #15646.ĔRename type patternsFor the difference between Ĕ and rnHsTyKi see Note [CpsRn monad] and Note [Implicit and explicit type variable binders]”source patternexpanded patternsuitably wrapped {        ) + 0 None ŔMultiplicity annotations are a simple wrapper around types. As such, renaming them is a straightforward wrapper around .None K Ɣ0'InstDeclFreeVarsMap is an association of an InstDecl with FreeVars. The FreeVars are the tycon names that are both a) free in the instance declaration b) bound by this group of typeclassinstance declsǔStandalone kind signatures.Ȕ-Free variables of standalone kind signatures.ɔTracks whether we are renaming an equation in a closed type family equation (ʔ ) or not (˔).̔Tracks whether we are renaming: A type family equation that is not associated with a parent type class (͔ ). Examples:  type family F a type instance F Int = Bool -- NonAssocTyFamEqn NotClosed type family G a where G Int = Bool -- NonAssocTyFamEqn Closed  /An associated type family default declaration (Δ). Example:  class C a where type A a type instance A a = a -> a -- AssocTyFamDeflt C  0An associated type family instance declaration (ϔ). Example:  instance C a => C [a] where type A [a] = Bool -- AssocTyFamInst C [a]  rnSourceDecl "renames" declarations. It simultaneously performs dependency analysis and precedence parsing. It also does the following error checks:Checks that tyvars are used properly. This includes checking for undefined tyvars, and tyvars in contexts that are ambiguous. (Some of this checking has now been moved to module  TcMonoType, since we don't have functional dependency information at this point.)1Checks that all variable occurrences are defined. Checks the (..)$ etc constraints in the export list.Brings the binders of the group into scope in the appropriate places; does NOT assume that anything is in scope alreadyДFor Windows DLLs we need to know what packages imported symbols are from to generate correct calls. Imported symbols are tagged with the current package, so if they get inlined across a package boundary we'll still know where they're from.є8Warn about non-canonical typeclass instance declarationsA "non-canonical" instance definition can occur for instances of a class which redundantly defines an operation its superclass provides as well (c.f. /!). In such cases, a canonical instance is one where the subclass inherits its method implementation from its superclass instance (usually the subclass has a default method implementation to that effect). Consequently, a non-canonical instance occurs when this is not the case.See also descriptions of checkCanonicalMonadInstances and checkCanonicalMonoidInstancesҔRenames role annotations, returning them as the values in a NameEnv and checks for duplicate role annotations. It is quite convenient to do both of these in the same place. See also Note [Role annotations in the renamer]Ӕ Construct an InstDeclFreeVarsMap by eliminating any Names from the FreeVars" which are *not* the binders of a TyClDecl.ԔGet the  LInstDecls which have empty FreeVars sets, and the InstDeclFreeVarsMap with these entries removed. We call (getInsts tcs instd_map) when we've completed the declarations for tcs. The call returns (inst_decls, instd_map'), where inst_decls are the instance declarations all of whose free vars are now defined instd_map' is the inst-decl map with tcs- removed from the free-var setՔRename injectivity annotation. Note that injectivity annotation is just the part after the "|". Everything that appears before it is renamed in rnFamDecl.֔Brings pattern synonym names and also pattern synonym selectors from record pattern synonyms into scope.Ք.Type variables declared in type family headResult signatureInjectivity annotationNone # הMap from names that should not have export warnings to the spans of export list items that are missing those warningsؔList of names and the information about their warnings (warning, export list item span)ٔWhat names not to export warnings for (because they are exported without a warning)ڔ$Information about warnings for names۔Tracks (re-)exported module names and the names they re-exportܔ Tracks exported occurrence namesݔGiven a resolved name in the children export list and a parent. Decide whether we are allowed to export the child with the parent. Invariant: gre_par == NoParent See Note [Typing Pattern Synonym Exports]ޔInsert the given 4 s into the ߔ#, checking that each of the given 4)s does not appear multiple times in the ߔ1, as per Note [Exporting duplicate declarations].Is it OK for the given name to be exported by both export items?,See Note [Exporting duplicate declarations].Is it OK to export two clashing duplicate record fields coming from the given export items, with -XDisambiguateRecordFields disabled?-See Note [Exporting duplicate record fields].K means no explicit export list-Imported modules; this is used to test if a  module Foo6 export is valid (it's not valid if we didn't import Foo!)ݔ5Alleged parent type constructor User wrote T( P, Q )Either a a) Pattern Synonym Constructor b) A pattern synonym selectorNone m/Rename a splice type pattern. Much the same as (, but works with LHsType instead of LPat/Rename a splice pattern. See Note [rnSplicePat]The splice data to be loggedEnsure that we are not using a term-level name in a type-level namespace or vice-versa. Throws a ֘ error if there is a problem.Returns the result of running a splice and the modFinalizers collected during the execution.5See Note [Delaying modFinalizers in untyped splices].outputs splice information for 2 flags which have different output formats: `-ddump-splices` and `-dth-dec-file`None ) Rename some StmtsA tree of statements using a mixture of applicative and bind constructs.The s of return and pure. These may not be  returnName and pureName due to  QualifiedDo or RebindableSyntax.maybe rearrange statements according to the ApplicativeDo transformation.strip the FreeVars annotations from statementsIs this a context where we respect RebindableSyntax? but ListComp are never rebindable Neither is ArrowExpr, which has its own desugarer in GHC.HsToCore.Arrowsrearrange a list of statements using ApplicativeDoStmt. See Note [ApplicativeDo].Turn a sequence of statements into an ExprStmtTree using a heuristic algorithm. O(n^2)Turn a sequence of statements into an ExprStmtTree optimally, using dynamic programming. O(n^3)Turn the ExprStmtTree back into a sequence of statements, using ApplicativeStmt where necessary.Divide a sequence of statements into segments, where no segment depends on any variables defined by a statement in another segment.Find a "good" place to insert a bind in an indivisible segment. This is the only place where we use heuristics. The current heuristic is to peel off the first group of independent statements and put the bind after those.Build an ApplicativeStmt, and strip the "return" from the tail if necessary.For example, if we start with do x <- E1; y <- E2; return (f x y) then we get do (E1[x] | E2[y]); f x ythe LastStmt in this case has the return removed, but we set the flag on the LastStmt to indicate this, so that we can print out the original statement correctly in error messages. It is easier to do it this way rather than try to ignore the return later in both the typechecker and the desugarer (I tried it that way first!).Given the statements following an ApplicativeStmt, determine whether we need a join or not, and remove the return if necessary.We don't need join if there's a single LastStmt in the form of return E,  return $ E, pure E or pure $ E.(Just e, Just False), if the expression is  return/pure e-, and the third argument is Nothing, (Just e, Just True) if the expression is return/pure $ e-, and the third argument is Nothing, (Just (pure e), Nothing) if the expression is  return/pure e!, and the third argument is Just pure_expr, (Just (pure $ e), Nothing) if the expression is return/pure $ e!, and the third argument is Just pure_expr, otherwise Nothing.Expand U if rebindable syntax is turned on See Note [Handling overloaded and rebindable constructs]7How to rename the body of each statement (e.g. rnLExpr) Statementsif these statements scope over something, this renames it and returns the result.'How to rename the body of the statement The statement0Rename the stuff that this statement scopes overThe free variables used in later statements. If the boolean is M, this might be an underestimate because we are in GHCi, and might thus be missing some "used later" FVs. See Note [What is "used later" in a rec stmt] the "tail"free variables of the tailis -XStrict enabled?The argsTrue  = need a joinThe body statements    1None&' Load the module containing the given Name and get its associated . Throws a . if loading fails or the name cannot be found."Temporarily extend the loaded env.Display the loader state.,Initialise the dynamic linker. This entails*a) Calling the C initialisation procedure,6b) Loading any packages specified on the command line,c) Loading any packages specified on the command line, now held in the -l options in v_Opt_l,d) Loading any .o/.dll7 files specified on the command line, now held in ldInputs, e) Loading any MacOS frameworks.NOTE: This function is idempotent; if called more than once, it does nothing. This is useful in Template Haskell, where we call it before trying to link.Merge runs of consecutive of . This allows for resolution of cyclic symbol references when dynamically linking. Specifically, we link together all of the static objects into a single shared object, avoiding the issue we saw in #13786.Load a single expression,  including first loading packages and modules that this expression depends on.Raises an IO exception () if it can't find a compiled version of the dependents to load.#Load the object files and link themIf the interpreter uses dynamic-linking, build a shared library and load it. Otherwise, use the RTS linker.Create a shared library containing the given object files and load it.!Useful to apply to the result of 8Unloading old objects ready for a new compilation sweep.The compilation manager provides us with a list of linkables that it considers "stable", i.e. won't be recompiled this time around. For each of the modules current linked in memory,if the linkable is stable (and it's the same one -- the user may have recompiled the module on the side), we keep it,otherwise, we unload it.?we also implicitly unload all temporary bindings at this point.Load exactly the specified packages, and their dependents (unless of course they are already loaded). The dependents are loaded automatically, and it doesn't matter what order you specify the input packages.Retrieve the list of search directory GCC and the System use to find libraries and components. See Note [Fork/Exec Windows].Cache for the GCC search directories as this can't easily change during an invocation of GHC. (Maybe with some env. variable but we'll) deal with that highly unlikely scenario then.Get a list of system search directories, this to alleviate pressure on the findSysDll function.Merge the given list of paths with those in the environment variable given. If the variable does not exist then just return the identity.returns the set of linkables required When called, the loader state must have been initialized (see )The linkables to *keep*.None Initialise plugins specified by the current DynFlags and update the session.Loads the plugins specified in the pluginModNames field of the dynamic flags. Should be called after command line arguments are parsed, but before actual compilation starts. Idempotent operation. Should be re-called if pluginModNames or pluginModNameOpts changes.=Force the interfaces for the given modules to be loaded. The # parameter is used for debugging (-ddump-if-trace) only: it is shown as the reason why the module is being loaded.Force the interface for the module containing the name to be loaded. The # parameter is used for debugging (-ddump-if-trace) only: it is shown as the reason why the module is being loaded. Load the  associated with the given name, come hell or high water. Fails if:!The interface could not be loadedThe name is not that of a +The name did not exist in the loaded module#Loads the value corresponding to a  if that value has the given . This only provides limited safety in that it is up to the user to ensure that that type corresponds to the type you try to use the return value at!8If the value found was not of the correct type, returns Left actual_type.. Any other condition results in an exception:%If we could not load the names module(If the thing being loaded is not a value(If the Name does not exist in the moduleIf the link failedCoerce a value as usual, but:1) Evaluate it immediately to get a segfault early if the coercion was wrong2) Wrap it in some debug messages at verbosity 3 or higher so we can see what happened if it does segfault Finds the  corresponding to the given 4 in the context of the  . Returns Nothing if no such > could be found. Any other condition results in an exception: If the module could not be found3If we could not determine the imports of the moduleCan only be used for looking up names while loading plugins (and is *not* suitable for use within plugins). The interface file is loaded very partially: just enough that it can be used, without its rules and instances affecting (and being linked from!) the module being compiled. This was introduced by 57d6798.Need the module as well to record information in the interface file  None&'hReturns true if an t is for data T (an abstract data type) Merge two ts together, preferring a non-abstract one. If both are non-abstract we pick one arbitrarily (and check for consistency later.) Merge two )s of ts by .This is a very interesting function. Like typecheckIface, we want to type check an interface file into a ModDetails. However, the use-case for these ModDetails is different: we want to compare all of the ModDetails to ensure they define compatible declarations, and then merge them together. So in particular, we have to take a different strategy for knot-tying: we first speculatively merge the declarations to get the "base" truth for what we believe the types will be (this is "type computation.") Then we read everything in relative to this truth and check for compatibility.During the merge process, we may need to nondeterministically pick a particular declaration to use, if multiple signatures define the declaration (). If, for all choices, there are no type synonym cycles in the resulting merged graph, then we can show that our choice cannot matter. Consider the set of entities which the declarations depend on: by assumption of acyclicity, we can assume that these have already been shown to be equal to each other (otherwise merging will fail). Then it must be the case that all candidate declarations here are type-equal (the choice doesn't matter) or there is an inequality (in which case merging will fail.)Unfortunately, the choice can matter if there is a cycle. Consider the following merge:signature H where { type A = C; type B = A; data C } signature H where { type A = (); data B; type C = B } If we pick  type A = C as our representative, there will be a cycle and merging will fail. But if we pick  type A = () as our representative, no cycle occurs, and we instead conclude that all of the types are unit. So it seems that we either (a) need a stronger acyclicity check which considers *all* possible choices from a merge, or (b) we must find a selection of declarations which is acyclic, and show that this is always the "best" choice we could have made (ezyang conjectures this is the case but does not have a proof). For now this is not implemented.It's worth noting that at the moment, a data constructor and a type synonym are never compatible. Consider:signature H where { type Int=C; type B = Int; data C = Int} signature H where { export Prelude.Int; data B; type C = B; }This will be rejected, because the reexported Int in the second signature (a proper data type) is never considered equal to a type synonym. Perhaps this should be relaxed, where a type synonym in a signature is considered implemented by a data type declaration which matches the reference of the type synonym.Typecheck a signature ʑ under the assumption that we have instantiated it under some implementation (recorded in ?) and want to check if the implementation fills the signature.0This needs to operate slightly differently than  because (1) we have a , from the exports of the implementing module, which we will use to give our top-level declarations the correct s even when the implementor provided them with a reexport, and (2) we have to deal with DFun silliness (see Note [rnIfaceNeverExported])1See Note [Interface File with Core: Sharing RHSs]This function is only used to construct the environment for GHCi, so we make up fake locationsTrue  =# discard IdInfo on IfaceId bindings,For associated type/data family declarationsTrue  =# discard IdInfo on IfaceId bindingsIs this unfolding compulsory? See Note [Checking for representation polymorphism] in GHC.Core.LintNone )3() describes how to typecheck an explicit (6) or implicit () binder in a type. It is just a record of flags that describe what sort of  to create.1Describes the kind expected in a certain context.a specific kindany kind will dosomething of the form TYPE _Info about the context in which we're checking a type. Currently, differentiates only between types and kinds, but this will likely grow, at least to include the distinction between patterns and not-patterns./To find out where the mode is used, search for =This data type is purely local, not exported from this moduleTypecheck a deriving strategy. For most deriving strategies, this is a no-op, but for the via* strategy, this requires typechecking the via type.%Type-check a visible type applicationCheck and desugar a type, returning the core type and its possibly-polymorphic kind. Much like  tcInferRho at the expression level.Infer the kind of a type and desugar. This is the "up" type-checker, as described in Note [Bidirectional type checking]Apply a type of a given kind to a list of arguments. This instantiates invisible parameters as necessary. Always consumes all the arguments, using matchExpectedFunKind as necessary. This takes an optional  VarEnv Kind which maps kind variables to kinds.- These kinds should be used to instantiate invisible kind variables; they come from an enclosing class for an associated type/data family.tcInferTyApps also arranges to saturate any trailing invisible arguments of a type-family application, which is usually the right thing to do tcInferTyApps_nosat does not do this saturation; it is used only by ":kind" in GHCiApply a type of a given kind to a list of arguments. This instantiates invisible parameters as necessary. Always consumes all the arguments, using matchExpectedFunKind as necessary. This takes an optional  VarEnv Kind which maps kind variables to kinds.- These kinds should be used to instantiate invisible kind variables; they come from an enclosing class for an associated type/data family.tcInferTyApps also arranges to saturate any trailing invisible arguments of a type-family application, which is usually the right thing to do tcInferTyApps_nosat does not do this saturation; it is used only by ":kind" in GHCiThis instantiates invisible arguments for the type being checked if it must be saturated and is not yet saturated. It then calls and uses the result from checkExpectedKindX to build the final typeNew unification variable '_' for a wildcard=Create a TyConBinder for a user-written type variable binder. Kind-check a 7 . Used in inferInitialKind$ (for tycon kinds and other kinds).-This function does not do telescope checking.Kind-check a declaration header against a standalone kind signature. See Note [kcCheckDeclHeader_sig]Check the result kind annotation on a type constructor against the corresponding section of the standalone kind signature. Drops invisible binders that interfere with unification.Skolemise the 6s in an 7 with the supplied .Bring into scope the binders of a PolyTcTyCon Used for the type variables of a type or class decl in the "kind checking" and "type checking" pass, but not in the initial-kind run.Generalize some of the free variables in the given type. All such variables should be *kind* variables; any type variables should be explicitly quantified (with a `forall` ) before now.The WantedConstraints are un-solved kind constraints. Generally they'll be reported as errors later, but meanwhile we refrain from quantifying over any variable free in these unsolved constraints. See Note [Failure in local type signatures].But in all cases, generalize only those variables whose TcLevel is strictly greater than the ambient level. This "strictly greater than" means that you likely need to push the level before creating whatever type gets passed here.Any variable whose level is greater than the ambient level but is not selected to be generalized will be promoted. (See [Promoting unification variables] in  GHC.Tc.Solver. and Note [Recipe for checking a signature].)The resulting KindVar are the variables to quantify over, in the correct, well-scoped order. They should generally be Inferred, not Specified, but that's really up to the caller of this function.Specialised version of , but with empty WantedConstraints, so no filtering is needed i.e. kindGeneraliseAll = kindGeneralizeSome emptyWCSpecialized version of , but where no variables can be generalized, but perhaps some may need to be promoted. Use this variant when it is unknowable whether metavariables might later be constrained.To see why this promotion is needed, see Note [Recipe for checking a signature], and especially Note [Promotion in signatures].Checks that the return kind in a data declaration's kind signature is permissible. There are three cases:If dealing with a data, newtype,  data instance, or newtype instance- declaration, check that the return kind is Type.If the declaration is a newtype or newtype instance and the UnliftedNewtypes extension is enabled, this check is slightly relaxed so that a return kind of the form TYPE r (for some r) is permitted. See )Note [Implementation of UnliftedNewtypes] in  GHC.Tc.TyCl.If dealing with a  data family declaration, check that the return kind is either of the form: TYPE r (for some r), ork (where k% is a bare kind variable; see #12369))See also Note [Datatype return kinds] in  GHC.Tc.TyCl2Checks that the result kind of a class is exactly  Constraint<, rejecting type synonyms and type families that reduce to  Constraint . See #16826.Make an appropriate message for an error in a function argument. Used for both expressions and types.3Add a "In the data declaration for T" or some such. The deriving strategyThe typechecked deriving strategy and the tyvars that it binds (if using 9).argument typesof these kinds expected kind of the whole tupleFunction (for printing only)FunctionArgs(f args, result kind)Function (for printing only)FunctionArgs(f args, result kind)"type we're checking (for printing)type we're checkingthe known kind of that typethe expected kindof the thing being checked What sort of  is being checkedBinders in the headerThe result kindA suitably-kinded TcTyConof the thing being checked What sort of  is being checkedBinders in the header/The result kind. AnyKind == no result signature%A suitably-kinded generalized TcTyConof the thing being checked What sort of  is being checkedBinders in the headerThe result kind%A suitably-kinded generalized TcTyConof the thing being checked What sort of  is being checkedThe result kind)A suitably-kinded non-generalized TcTyCon;Standalone kind signature, fully zonked! (zonkTcTypeToType)of the thing being checked What sort of  is being checkedBinders in the header/The result kind. AnyKind == no result signatureA suitably-kinded, fully generalised TcTyCon Postcondition to (kcCheckDeclHeader_sig sig_kind n f hs_tvs kc_res_ki): kind(returned PolyTcTyCon) = sig_kind0the result kind from the separate kind signature+the result kind from the declaration headerneedn't be zonkedČ֌ˌی،ьٌnjЌŌԌՌƌҌȌΌ͌ό׌ӌɌ݌̌܌ڌʌČ֌ˌی،ьٌnjЌŌԌՌƌҌȌΌ͌ό׌ӌɌ݌̌܌ڌʌ      !   None Find the location of the top-level context of a HsType. For example:  forall a b. (Eq a, Ord b) => blah ^^^^^^^^^^^^^  If there is none, return Nothing0If there are no wildcards, return a LHsSigWcTypeNone  A variant of tcPat that takes a custom origin:Convenient wrapper for calling a matchExpectedXXX functionCheck that a pattern isn't a GADT, or doesn't have existential variables, in a situation in which that is not permitted (inside a lazy pattern, or in arrow notation).patternstypes of the patternschecker for the body(origin to use if the type needs inst'ingFully refined result typeTranslated patternType of the patternThe TyCon that this data constructor actually returns. In the case of a data family, this is the representation TyCon.The type of the pattern. In the case of a data family, this would mention the family TyCon existentialsargument types     None None pWarn the user about polymorphic local binders that lack type signatures. ann takes an optional multiplicity annotation. If present the multiplicity is returned, otherwise a fresh unification variable is generated so that multiplicity can be inferred.The location of the first pattern synonym binding (for error reporting)  'None A monad for type synonym cycle checking, which keeps track of the TyCons which are known to be acyclic, or a failure message reporting that a cycle was found. Test if a 8 is acyclic, short-circuiting if we've seen it already.Checks if any of the passed in s have cycles. Takes the  of the home package (as we can avoid checking those TyCons: cycles never go through foreign packages) and the corresponding LTyClDecl Name for each (, so we can give better error messages.            None  Given a . of an instantiated signature (note that the  must be knot-tied consistently with the actual implementation) and a 4 constructed from the implementor of this interface, verify that the actual implementation actually matches the original interface.Note that it is already assumed that the implementation *exports* a sufficient set of entities, since otherwise the renaming and then typechecking of the signature ʑ would have failed. Checks if a w is "defined". In general, for hsig files we can't assume that the implementing file actually implemented the instances (they may be reexported from elsewhere). Where should we look for the instances? We do the same as we would otherwise: consult the EPS. This isn't perfect (we might conclude the module exports an instance when it doesn't, see #9422), but we will never refuse to compile something. For a module modname of type %, determine the list of extra "imports" of other requirements which should be considered part of the import of the requirement, because it transitively depends on those requirements by imports of modules from other packages. The situation is something like this:unit p where signature X signature Y import Xunit q where dependency p[X=,Y=] signature A signature BAlthough q's B does not directly import A, we still have to make sure we process A first, because the merging process will cause B to indirectly import A. This function finds the TRANSITIVE closure of all such imports we need to make.Like implicitRequirements', but returns either the module name, if it is a free hole, or the instantiated unit the imported module is from, so that that instantiated unit can be processed and via the batch mod graph (rather than a transitive closure done here) all the free holes are still reachable.Given a , make sure it is well typed. This is because unit IDs come from Cabal, which does not know if things are well-typed or not; a component may have been filled with implementations for the holes that don't actually fulfill the requirements.Top-level driver for signature instantiation (run when compiling an hsig file.)Top-level driver for signature merging (run after typechecking an hsig file). The list of s of *non-exported* ts which this t may refer to. A non-exported t1 should be kept after thinning if an *exported* t (or ܑ, perhaps) refers to it; we can't decide to keep it by looking at the exports of a module after thinning. Keep this synchronized with  rnIfaceDecl.Given a local ʑ), merge all inherited requirements from ) into this signature, producing a final ? that matches the local signature and all required signatures.Add on the necessary transitive information from the merged signature to the  of the result of merging. This propagates the orphan instances which were in the transitive closure of the signature through the merge.Top-level driver for signature instantiation (run when compiling an hsig file.)Check if module implements a signature. (The signature is always un-hashed, which is why its components are specified explicitly.)Given , instantiate a ʑ from the indefinite library to use the actual implementations of the relevant entities, checking that the implementation matches the signature.+From the signature resulting from the mergeFrom the original signature  None r PatSyn NamePatSyn type (UniBidirExplicitBidir) Whether infixPattern of the PatSynPattern arguments and types. These must have a syntactically fixed RuntimeRep as per Note [Fixed RuntimeRep] in GHC.Tc.Utils.Concrete. Pattern type  Type) Maybe where {} 'Then in order to typecheck the default F+ instance, we must apply the substitution #[k :-> (Type -> Type), a :-> Maybe] to F's binders, which are [k, a, (b :: k)]#. The result should look like this: ? type F (Type -> Type) Maybe (b :: Type -> Type) = (Proxy (Type -> Type) Maybe, Proxy $(Type -> Type) (b :: Type -> Type)) 9Making this work requires some care. There are two cases: If we encounter a type variable in the domain of the substitution (e.g., k or a+), then we apply the substitution directly.Otherwise, we substitute into the type variable's kind (e.g., turn b :: k to b :: Type -> Type=). We then return an extended substitution where the old b (of kind k) maps to the new b (of kind  Type -> Type).This step is important to do in case there are later occurrences of b, which we must ensure have the correct kind. Otherwise, we might end up with Proxy @(Type -> Type) (b :: k) on the right-hand side of the default instance, which would be completely wrong. Contrast . function with similar substitution functions: substTyVars does not substitute into the kinds of each type variable, nor does it extend the substitution.  substTyVars8 is meant for occurrences of type variables, whereas  substATBndrs is meant for binders.substTyVarBndrs does substitute into kinds and extends the substitution, but it does not apply the substitution to the variables themselves. As such, substTyVarBndrs returns a list of s rather than a list of s.  None 3`!Information about the arguments to the class in a stock- or newtype-derived instance. For a deriving2-generated instance declaration such as this one: instance Ctx => Cls cls_ty_1 ... cls_ty_m (TC tc_arg_1 ... tc_arg_n) where ...  corresponds to cls_ty_1 ... cls_ty_m. corresponds to TC. corresponds to tc_arg_1 ... tc_arg_n.See &Note [DerivEnv and DerivSpecMechanism] in GHC.Tc.Deriv.Utils for a more in-depth explanation, including the relationship between  and .A ? value can be seen as a more structured representation of the  denv_inst_tys in a DerivEnv , as the  denv_inst_tys is equal to dit_cls_tys ++ [. dit_tc dit_tc_args]?. Other parts of the instance declaration can be found in the DerivEnv. For example, the Cls* in the example above corresponds to the denv_cls field of DerivEnv./Similarly, the type variables that appear in a + value are the same type variables as the denv_tvs in the parent DerivEnv. Accordingly, if we are inferring an instance context, the type variables will be , skolems. Otherwise, they will be ordinary s. See Note [Overlap and deriving] in GHC.Tc.Deriv.Infer.The cached results of instantiating each data constructor's field types using \ data_con  . See 2Note [Instantiating field types in stock deriving].This field is only used for stock-derived instances and goes unused for newtype-derived instances. It is put here mainly for the sake of convenience.The representation types for 7 (for data family instances). Otherwise the same as .The representation tycon for 7 (for data family instances). Otherwise the same as .!Arguments to the type constructorType constructor for which the instance is requested (last arguments to the type class),Other arguments to the class except the lastA declarative description of an auxiliary binding that should be generated. See Note [Auxiliary binders]8 for a more detailed description of how these are used.$tag2con:: Given a tag, computes the corresponding data constructor$maxtag: The maximum possible tag value among a data type's constructors$t: The DataType representation for a Data instance$c: The Constr representation for a Data instance Retrieve the 4" of the binding that the supplied  describes.showString :: String -> ShowS(showsPrec :: Show a => Int -> a -> ShowSshows :: Show a => a -> ShowS6Generate the full code for an auxiliary binding. See =Note [Auxiliary binders] (Wrinkle: Reducing code duplication).Generate the code for an auxiliary binding that is a duplicate of another auxiliary binding. See =Note [Auxiliary binders] (Wrinkle: Reducing code duplication).:Generate the type signature of an auxiliary binding. See Note [Auxiliary binders].Take a  of s and generate the code for auxiliary bindings based on the declarative descriptions in the supplied s. See Note [Auxiliary binders].Make a function binding. If no equations are given, produce a function with the given arity that produces a stock error.Make a function binding. If no equations are given, produce a function with the given arity that uses an empty case expression for the last argument that is passes to the given function to produce the right-hand side.Produces a function binding. When no equations are given, it generates a binding of the given arity and an empty case expression for the last argument that it passes to the given function to produce the right-hand side.Produces a function binding. When there are no equations, it generates a binding with the given arity that produces an error based on the name of the type of the last argument.Generate the name for an auxiliary binding, giving it a fresh . Returns an 4 4 with an underlying System . See Note [Auxiliary binders].$getPossibleDataCons tycon tycon_args returns the constructors of tycon0 whose return types match when checked against  tycon_args.7See Note [Filter out impossible GADT data constructors];Look up a data constructor's instantiated field types in a . See 2Note [Instantiating field types in stock deriving]. tycon arg_tys' constructs a cache that maps each of tycon's data constructors to their field types, with are to be instantiated with arg_tys. See 2Note [Instantiating field types in stock deriving].#Apply a substitution to all of the s contained in a . See 2Note [Instantiating field types in stock deriving]' for why we need to substitute into a  in the first place. Zonk the s in a  value to s. See Note [What is zonking?] in GHC.Tc.Zonk.Type.This is only used in the final zonking step when inferring the context for a derived instance. See Note [Overlap and deriving] in GHC.Tc.Deriv.Infer.%%  !None   Forall type.Type app, variable other than in last argument2Type app, variable only in last argument. The two ,s are the function and argument parts of  fun_ty arg_ty, respectively.Tuple type. The [a]= is the result of folding over the arguments of the tuple. Function type$The variable itself, contravariantlyThe variable itselfDoes not contain variable#Return all syntactic subterms of a  that are applied to the  argument. This determines what constraints should be inferred for derived *, 5, and 6 instances in GHC.Tc.Deriv.Infer. For instance, if we have: :data Foo a = MkFoo Int a (Maybe a) (Either Int (Maybe a)) Then the following would hold: a Int would return [], since Int' does not contain the type variable a at all. a a would return []. Although the type a contains the type variable a , it is not applied to a!, which is the criterion that  checks for. a (Maybe a) would return [Maybe], as Maybe is applied to a. a (Either Int (Maybe a)) would return [Either Int, Maybe]%. Both of these types are applied to a through composition. As used in GHC.Tc.Deriv.Infer, the ! argument will always come from , so it is important that the  comes from \ to match. Make sure not to take the  from L, as these differ from the \ when the data type is a GADT. (See #22167 for what goes wrong if L is used.)Variable to look for How to foldType to processNone See documentation of ; that function uses the fields of this type to interpret the structure of a type when that type is considered as an argument to a constructor that is being represented with Rep1. Called by  6; generates a list of types, each of which must be a * in order for the Generic1- instance to work. For instance, if we have: :data Foo a = MkFoo Int a (Maybe a) (Either Int (Maybe a)) Then  a (f (g a)) would return  [Either Int], as a derived Generic1 instance would need to call  at that type. Invoking  a* on any of the other fields would return []. is very similar in spirit to  in GHC.Tc.Deriv.Functor. Just like with , it is important that the  argument come from \%. (See #22167 for what goes wrong if L is used.) argTyFold3 implements a generalised and safer variant of the arg function from Figure 3 in  (http://dreixel.net/research/pdf/gdmh.pdf. arg is conceptually equivalent to: arg t = case t of _ | isTyVar t -> if (t == argVar) then Par1 else Par0 t App f [t'] | representable1 f && t' == argVar -> Rec1 f App f [t'] | representable1 f && t' has tyvars -> f :.: (arg t') _ -> Rec0 twhere argVar is the last type variable in the data type declaration we are finding the representation for. argTyFold is more general than arg because it uses . to abstract out the concrete invocations of Par0, Rec0, Par1, Rec1, and :.:. argTyFold is safer than arg because arg would lead to a GHC panic for some data types. The problematic case is when t0 is an application of a non-representable type f to argVar: App f [argVar] is caught by the _% pattern, and ends up represented as Rec0 t. This type occurs free in the RHS of the eventual Rep1 instance, which is therefore ill-formed. Some representable1 checks have been relaxed, and others were moved to canDoGenerics1.-Variant of foldr for producing balanced listsNone *3 A list of  constraints to simplify when inferring a derived instance's context. For the stock, newtype, and via- deriving strategies, these will consist of  s, and for DeriveAnyClass, these will consist of 0s. Here is an example to illustrate the latter: class Foo a where bar :: forall b. Ix b => a -> b -> String default bar :: forall y. (Show a, Ix y) => a -> y -> String bar x y = show x ++ show (range (y, y)) baz :: Eq a => a -> a -> Bool default baz :: Ord a => a -> a -> Bool baz x y = compare x y == EQ data Quux q = Quux deriving anyclass Foo Then it would generate two s, one for each method: [ SubTypePredSpec { stps_ty_actual = forall y. (Show (Quux q), Ix y) => Quux q -> y -> String , stps_ty_expected = forall b. (Ix b) => Quux q -> b -> String , stps_ty_origin = DerivClauseCtxt } , SubTypePredSpec { stps_ty_actual = Ord (Quux q) => Quux q -> Quux q -> Bool , stps_ty_expected = Eq (Quux q) => Quux q -> Quux q -> Bool , stps_ty_origin = DerivClauseCtxt } ] (Note that the type variable q is bound by the data type Quux , and thus appears free in the s and s.)See ?Note [Gathering and simplifying constraints for DeriveAnyClass] in GHC.Tc.Deriv.Infer! for an explanation of how these /s are used to compute implication constraints.A  specifies a constraint to emitted when inferring the instance context for a derived instance in  . An ordinary  that directly stores a , which will be emitted as a wanted constraint in the constraint solving machinery. This is the simple case, as there are no skolems, metavariables, or given constraints involved. A special  that is only used by DeriveAnyClass. This will check if stps_ty_actual0 is a subtype of (i.e., more polymorphic than) stps_ty_expected in the constraint solving machinery, emitting an implication constraint as a side effect. For more details on how this works, see ?Note [Gathering and simplifying constraints for DeriveAnyClass] in GHC.Tc.Deriv.Infer.(Whether the constraint is a type or kindThe origin of the constraint"The constraint to emit as a wantedThe origin of the constraint%The expected type. In the context of DeriveAnyClass., this is the original method type signature.#The actual type. In the context of DeriveAnyClass-, this is the default method type signature.-Describes how to generate instance bindings ()) and associated type family instances (+) for a particular stock-derived instance.Describes how to generate associated type family instances for a stock-derived instance. This function takes the same arguments as the  function but returns a list of ps instead. Generating type family instances is done separately from  since the type family instances must be generated before the instance bindings can be typechecked. See Note [Staging of tcDeriving] in  GHC.Tc.Deriv.Describes how to generate instance bindings for a stock-derived instance."This function takes two arguments: : the source location where the instance is being derived. This will eventually be instantiated with the  field of a .: information about the argument types to which a class is applied in a derived instance. This will eventually be instantiated with the  field of a ."This function returns four things: 7 56: The derived instance's function bindings (e.g., !compare (T x) (T y) = compare x y)[7 5]: A list of instance specific signatures/pragmas. Most likely INLINE pragmas for class methods. : Auxiliary bindings needed to support the derived instance. As examples, derived % and ,+ instances sometimes require top-level con2tag functions. See Note [Auxiliary binders] in GHC.Tc.Deriv.Generate.[]: A list of Names for which -Wunused-binds should be suppressed. This is used to suppress unused warnings for record selectors when deriving -, 1, or Generic . See +Note [Deriving and unused record selectors].Records whether a particular class can be derived by way of an  originative deriving strategy (i.e., stock or anyclass).See Note [Deriving strategies] in  GHC.Tc.Deriv.Whether GHC is processing a deriving. clause or a standalone deriving declaration.'InferContext mb_wildcard is either:A deriving clause (in which case  mb_wildcard is K).A standalone deriving declaration with an extra-constraints wildcard as the context (in which case  mb_wildcard is L loc, where loc$ is the location of the wildcard.GHC should infer the context. theta. is a standalone deriving declaration, where theta& is the context supplied by the user.>What action to take in order to derive a class instance. See &Note [DerivEnv and DerivSpecMechanism], as well as Note [Deriving strategies] in  GHC.Tc.Deriv."Standard" classes GeneralizedNewtypeDeriving DeriveAnyClass  DerivingViaHow to generate the instance bindings and associated type family instances.Information about the arguments to the class in the derived instance, including what type constructor the last argument is headed by. See &Note [DerivEnv and DerivSpecMechanism].The newtype rep type.Information about the arguments to the class in the derived instance, including what type constructor the last argument is headed by. See &Note [DerivEnv and DerivSpecMechanism].The via typeThe last argument to the class.0All arguments to the class besides the last one.Contains all of the information known about a derived instance when determining what its EarlyDerivSpec should be. See &Note [DerivEnv and DerivSpecMechanism].7A warning to emit whenever the derived instance is usedL if user requests a particular deriving strategy. Otherwise, K.The  used to skolemise the denv_tvs in the case where the  is . theta for standalone deriving (where theta( is the context of the instance).  for deriving clauses, or for standalone deriving that uses a wildcard constraint. See %Note [Inferring the instance context].All arguments to  in the derived instance.-Class for which we need to derive an instanceUniversally quantified type variables in the instance. If the  denv_ctxt is , these will be  skolems. If the  denv_ctxt is , these will be ordinary  s. See Note [Overlap and deriving] in GHC.Tc.Deriv.Infer.&All type variables that appear in the , , , and  should come from . Is this an overlapping instance?0To avoid having to manually plumb everything in " throughout various functions in  GHC.Tc.Deriv and GHC.Tc.Deriv.Infer , we use #, which is a simple reader around .4Is GHC processing a standalone deriving declaration?Is GHC processing a standalone deriving declaration with an extra-constraints wildcard as the context? (e.g., !deriving instance _ => Eq (Foo a))Return Ҍ! if processing with a standalone deriving declaration or ٌ if processing a deriving clause. wc returns  if wc is M, and  if wc is J. Useful for error-reporting.Set the  in a . Zonk the s in a  to s. See Note [What is zonking?] in GHC.Tc.Zonk.Type.This is only used in the final zonking step when inferring the context for a derived instance. See Note [Overlap and deriving] in GHC.Tc.Deriv.Infer. Convert a  to its corresponding 9. Zonk the s in a  to s. See Note [What is zonking?] in GHC.Tc.Zonk.Type.This is only used in the final zonking step when inferring the context for a derived instance. See Note [Overlap and deriving] in GHC.Tc.Deriv.Infer.Build a list of s, using the supplied  and % values for each ."Capture wanted constraints from a .Some common validity checks shared among stock derivable classes. One check that absolutely must hold is that if an instance C (T a) is being derived, then T must be a tycon for a data type or a newtype. The remaining checks are only performed if using a deriving) clause (i.e., they're ignored if using StandaloneDeriving): The data type must have at least one constructor (this check is ignored if using EmptyDataDeriving).0The data type cannot have any GADT constructors.The data type cannot have any constructors with existentially quantified type variables.+The data type cannot have a context (e.g., data Foo a = Eq a => MkFoo).8The data type cannot have fields with higher-rank types.For some classes (eg %, ,) we allow unlifted arg types by generating specialised code. For others (eg Data!) we don't. For even others (eg Lift7), unlifted types aren't even a special consideration!2Information about the type arguments to the class. if deriving an instance for this type is possible. Otherwise, it's  err, where err explains what went wrong.9Used to inform error messages as to whether we are in a deriving clause or a standalone deriving declaration0The specs from which constraints will be created? if this is standalone deriving with a user-supplied context,  if not. If it is the former, we relax some of the validity checks we would otherwise perform (i.e., "just go for it").M  = allow higher rank arguments and empty data types (with no data constructors) even in the absence of the -XEmptyDataDeriving extension.  !    '  :  NoneWLike #, but used only in the case of the stock deriving strategy. The constraints are inferred by inspecting the fields of each data constructor. In this example: 'data Foo = MkFoo Int Char deriving Show*We would infer the following constraints (s): (Show Int, Show Char)9Note that this function also returns the type variables (s) and class arguments (f>s) for the resulting instance. This is because when deriving *-like classes, we must sometimes perform kind substitutions to ensure the resulting instance is well kinded, which may affect the type variables and class arguments. In this example: newtype Compose (f :: k -> Type) (g :: Type -> k) (a :: Type) = Compose (f (g a)) deriving stock FunctorWe must unify k with Type in order for the resulting *+ instance to be well kinded, so we return []/ [Type, f, g] for the sfs, not [k] [k, f, g]-. See Note [Inferring the instance context].Like , but used only in the case of DeriveAnyClass, which gathers its constraints based on the type signatures of the class's methods instead of the types of the data constructor's field.See Note [Gathering and simplifying constraints for DeriveAnyClass] for an explanation of how these constraints are used to determine the derived instance context.Given instance (wanted) => C inst_ty , simplify wanted, as much as possible. Fail if not possible.1Needed constraints (after simplification), i.e. [].None &)+3Rebuild an application: takes a type-checked application head expression together with arguments in the form of typechecked s and returns a typechecked application of the head to the arguments.This performs a representation-polymorphism check to ensure that representation-polymorphic unlifted newtypes have been eta-expanded.4See Note [Eta-expanding rep-poly unlifted newtypes].the function being appliedthe arguments to the function88        None &'V.Type checker for a body of a match alternativeType-check a MatchGroup.checkArgCounts takes a [RenamedMatch]) and decides whether the same number of required (aka visible) args are used in each equation. Returns the arity, the number of required args E.g. f @a True y = ... f False z = ... The MatchGroup for f has arity 2, not 3Typecheck the alternative RHSSType of scrutineeThe case alternatives!Type of the whole case expressionExpected pattern types."Expected result-type of the Match.None /"'Arrow type constructor, of kind *->*->*•5Typechecking for case command alternatives. Used for U.ÕTypechecking for U and  HsCmdLamCase.ĕ2Type-checked Arrow class methods (arr, (>>>), ...)•Type of the scrutinee.case alternativesNone +3ŕReject any unsaturated use of an unlifted newtype constructor if the representation of its argument isn't known.4See Note [Eta-expanding rep-poly unlifted newtypes].ƕ;Type variables that must be instantiated to concrete types.See Note [Representation-polymorphism checking built-ins] in GHC.Tc.Utils.Concrete. Function type Argument typeǕArgumentType expected by the function        None 3!Slightly more general version of  that allows the caller to specify the shape of the result of the syntax operatorTypecheck a syntax operator The operator is a variable or a lambda at this stage (i.e. renamer output)tȕTypecheck an explicit tuple (a,b,c) or  (#a,b,c#).Does not handle tuple sections.ɕTypecheck an explicit tuple or tuple section by performing type inference.ʕExpands a record update $record_expr { fld1 = e1, fld2 = e2 } into a case expression that matches on the constructors of the record r), as described in Note [Record Updates].Returns a renamed but not-yet-typechecked expression, together with the result type of this expanded record update.˕Pretty-print a collection of lines, adding commas at the end of each line, and adding "and" to the start of the last line.̕+Disambiguate the fields in a record update.Most of the disambiguation has been done by the renamer; this function performs a final type-directed disambiguation pass, as explained in Note [Type-directed record disambiguation].͕=Checks if the given name is closed and emits an error if not.%See Note [Not-closed error messages]."shape of syntax operator argumentsoverall result typeType check any arguments, takes a type per hole and a multiplicity per arrow in the shape.ȕArgument types. This function ensures they all have a fixed runtime representation.ɕargument typesΕ/the operator to check (for error messages only)shape it is expected to havecheck the argumentsreturns a wrapper :: (type of right shape) "->" (type passed in)ϕ1the operator we are checking (for error messages)argument shapes result shapecheck the argumentsreturns a wrapper to be applied to the original function, wrappers to be applied to arguments and a wrapper to be applied to the overall expressionʕ record_expr2: expression to which the record update is appliedPossible parent /Ts for the record update, with the associated constructors and field labelsthe record update fields-the expected result type of the record updateffffffffffffffNone None )Check that the type has the form (IO t) or (t) , and that t satisfies the given predicate. When calling this function, any newtype wrappers (should) have been already dealt with by normaliseFfiType.We also check that the Safe Haskell condition of FFI imports having results in the IO monad holds.Е0Reason why a type in an FFI signature is invalidѕ&Check validity for a type of the form Any :: k.This function returns: Just IsValid for  Any :: Type and Any :: UnliftedType,Just (NotValid ..) for Any :: k if k is not a kind of boxed types,Nothing if the type is not Any.None %Stuff needed to process a datatype's  `deriving` clauses error context4Variables that scope over the deriving clause. See !Note [Scoped tyvars in a TcTyCon] in GHC.Core.TyCon.The data tycon for normal datatypes, or the *representation* tycon for data familiesҕ(Process the derived classes in a single deriving clause.ӕ Process a single predicate in a deriving clause.This returns a @& because the user might try to derive Typeable, which is a no-op nowadays.ԕ Generate the  for the required instance, plus any auxiliary bindings required (see Note [Auxiliary binders] in GHC.Tc.Deriv.Generate) and any additional free variables that should be marked (see +Note [Deriving and unused record selectors] in GHC.Tc.Deriv.Utils).ՕGenerate the associated type family instances for a derived instance.֕$The given deriving strategy, if any.The given deriving predicates of a deriving clause (for example 1 & % in deriving (Show, Eq)) along with the ו which we use to find out what deriving strategy was actually used. See comments of .ؕ$The given deriving strategy, if any.The standalone deriving declaration's signature for example, the: C a => C (T a) part of the standalone deriving instance: deriving instance C a => C (T a)3We extract the assumed deriving strategy from this.ҕThe location refers to the  (Show, Eq) part of deriving (Show, Eq).ٕIf , add a snippet about how not even GeneralizedNewtypeDeriving would make this declaration work. This only kicks in when an explicit deriving strategy is not given. #None )ڕGet the initial kind of a TyClDecl, either generalized or non-generalized, depending on the .ەMaybe return a list of Bools that say whether a type family was declared injective in the corresponding type arguments. Length of the list is equal to the number of arguments (including implicit kind/coercion arguments). True on position N means that a function is injective in its Nth argument. False means it is not.ܕProduce an "expected kind" for the arguments of a data/newtype. If the declaration is indeed for a newtype, then this expected kind will be the kind provided. Otherwise, it is OpenKind for datatypes and liftedTypeKind. Why do we not check for -XUnliftedNewtypes? See point  ErrorMessages. in Note [Implementation of UnliftedNewtypes]ݕFrom information about a source datacon definition, extract out what the universal variables and the GADT equalities should be. See Note [mkGADTVars].ޕ Check that a 9 is consistent with the one in the hs-boot file, if any.+See Note [TyCon boot consistency checking].ߕ Just cls  =* this is an associated family of class clsFamily TyCon (not knot-tied)DefaultsType checked RHSݕThe tycon varsThe datacon varsThe matching between the template result type and the actual result typeThe univ. variables, the GADT equalities, and a subst to apply to the GADT equalities and existentials.None Use DerivInfo for data family instances (produced by tcInstDecls1), datatype declarations (TyClDecl), and standalone deriving declarations (DerivDecl) to check and process all derived class instances.None s$Compares two things for equivalence between boot-file and normal code, reporting an error if they don't match up.3How should we infer a type? See Note [TcRnExprMode]-Instantiate inferred quantifiers only (:type)Instantiate all quantifiers, and do eager defaulting (:type +d)9A plan is an attempt to lift some code into the IO monad.Writer monad for accumulating errors when comparing an hs-boot or signature file with its implementing module.1Top level entry point for typechecker and renamerWarn about any imported default declaration that is not subsumed by either a local or an imported default declaration.Collapse a non-empty list of default declarations for the same class to the single declaration among them that subsumes all others, or to no declaration otherwise.Runs TH finalizers and renames and typechecks the top-level declarations that they could introduce.If the test in the first parameter is True, succeed. Otherwise, record the given error.Record an error.0A convenience synonym for a lack of errors, for  checkBootDecl and friends.>Map over the error types in an error-accumulating computation./Wrap up a list of errors into a single message.Compares the two things for equivalence between boot-file and normal code. Returns Nothing on success or !Just "some helpful info for user"; failure. If the difference will be apparent to the user,  Just empty is perfectly suitable.?Run the check provided for every pair of elements in the lists.Records an error:when any two items at the same position in the two lists don't match according to the given function,(when the lists are of different lengths.=Check that two class methods have compatible type signatures./Check that two associated types are compatible.4Check that two functional dependencies are the same.0Check compatibility of two type family flavours.Check that two Ls are compatible.Check that two (s are compatible.=We are implementing an abstract data declaration of the form data T+ in a signature file, with a type synonym type T tvs = rhs in the implementing module.6This function checks that the implementation is valid: 0the type synonym T is nullary, i.e. tvs is null,rhs doesn't contain any type families, foralls, or qualified types.+See Note [Synonyms implement abstract data]5Is this type a valid implementation of abstract data?0Returns a list of invalid sub-types encountered.Get the unqualified name of the function to use as the "main" for the main module. Either returns the default name or the one configured on the command line with -main-isThe returned [Id] is the list of new Ids bound by this statement. It can be used to extend the InteractiveContext via extendInteractiveContext.The returned TypecheckedHsExpr is of type IO [ Any ], a list of the bound values, coerced to Any.Try the plans in order. If one fails (by raising an exn), try the next. If one succeeds, take it.Typecheck (and lift4) a stmt entered by the user in GHCi into the GHCi  environment.By lift and 'environment we mean that the code is changed to execute properly in an IO monad. See Note [Interactively-bound Ids in GHCi] in GHC.Driver.Env for more details. We do this lifting by trying different ways (plans) of lifting the code into the IO monad and type checking each plan until one succeeds.Typecheck the statements given and then return the results of the statement in the form 'IO [Any]'.Generate a typed ghciStepIO expression (ghciStep :: Ty a -> IO a):tcRnExpr just finds the type of an expression for :type)ASSUMES that the module is either in the HomePackageTable or is a package module with an interface on disk. If neither of these is true, then the result will be an error indicating the interface could not be found.8Find all the Names that this RdrName could mean, in GHCi!Dump, with a banner, if -ddump-rn.Extract the renamed information from TcGblEnv. boot thing real thingtc1, the abstract data  we are implementingtc2, a type synonym type T tvs = ty we are using to implement tc1 tvs ty!! None This is a value of type a with potentially a CoreExpr-shaped hole in it. This is used to deal with cases where we are potentially handling pattern match failure, and want to later specify how failure is handled.We represent the case where there is no hole without a function from , like this, because sometimes we have nothing to put in the hole and so want to be sure there is in fact no hole.What to do after match0The rest of the equation after its first pattern!The first pattern of the equationNB: The location info is used to determine whether the pattern is generated or not. This helps us avoid warnings on patterns that GHC elaborated. NB: We have already applied decideBangHood0 to this pattern. See Note [decideBangHood] in GHC.HsToCore.UtilsRun a  action inside the  monad.Run a  action inside the D monad.5Build a set of desugarer environments derived from a .We have in hand the  for the module, but when doing pattern-match overlap checking we want the b* for each data constructor, not just its '. This function makes the transition.Run a & action in the context of an existing 0Get the current pattern match oracle state. See .Set the pattern match oracle state within the scope of the given action. See .Emit a diagnostic for the current source location. In case the diagnostic is a warning, the latter will be ignored and discarded if the relevant  is not set in the DynFlags. See Note [Discarding Messages] in  .Issue an error, but return the expression for (), so that we can continue reporting errors.The COMPLETE pragmas that are in scope.Inject a trace message into the compiled program. Whereas pprTrace prints out information *while compiling*, pprRuntimeTrace captures that information and causes it to be printed *at runtime* using Debug.Trace.trace.pprRuntimeTrace hdr doc expr*will produce an expression that looks liketrace (hdr + doc) exprWhen using this to debug a module that Debug.Trace depends on, it is necessary to import {-# SOURCE #-} Debug.Trace () in that module. We could avoid this inconvenience by wiring in Debug.Trace.trace, but that doesn't seem worth the effort and maintenance cost.See .Product is an "or" on fallibility---the combined match result is infallible only if the left and right argument match results both were.This is useful for combining a bunch of alternatives together and then getting the overall fallibility of the entire group. See  mkDataConCase for an example.headerinformation to output expression4"w v!4"w v!  5  #  !  !  None Generate a fresh  of a given type=All warning flags that need to run the pattern match checker.Check whether the redundancy checker should run (redundancy only)Check whether the exhaustiveness checker should run (exhaustiveness only)6Check whether unnecessary bangs should be warned aboutDenotes whether an exhaustiveness check is supported, and if so, via which  it's controlled. Returns K if check is not supported.Check whether any part of pattern match checking is enabled for this T (does not matter whether it is the redundancy check or the exhaustiveness check).7Check whether exhaustivity checks are enabled for this T1, when dealing with a single pattern (using the matchSinglePatVar function).4Return True when any of the pattern match warnings () are enabled, in which case we need to run the pattern match checker.  None)04)See Note [Case split inhabiting patterns]A high-level pattern-match constraint. Corresponds to  from Figure 3 of the LYG paper.A type constraint "T ~ U". PhiCoreCt x e encodes "x ~ e", equating x with the  e.PhiConCt x K tvs dicts ys encodes K @tvs dicts ys <- x , matching x against the  application K @tvs dicts ys , binding tvs, dicts and possibly unlifted fields ys in the process. See Note [Strict fields and variables of unlifted type].PhiNotConCt x K! encodes "x D K", asserting that x can't be headed by K. PhiBotCt x encodes "x ~ E", equating x to E. by K.PhiNotBotCt x y! encodes "x D E", asserting that x can't be E.The return value of  was able to simplify the type with some local constraint from the type oracle, but [! couldn't identify a type redex.5 may or may not been able to simplify the type, but [ made progress either way and got rid of at least one outermost type or data family redex or newtype. The first field is the last type that was reduced solely through type family applications (possibly just the d type). This is the one that is equal (in source Haskell) to the initial type. The third field is the type that we get when also looking through data family applications and newtypes. This would be the representation type in Core (modulo casts). The second field is the list of Newtype (s that we looked through in the chain of reduction steps between the Source type and the Core type. We also keep the type of the DataCon application and its field, so that we don't have to reconstruct it in inhabitationCandidates and 1. For an example, see Note [Type normalisation].Add a bunch of  s to all the ֳ s. Lifts  over many Գ.addPmCtsNablas for a single PmCt.Test if any of the ֳs is inhabited. Currently this is pure, because we preserve the invariant that there are no uninhabited ֳs. But that could change in the future, for example by implementing this function in terms of notNull  $ generateInhabitingPatterns 1 ds.Update the COMPLETE sets of , or K4 if there was no change as per the update function. A pseudo-1 for the vanilla complete set of the given data . Ex.: vanillaCompleteMatchTC @ ==> Just (Maybe, {L,K})Initialise from 1 (containing all COMPLETE pragmas) if the given  were empty.Adds the declared  from COMPLETE pragmas, as well as the vanilla data defn if it is a (.Adds * the % from COMPLETE pragmas * and the vanilla  from the data  to the , if not already present.Return the fields of 3. Returns appropriate defaults in the other cases.Get rid of *outermost* (or toplevel) * type function redex * data family redex * newtypes Behaves like p, but instead of returning a coercion, it returns useful information for issuing pattern matching warnings. See Note [Type normalisation] for details. It also initially -s the type with the bag of local constraints.See % for the meaning of the return value.NB: Normalisation can potentially change kinds, if the head of the type is a type family with a variable result kind. I (Richard E) can't think of a way to cause trouble here, though.Returns M if the argument  is a fully saturated application of a closed type constructor.Closed type constructors are those with a fixed right hand side, as opposed to e.g. associated types. These are of particular interest for pattern-match coverage checking, because GHC can exhaustively consider all possible forms that values of a closed type can take on.Note that this function is intended to be used to check types of value-level patterns, so as a consequence, the = supplied as an argument to this function should be of kind Type.Normalise the given source type to WHNF. If it isn't already in WHNF () , it will normalise the type and then try to step through type family applications, but not data family applications or newtypes.(This is a pretty common case of calling  and it should be efficient. Is the source type in WHNF wrt. ?Returns False if the given type is not a TyCon application, or if the TyCon app head is a type family TyCon. (But not for data family TyCons!)The fuel for the inhabitation test. See Note [Fuel for the inhabitation test].Adds new constraints to ֳ and returns K# if that leads to a contradiction.0In terms of the paper, this function models the E_3 function in Figure 7 on batches of  constraints.Adds new type-level constraints by calling out to the type-checker via .'Add some extra type constraints to the г ; return K# if we find a contradiction (e.g.  Int ~ Bool).See Note [Pattern match warnings with insoluble Givens] in GHC.Tc.Solver.Allocates a fresh - name for PredTys.Adds a single higher-level  constraint by dispatching to the various oracle functions.In terms of the paper, this function amounts to the constructor constraint case of E_ in Figure 7, which "desugars" higher-level  constraints into lower-level  constraints. We don't have a data type for  constraints and call the corresponding oracle function directly instead.Precondition: The  is not0 a type constraint! These should be handled by  before, through .Adds the constraint x ~ E', e.g. that evaluation of a particular  x$ surely diverges. Quite similar to #, only that it only cares about E.Adds the constraint x ~/ E to ֳ. Quite similar to *, but only cares for the E "constructor". Record a x ~/ K$ constraint, e.g. that a particular  x can't take the shape of a  K in the ֳ and return Nothing if that leads to a contradiction. See Note [TmState invariants].Add a x ~ K tvs args ts constraint. addConCt x K tvs args ts+ extends the substitution with a solution x :-> (K, tvs, args)? if compatible with the negative and positive info we have on x , reject (Nothing ) otherwise.See Note [TmState invariants].Adds a x ~ y constraint by merging the two ij&s and record the gained knowledge in ֳ.Returns Nothing5 when there's a contradiction while merging. Returns  Just nabla when the constraint was compatible with prior facts, in which case nabla; has integrated the knowledge from the equality constraint.See Note [TmState invariants]. Inspects a PmCoreCt  let x = e by recording constraints for x based on the shape of the  e . Examples:For let x = Just (42, z)( we want to record the constraints $x ~ Just a, a ~ (b, c), b ~ 42, c ~ z . See  data_con_app.For let x = unpackCString# "tmp"/ we want to record the literal constraint  x ~ "tmp".For  let x = I# 42 we want the literal constraint x ~ 42'. Similar for other literals. See .Finally, if we have  let x = e and we already have seen  let y = e, we want to record x ~ y.Like ', but with an effectful modifier actionFinds a representant of the semantic equality class of the given e. Which is the x of a  let x = e' constraint (with e semantically equivalent to e') we encountered earlier, or a fresh identifier if there weren't any such constraints. Change out s which are uniquely determined by their type to a common value, so that different names for dictionaries of the same type are considered equal when building a .6See Note [Unique dictionaries in the TmOracle CoreMap]Makes sure the given ֳ is still inhabited, by trying to instantiate all dirty variables (or all variables when the г1 changed) to concrete inhabitants. It returns a ֳ with the *same* inhabitants, but with some amount of work cached (like failed instantiation attempts) from the test.The  D E x inh, judgment form in Figure 8 of the LYG paper.Checks whether the given ij. needs to be tested for inhabitants. Returns J when we can skip the inhabitation test, presuming it would say "yes" anyway. See Note [Shortcutting the inhabitation test].Returns (Just vi) if at least one member of each ConLike in the COMPLETE set satisfies the oracle9Internally uses and updates the CompleteMatchs in vi_rcm. NB: Does not filter each CompleteMatch with the oracle; members may remain that do not satisfy it. This lazy approach just avoids doing unnecessary work.The E_{Bot} rule from the paperDoes a . and then tries to look through a data family application to find the representation TyCon, to which the data constructors are attached. Returns the representation TyCon, the TyCon application args and a representational coercion that will be Refl for non-data family apps.This is the |-Inst rule from the paper (section 4.5). Tries to find an inhabitant in every complete set by instantiating with one their constructors. If there is any complete set where we can't find an inhabitant, the whole thing is uninhabited. It returns the updated ij where all the attempted ConLike instantiations have been purged from the , which functions as a cache. instCompleteSet fuel nabla x cls iterates over cls5 until it finds the first inhabited ConLike (as per ). Any failed instantiation attempts of a ConLike are recorded as negative information in the returned ֳ, so that later calls to this function can skip repeatedly fruitless instantiation of that same constructor.Note that the returned Nabla is just a different representation of the original Nabla, not a proper refinement! No positive information will be added, only negative information from failed instantiation attempts, entirely as an optimisation.Is this ( trivially inhabited, that is, without needing to perform any inhabitation testing because of strict/unlifted fields or type equalities? See Note [DataCons that are definitely inhabitable]'All these types are trivially inhabited"instCon fuel nabla (x::match_ty) K tries to instantiate x to K. by adding the proper constructor constraint.#See Note [Instantiating a ConLike].matchConLikeResTy _ _ ty K tries to match ty against the result type of K, res_ty. It returns a substitution s for K's universal tyvars such that  s(res_ty) equals ty if successful.Make sure that ty is normalised before.2See Note [Matching against a ConLike result type].%generateInhabitingPatterns vs n nabla returns a list of at most n% (but perhaps empty) refinements of nabla that represent inhabited patterns. Negative information is only retained if literals are involved or for recursive GADTs.>If multiple residual COMPLETE sets apply, pick one as follows:prefer COMPLETE sets in which all constructors are in scope, as per Note [Prefer in-scope COMPLETE matches],if there are ties, pick the one with the fewest (residual) ConLikes,if there are ties, pick the one with the fewest "trivially inhabited" types,8if there are ties, pick the one with the fewest PatSyns,if there are still ties, pick the one that comes first in the list of COMPLETE pragmas, which means the one that was brought into scope first.ڳֳԳճֳԳճڳ  +    3   None+*Coverage checking action. Can be composed  or .A ) representing a successful pattern-match. Composes s top-to-bottom: If a value falls through the resulting action, then it must fall through the first action and then through the second action. If a value matches the resulting action, then it either matches the first action or matches the second action. Basically the semantics of the LYG branching construct. Composes s left-to-right: If a value falls through the resulting action, then it either falls through the first action or through the second action. If a value matches the resulting action, then it must match the first action and then match the second action. Basically the semantics of the LYG guard construct.throttle limit old new returns old if the number of ֳs in new is exceeding the given limit and the old number of ֳ-s. See Note [Countering exponential blowup]. 0 0None Use -XStrict to add a ! or remove a ~ See Note [decideBangHood] Scrutinee Type of exp,Alternatives (bndrs *include* tyvars, dicts)ticks to add, possibly The patternWhere the pattern occurs(Expression to which the pattern is boundId the rhs is bound to, for desugaring strict binds (see Note [Desugar Strict binds] in GHC.HsToCore.Binds) and all the desugared bindsOriginal pattern77NoneNone#NoneNone5(Desugaring of JavaScript foreign importsNone Foreign callsNone None 'See Note [FractionalLit representation]Post-typechecker, the % field of an S8 contains (an expression for) the literal value itself.Emit warnings on overloaded integral literals which overflow the bounds implied by their type.Emit warnings on integral literals which overflow the bounds implied by their type.Emit warnings on integral literals which overflow the bounds implied by their type. Warns about  [2,3 .. 1] or [b .. a] which return the empty list. For numeric literals, only works for integral types, not floating point.See if the expression is an ( literal.If (, extract the value and type of the overloaded literal. See Note [Literals and the OverloadedLists extension]If (;, extract the value and type of the non-overloaded literal.5Extract the Char if the expression is a Char literal.Convert a pair (Integer, Type) to (Integer, Name) after eventually normalising the typeConvert a pair (Integer, Type) to (Integer, Name) without normalising the type'the literal value and name of its tycon!Type of the whole case expression All PgLits  None Guarded RHSs Type of RHSRefined pattern match checking models, one for the pattern part and one for each GRHS.None&+4.Smart constructor that eliminates trivial letsADT constructor pattern => no existentials, no local constraints Creates a  refining a match var of list type to a list, where list fields are matched against the incoming tagged s. For example: )mkListGrds "a" "[(x, True <- x),(y, !y)]" to 2"[(x:b) <- a, True <- x, (y:c) <- b, !y, [] <- c]" where b and c are freshly allocated in  mkListGrds and a is the match variable. Create a  refining a match variable to a .desugarPat _ x pat transforms pat into a 0, where the variable representing the match is x.-, but also select and return a new match var.-, but also select and return a new match var. desugarListPat _ x [p1, ..., pn] is basically 6desugarConPatOut _ x $(mkListConPatOuts [p1, ..., pn]> without ever constructing the  ConPatOuts.Desugar a constructor patternDesugar the non-empty Tes of a %..Desugar a guarded right-hand side to a single GrdTreeDesugar a guard statement to a %Desugar local bindings to a bunch of ! guards. Deals only with simple let or where bindings without any polymorphism, recursion, pattern bindings etc. See Note [Long-distance information for HsLocalBinds].Desugar a pattern guard pat  -e == let x = e; guards for pat <- xDesugar a boolean guard e ==> let x = e; True <- xNone+z7A datatype to accommodate the different call sites of –. Used for extracting Ös from a concrete ann through Ė:. Since this is only possible for a couple of well-known anns, this is a GADT.Ö TypeRep a  None  3 ҖConstruct the functions which will apply the relevant part of the QuoteWrapper to identifiers during desugaring.Ӗ+Represent result signature of a type familyԖRepresent result signature using a Maybe Kind. Used with data families, where the result signature can be either missing or a kind but never a named result variable.Ֆ1Represent injectivity annotation of a type family֖If a type implicitly quantifies its outermost type variables, return M if the list of implicitly bound type variables is empty. If a type explicitly quantifies its outermost type variables, always return M.This is used in various places to determine if a Template Haskell  should be headed by a ForallT or not.זIf a type explicitly quantifies its outermost type variables, return M if the list of explicitly bound type variables is empty. If a type implicitly quantifies its outermost type variables, always return M.This is used in various places to determine if a Template Haskell  should be headed by a ForallT or not.ؖ Represent a type variable binderٖ#Represent a type wrapped in a Maybeږ:Construct Core expression for Nothing of a given type nameۖ5Construct Core expression for Nothing of a given typeܖ:Store given Core expression in a Just of a given type nameݖ5Store given Core expression in a Just of a given typeޖTrue for a  type data declaration. See Note [Type data declarations] in GHC.Rename.Moduleږ%Name of the TyCon of the element typeۖThe element typeܖ%Name of the TyCon of the element typeݖThe element type , * None None $) matchSimply is a wrapper for  which deals with the situation where we want to match a single expression against a single pattern. It returns an expression.ߖ'Use this pattern synonym to match on a S.2N.B.: View patterns can occur inside HsExpansions.&The scrutinee the match id is bound to Scrutinee Match kind%Scaling factor of the case expressionPattern it should matchReturn this if it matchesReturn this if it doesn'tFor shadowing warning messages0Scrutinee(s) see Note [matchWrapper scrutinees]Matches being desugaredResults (usually passed to )Variables rep'ing the exprs we're matching with ^ See Note [Match Ids]^ Note that the Match Ids carry not only a name, but ^ also the multiplicity at which each column has been ^ type checked.Type of the case expression.Info about patterns, etc. (type synonym below)Desugared result!  None ['the desugared rhs of the bind statement S in (>>=) :: Q -> (R -> S) -> TNone /None ))Desugar a located typechecked expression.!Desugar a typechecked expression.+Helper function. You can use the result of  with ` for instance. & binds makes a single mutually-recursive bindings with all the rhs/lhs pairs in binds & binds makes one non-recursive binding for each rhs/lhs pairs in binds4The longest list length which we will desugar using build.This is essentially a magic number and its setting is unfortunate rather arbitrary. The idea here, as mentioned in Note [Desugaring explicit lists], is to avoid deforesting large static data into large(r) code. Ideally we'd want a smaller threshold with larger consumers and vice-versa, but we have no way of knowing what will be consuming our list in the desugaring impossible to set generally correctly.0The effect of reducing this number will be that build fusion is applied less often. From a runtime performance perspective, applying build more liberally on "moderately" sized lists should rarely hurt and will often it can only expose further optimization opportunities; if no fusion is possible it will eventually get rule-rewritten back to a list). We do, however, pay in compile time.This function desugars ~>: it eta-expands data constructors to make linear types work. b) where module B where import A -- ** module C where import A import BWhether or not we add or remove the import to A in B affects the orphan hash of B. But it shouldn't really affect the orphan hash of C. If we hashed only direct dependencies, there would be no way to tell that the net effect was a wash, and we'd be forced to recompile C and everything else.Creates cached lookup for the ֑ field of ModIface Hackily, we use "module" as the OccName for any module-level annotations the reason we need to recompile.The old item, if it exists--   !  "  7  "  %  &   $      NoneAre all implicit imports required to be safe for this Safe Haskell mode?Find object files corresponding to the transitive closure of given home modules and direct object files for pkg dependenciesNoneNoneFully instantiate an interface. Adds fingerprints and potentially code generator produced information.CmmCgInfos is not available when not generating code (-fno-code), or when not generating interface pragmas (-fomit-interface-pragmas). See also Note [Conveying CAF-info and LFInfo between modules] in GHC.StgToCmm.Types. Compress an ʑ8 and share as many values as possible, depending on the ( level. See Note [Sharing of ModIface].We compress the ʑ by serialising the ʑ to an in-memory byte array, and then deserialising it. The deserialisation will deduplicate certain values depending on the  level. See Note [Deduplication during iface binary serialisation] for how we do that.  ;  >             None /"Main entry point to the desugarer.None7The header for HIE files - Capital ASCII letters "HIE".Write a  to the given ., with a proper header and symbol tables for s and  s.Read a  from a . Can use an existing ٣. Allows you to specify which versions of hieFile to attempt to read. N* case returns the failing header versions.Read a  from a . Can use an existing ٣.None`getCasts from_rep to_rep` gives us a list of primops which when applied in order convert from_rep to to_rep. See Note [PrimRep based casting]None~A mapping from binders to the Ids they were expanded/renamed to.x :-> MultiVal [a,b,c] in rhoiff x's typePrimRep is not a singleton, or equivalently x's type is an unboxed tuple, sum or void.x :-> UnaryVal x'iff x's RepType is UnaryRep or equivalently x's type is not unboxed tuple, sum or void.So x :-> MultiVal [a] in rho means x is represented by singleton tuple.*x :-> MultiVal [] in rho means x is void.INVARIANT: OutStgArgs in the range only have NvUnaryTypes (i.e. no unboxed tuples, sums or voids)Extend the environment, checking the UnariseEnv invariant. The id is mapped to one or more things. See Note [UnariseEnv]Make alternatives that match on the tag of a sum (i.e. generate LitAlts for the tag):Build a unboxed sum term from arguments of an alternative.3Example, for (# x | #) :: (# (# #) | Int #) we call5mkUbxSum (# _ | #) [ [], [LiftedRep] ] [ voidPrimId ] which returns  1#, rubbish /Return a rubbish value for the given slot type.We use the following rubbish values: * Literals: 0 or 0.0 * Pointers: `ghc-prim:GHC.Prim.Panic.absentSumFieldError`(See Note [aBSENT_SUM_FIELD_ERROR_ID] in  GHC.Core.Make:MultiVal a function argument. Never returns an empty list.MultiVal a DataCon argument. Returns an empty list when argument is void.  None  Optional Stg-to-Stg passes. Common subexpression eliminationLambda lifting closure variables, trading stack/register allocation for heap allocationMandatory unarise pass, desugaring unboxed tuple and sum binders$Mandatory when compiling to bytecodeUseful for building up  getStgToDoIs a top-level (static) StgConApp allowed or not. If not, use dynamic allocation.This is typically used to support dynamic linking on Windows and the -fexternal-dynamic-refs flag. See GHC.Stg.Utils.allowTopLevelConApp.9Should we lint the STG at various stages of the pipeline?$Spec of what stg-to-stg passes to doextra vars in scope from GHCimodule being compiled input program00          ! #( *1None4Initialize STG pretty-printing options from DynFlags;Which Stg-to-Stg passes to run. Depends on flags, ways etc.Are we preparing for bytecode?None+'V. Return an D that hydrates Core bindings and compiles them to bytecode if the interface contains any, using the supplied type env for typechecking.Unlike +, this does not use lazy IO. Instead, the D is only evaluated (in  get_link_deps) when it is clear that it will be used immediately (because we're linking TH with -fprefer-byte-code0 in oneshot mode), and the result is cached in .4 needs the laziness because it is used to populate , which is done preemptively, in anticipation of downstream modules using the bytecode for TH in make mode, which might never happen./Initialize HscEnv from an optional top_dir pathlog warning in the monad, and if there are errors then throw a SourceError exception.Log warnings and throw errors, assuming the messages contain at least one error (e.g. coming from PFailed)