Apoorv Ingle pushed to branch wip/ani/T27156 at Glasgow Haskell Compiler / GHC

Commits:

18 changed files:

Changes:

  • changelog.d/T27156
    1
    +section: compiler
    
    2
    +issues: #27156
    
    3
    +mrs: !15868
    
    4
    +synopsis:
    
    5
    +  Refactor code, to perform expansions related to rebindable sytax in their own pass
    
    6
    +description:
    
    7
    +  Expansions for some constructs (HsIf, Record Dot Syntax, Sections)
    
    8
    +  was done in the renamer while for others it was done in
    
    9
    +  the type checker. This patch moves all the expansions out of the renamer into its own pass.
    
    10
    +  This patch changes the behavior of typed template haskell with rebindable syntax turned on.
    \ No newline at end of file

  • compiler/GHC/Hs/Expr.hs
    ... ... @@ -221,7 +221,9 @@ type instance XRecSel GhcTc = NoExtField
    221 221
     -- OverLabel not present in GhcTc pass; see GHC.Rename.Expr
    
    222 222
     -- Note [Handling overloaded and rebindable constructs]
    
    223 223
     type instance XOverLabel     GhcPs = SourceText
    
    224
    -type instance XOverLabel     GhcRn = SourceText
    
    224
    +type instance XOverLabel     GhcRn = ( SourceText              -- Needed for pretty printing
    
    225
    +                                     , RebindableSyntaxTable)  -- contains the fromLabel Name
    
    226
    +
    
    225 227
     type instance XOverLabel     GhcTc = DataConCantHappen
    
    226 228
     
    
    227 229
     -- ---------------------------------------------------------------------
    
    ... ... @@ -278,7 +280,7 @@ type instance XCase GhcRn = HsMatchContextRn
    278 280
     type instance XCase          GhcTc = HsMatchContextRn
    
    279 281
     
    
    280 282
     type instance XIf            GhcPs = AnnsIf
    
    281
    -type instance XIf            GhcRn = NoExtField
    
    283
    +type instance XIf            GhcRn = RebindableSyntaxTable -- NoRebindable <=> RebindableSyntax is off
    
    282 284
     type instance XIf            GhcTc = NoExtField
    
    283 285
     
    
    284 286
     type instance XMultiIf       GhcPs = (EpToken "if", EpToken "{", EpToken "}")
    
    ... ... @@ -294,7 +296,7 @@ type instance XDo GhcRn = NoExtField
    294 296
     type instance XDo            GhcTc = Type
    
    295 297
     
    
    296 298
     type instance XExplicitList  GhcPs = AnnList ()
    
    297
    -type instance XExplicitList  GhcRn = NoExtField
    
    299
    +type instance XExplicitList  GhcRn = RebindableSyntaxTable -- NoRebindable <=> RebindableSyntax is off
    
    298 300
     type instance XExplicitList  GhcTc = Type
    
    299 301
     -- GhcPs: ExplicitList includes all source-level
    
    300 302
     --   list literals, including overloaded ones
    
    ... ... @@ -308,8 +310,9 @@ type instance XRecordCon GhcPs = NoExtField
    308 310
     type instance XRecordCon     GhcRn = NoExtField
    
    309 311
     type instance XRecordCon     GhcTc = PostTcExpr   -- Instantiated constructor function
    
    310 312
     
    
    313
    +
    
    311 314
     type instance XRecordUpd     GhcPs = (EpToken "{", EpToken "}")
    
    312
    -type instance XRecordUpd     GhcRn = NoExtField
    
    315
    +type instance XRecordUpd     GhcRn = RebindableSyntaxTable -- NoRebindable <=> RebindableSyntaxTable is off
    
    313 316
     type instance XRecordUpd     GhcTc = DataConCantHappen
    
    314 317
       -- We desugar record updates in the typechecker.
    
    315 318
       -- See [Handling overloaded and rebindable constructs],
    
    ... ... @@ -341,16 +344,16 @@ type instance XLHsRecUpdLabels GhcTc = DataConCantHappen
    341 344
     type instance XLHsOLRecUpdLabels p = NoExtField
    
    342 345
     
    
    343 346
     type instance XGetField     GhcPs = NoExtField
    
    344
    -type instance XGetField     GhcRn = NoExtField
    
    347
    +type instance XGetField     GhcRn = RebindableSyntaxTable
    
    345 348
     type instance XGetField     GhcTc = DataConCantHappen
    
    346
    --- HsGetField is eliminated by the renamer. See [Handling overloaded
    
    347
    --- and rebindable constructs].
    
    349
    +-- HsGetField is eliminated by the expansion in GHC.Tc.Expand
    
    350
    +-- See [Handling overloaded and rebindable constructs].
    
    348 351
     
    
    349 352
     type instance XProjection     GhcPs = AnnProjection
    
    350
    -type instance XProjection     GhcRn = NoExtField
    
    353
    +type instance XProjection     GhcRn = RebindableSyntaxTable
    
    351 354
     type instance XProjection     GhcTc = DataConCantHappen
    
    352
    --- HsProjection is eliminated by the renamer. See [Handling overloaded
    
    353
    --- and rebindable constructs].
    
    355
    +-- HsProjection is eliminated by the expansion in GHC.Tc.Expand
    
    356
    +-- See [Handling overloaded and rebindable constructs].
    
    354 357
     
    
    355 358
     type instance XExprWithTySig GhcPs = TokDcolon
    
    356 359
     type instance XExprWithTySig GhcRn = NoExtField
    
    ... ... @@ -644,7 +647,7 @@ tupArgsPresent_maybe = traverse tupArgPresent_maybe
    644 647
     *                                                                      *
    
    645 648
     ********************************************************************* -}
    
    646 649
     
    
    647
    -type instance XXExpr GhcPs = DataConCantHappen
    
    650
    +type instance XXExpr GhcPs = XXExprGhcPs
    
    648 651
     type instance XXExpr GhcRn = XXExprGhcRn
    
    649 652
     type instance XXExpr GhcTc = XXExprGhcTc
    
    650 653
     -- XXExprGhcRn: see Note [Rebindable syntax and XXExprGhcRn] below
    
    ... ... @@ -657,6 +660,10 @@ type instance XXExpr GhcTc = XXExprGhcTc
    657 660
     *                                                                      *
    
    658 661
     ********************************************************************* -}
    
    659 662
     
    
    663
    +data XXExprGhcPs
    
    664
    +  = ReSynBinds ModuleName (HsExpr GhcPs)
    
    665
    +
    
    666
    +
    
    660 667
     -- See Note [Rebindable syntax and XXExprGhcRn]
    
    661 668
     -- See Note [Expanding HsDo with XXExprGhcRn] in `GHC.Tc.Gen.Do`
    
    662 669
     -- See Note [Typechecking by expansion: overview]
    
    ... ... @@ -673,6 +680,7 @@ data XXExprGhcRn
    673 680
                                -- See Note [Non-overloaded record field selectors] and
    
    674 681
                                -- Note [Record selectors in the AST]
    
    675 682
     
    
    683
    +
    
    676 684
     data XXExprGhcTc
    
    677 685
       = WrapExpr        -- Type and evidence application and abstractions
    
    678 686
           HsWrapper (HsExpr GhcTc)
    
    ... ... @@ -817,7 +825,7 @@ ppr_expr (HsHole x) = case (ghcPass @p, x) of
    817 825
       (GhcTc, (HoleError, _)) -> pprPrefixOcc unnamedHoleRdrName
    
    818 826
     ppr_expr (HsOverLabel s l) = case ghcPass @p of
    
    819 827
                    GhcPs -> helper s
    
    820
    -               GhcRn -> helper s
    
    828
    +               GhcRn -> helper (fst s)
    
    821 829
                    GhcTc -> dataConCantHappen s
    
    822 830
     
    
    823 831
         where helper :: SourceText -> SDoc
    
    ... ... @@ -1021,9 +1029,12 @@ ppr_expr (HsFunArr _ arr arg res)
    1021 1029
       = sep [ppr_lexpr arg, pprHsModifiedFunArr arr <+> ppr_lexpr res]
    
    1022 1030
     
    
    1023 1031
     ppr_expr (XExpr x) = case ghcPass @p of
    
    1032
    +  GhcPs -> ppr x
    
    1024 1033
       GhcRn -> ppr x
    
    1025 1034
       GhcTc -> ppr x
    
    1026 1035
     
    
    1036
    +instance Outputable XXExprGhcPs where
    
    1037
    +  ppr (ReSynBinds m e) = text "{{" <+> ppr m <+> text "}}" <+> ppr e
    
    1027 1038
     
    
    1028 1039
     ppr_hse :: forall p. (IsPass p) => HsExpansion (GhcPass p) -> SDoc
    
    1029 1040
     ppr_hse hse
    
    ... ... @@ -1080,10 +1091,14 @@ ppr_infix_expr (HsHole x) = Just $ pprInfixOcc $ case (ghcPass @p, x) of
    1080 1091
       (GhcTc, (HoleVar (L _ v), _)) -> v
    
    1081 1092
       _ -> unnamedHoleRdrName -- TODO: this is the HoleError case; this should print the source text instead of "_".
    
    1082 1093
     ppr_infix_expr (XExpr x)            = case ghcPass @p of
    
    1094
    +                                        GhcPs -> ppr_infix_expr_ps x
    
    1083 1095
                                             GhcRn -> ppr_infix_expr_rn x
    
    1084 1096
                                             GhcTc -> ppr_infix_expr_tc x
    
    1085 1097
     ppr_infix_expr _ = Nothing
    
    1086 1098
     
    
    1099
    +ppr_infix_expr_ps :: XXExprGhcPs -> Maybe SDoc
    
    1100
    +ppr_infix_expr_ps (ReSynBinds{}) = Nothing
    
    1101
    +
    
    1087 1102
     ppr_infix_expr_rn :: XXExprGhcRn -> Maybe SDoc
    
    1088 1103
     ppr_infix_expr_rn (ExpandedThingRn (HSE thing _)) = ppr_infix_hs_expansion thing
    
    1089 1104
     ppr_infix_expr_rn (HsRecSelRn f)            = Just (pprInfixOcc f)
    
    ... ... @@ -1174,9 +1189,13 @@ hsExprNeedsParens prec = go
    1174 1189
         go (HsQual{})                     = prec >= funPrec
    
    1175 1190
         go (HsFunArr{})                   = prec >= funPrec
    
    1176 1191
         go (XExpr x) = case ghcPass @p of
    
    1192
    +                     GhcPs -> go_x_ps x
    
    1177 1193
                          GhcTc -> go_x_tc x
    
    1178 1194
                          GhcRn -> go_x_rn x
    
    1179 1195
     
    
    1196
    +    go_x_ps :: XXExprGhcPs -> Bool
    
    1197
    +    go_x_ps (ReSynBinds _ e) = hsExprNeedsParens prec e
    
    1198
    +
    
    1180 1199
         go_x_tc :: XXExprGhcTc -> Bool
    
    1181 1200
         go_x_tc (WrapExpr _ e)                   = hsExprNeedsParens prec e
    
    1182 1201
         go_x_tc (ExpandedThingTc (HSE thing _))  = hsExpandedNeedsParens thing
    
    ... ... @@ -1264,7 +1283,8 @@ instance Outputable (HsPragE (GhcPass p)) where
    1264 1283
     {- Note [Rebindable syntax and XXExprGhcRn]
    
    1265 1284
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1266 1285
     We implement rebindable syntax (RS) support by performing an expansion
    
    1267
    -in the renamer. We transform GhcPs expressions and patterns affected by
    
    1286
    +right before typechecking and after renaming.
    
    1287
    +We transform GhcRn expressions and patterns affected by
    
    1268 1288
     RS into the appropriate expanded form, but **annotated with the original
    
    1269 1289
     expression/pattern**.
    
    1270 1290
     
    
    ... ... @@ -1297,7 +1317,7 @@ original 'if' expression around too, using the TTG
    1297 1317
     XExpr extension point to allow GHC to construct an
    
    1298 1318
     'XXExprGhcRn' value that will keep track of the original
    
    1299 1319
     expression in its first field, and the desugared one in the
    
    1300
    -second field. The resulting renamed AST would look like:
    
    1320
    +second field. The resulting expanded AST would look like:
    
    1301 1321
     
    
    1302 1322
         L locif (XExpr
    
    1303 1323
           (ExpandedThingRn (HSE
    
    ... ... @@ -1357,25 +1377,26 @@ tcl_in_gen_code Bool to False.
    1357 1377
     
    
    1358 1378
     ---
    
    1359 1379
     
    
    1360
    -An overview of the constructs that are desugared in this way is laid out in
    
    1380
    +An overview of the constructs that are expanded in this way is laid out in
    
    1361 1381
     Note [Handling overloaded and rebindable constructs] in GHC.Rename.Expr.
    
    1362 1382
     
    
    1363 1383
     A general recipe to follow this approach for new constructs could go as follows:
    
    1364 1384
     
    
    1365 1385
     - Remove any GhcRn-time SyntaxExpr extensions to the relevant constructor for your
    
    1366 1386
       construct, in HsExpr or related syntax data types.
    
    1367
    -- At renaming-time:
    
    1387
    +- At renaming-time (GHC.Tc.Gen.Rename.rnExpr) :
    
    1368 1388
         - take your original node of interest (HsIf above)
    
    1369 1389
         - rename its subexpressions/subpatterns (condition and true/false
    
    1370 1390
           branches above)
    
    1371 1391
         - construct the suitable "rebound"-and-renamed result (ifThenElse call
    
    1372 1392
           above), where the 'SrcSpan' attached to any _fabricated node_ (the
    
    1373 1393
           HsVar/HsApp nodes, above) is set to 'generatedSrcSpan'
    
    1394
    +- At Expansion time (GHC.Tc.Gen.Expand.tcExpand)
    
    1374 1395
         - take both the original node and that rebound-and-renamed result and wrap
    
    1375 1396
           them into an expansion construct:
    
    1376
    -        for expressions, XExpr (ExpandedThingRn <original node> <desugared>)
    
    1397
    +        for expressions, XExpr (ExpandedThingRn (HSE { hse_ctxt = <original node> hse_exp = <desugared> }))
    
    1377 1398
             for patterns, XPat (HsPatExpanded <original node> <desugared>)
    
    1378
    - - At typechecking-time:
    
    1399
    + - At typechecking-time (GHC.Tc.Gen.tcExpr):
    
    1379 1400
         - remove any logic that was previously dealing with your rebindable
    
    1380 1401
           construct, typically involving [tc]SyntaxOp, SyntaxExpr and friends.
    
    1381 1402
         - the XExpr (ExpandedThingRn ... ...) case in tcExpr already makes sure that we
    
    ... ... @@ -1482,6 +1503,14 @@ type instance XXCmd GhcTc = HsWrap HsCmd
    1482 1503
     type CmdSyntaxTable p = [(Name, HsExpr p)]
    
    1483 1504
     -- See Note [CmdSyntaxTable]
    
    1484 1505
     
    
    1506
    +-- | Syntax lookup table for rebindable constructs
    
    1507
    +data RebindableSyntaxTable = NoRebindable | Rebindable [(OccName, Name)]
    
    1508
    +-- See Note [RebindableSyntaxTable]
    
    1509
    +
    
    1510
    +isNoRebindable :: RebindableSyntaxTable -> Bool
    
    1511
    +isNoRebindable NoRebindable = True
    
    1512
    +isNoRebindable Rebindable{} = False
    
    1513
    +
    
    1485 1514
     {-
    
    1486 1515
     Note [CmdSyntaxTable]
    
    1487 1516
     ~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -1518,6 +1547,32 @@ is Less Cool because
    1518 1547
         typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
    
    1519 1548
     -}
    
    1520 1549
     
    
    1550
    +{-
    
    1551
    +Note [RebindableSyntaxTable]
    
    1552
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1553
    +During renaming of constructs that support rebindable syntax (eg. HsIf),
    
    1554
    +we store the function (eg. ifThenElse) in a rebindable syntax table. Then
    
    1555
    +in the the expansion phase, right before typechecking, we use the
    
    1556
    +function (eg. ifThenElse) to build the actual expression to be typechecked.
    
    1557
    +
    
    1558
    +Why do we need to do this?
    
    1559
    +The renamer identifies the free variables of the expressions to perform dependency analysis.
    
    1560
    +When rebindable sytax is turned on, we want to treat the expression
    
    1561
    +
    
    1562
    +      HsIf b e1 e2
    
    1563
    +
    
    1564
    +As if it is
    
    1565
    +
    
    1566
    +      ifThenElse b e1 e2
    
    1567
    +
    
    1568
    +Thus the renamer needs to return `ifThenElse` as a free variable.
    
    1569
    +
    
    1570
    +Rebindable syntax stores this `ifThenElse` name so that it can be
    
    1571
    +used to build the correct expanded expression in GHC.Tc.Gen.Expand.tcExpand.
    
    1572
    +
    
    1573
    +-}
    
    1574
    +
    
    1575
    +
    
    1521 1576
     data CmdTopTc
    
    1522 1577
       = CmdTopTc
    
    1523 1578
         -- | Nested tuple of inputs on the command's stack
    

  • compiler/GHC/Hs/Instances.hs
    ... ... @@ -355,6 +355,8 @@ deriving instance Data (RoleAnnotDecl GhcTc)
    355 355
     -- ---------------------------------------------------------------------
    
    356 356
     -- Data derivations from GHC.Hs.Expr -----------------------------------
    
    357 357
     
    
    358
    +deriving instance Data RebindableSyntaxTable -- maybe don't traverse?
    
    359
    +
    
    358 360
     deriving instance Data (FieldLabelStrings GhcPs)
    
    359 361
     deriving instance Data (FieldLabelStrings GhcRn)
    
    360 362
     deriving instance Data (FieldLabelStrings GhcTc)
    
    ... ... @@ -728,7 +730,7 @@ deriving instance Data (HsExpansion GhcTc)
    728 730
     deriving instance Data a => Data (WithUserRdr a)
    
    729 731
     
    
    730 732
     -- -------------------------------
    
    731
    ---------------------------------------
    
    733
    +deriving instance Data XXExprGhcPs
    
    732 734
     deriving instance Data XXExprGhcTc
    
    733 735
     deriving instance Data XXPatGhcTc
    
    734 736
     
    

  • compiler/GHC/Rename/Expr.hs
    ... ... @@ -3,6 +3,7 @@
    3 3
     {-# LANGUAGE MultiWayIf          #-}
    
    4 4
     {-# LANGUAGE TypeFamilies        #-}
    
    5 5
     {-# LANGUAGE ViewPatterns        #-}
    
    6
    +{-# LANGUAGE RecordWildCards     #-}
    
    6 7
     
    
    7 8
     {-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
    
    8 9
     
    
    ... ... @@ -39,7 +40,6 @@ import GHC.Rename.Unbound ( reportUnboundName )
    39 40
     import GHC.Rename.Splice  ( rnTypedBracket, rnUntypedBracket, rnTypedSplice
    
    40 41
                               , rnUntypedSpliceExpr, checkThLocalNameWithLift, checkThLocalNameNoLift )
    
    41 42
     import GHC.Rename.HsType
    
    42
    -import GHC.Rename.Lit
    
    43 43
     import GHC.Rename.Pat
    
    44 44
     
    
    45 45
     import GHC.Driver.DynFlags
    
    ... ... @@ -49,7 +49,6 @@ import GHC.Unit.Module ( isInteractiveModule )
    49 49
     
    
    50 50
     import GHC.Types.Basic (TypeOrKind (TypeLevel))
    
    51 51
     import GHC.Types.FieldLabel
    
    52
    -import GHC.Types.Id.Make
    
    53 52
     import GHC.Types.Name
    
    54 53
     import GHC.Types.Name.Set
    
    55 54
     import GHC.Types.Name.Reader
    
    ... ... @@ -72,7 +71,7 @@ import qualified GHC.LanguageExtensions as LangExt
    72 71
     import Control.Monad
    
    73 72
     import qualified Data.Foldable as Partial (maximum)
    
    74 73
     import Data.List (unzip4)
    
    75
    -import Data.List.NonEmpty ( NonEmpty(..), head, init, last, nonEmpty, scanl, tail )
    
    74
    +import Data.List.NonEmpty ( NonEmpty(..), head, nonEmpty, scanl, tail )
    
    76 75
     import Control.Arrow (first)
    
    77 76
     import Data.Ord
    
    78 77
     import Data.Array
    
    ... ... @@ -84,20 +83,34 @@ import Data.Foldable (toList)
    84 83
     
    
    85 84
     Nomenclature
    
    86 85
     -------------
    
    87
    -* Expansion (`HsExpr GhcRn -> HsExpr GhcRn`): expand between renaming and
    
    88
    -  typechecking, using the `XXExprGhcRn` constructor of `HsExpr`.
    
    89
    -* Desugaring (`HsExpr GhcTc -> Core.Expr`): convert the typechecked `HsSyn` to Core.  This is done in GHC.HsToCore
    
    86
    +* Expansion (`HsExpr GhcRn -> HsExpansion GhcRn`): expand after renaming and
    
    87
    +  right before typechecking, using the `XXExprGhcRn` constructor of `HsExpr`.
    
    88
    +* Desugaring (`HsExpr GhcTc -> Core.Expr`): convert the typechecked `HsSyn` to Core.
    
    89
    +  This is done in GHC.HsToCore
    
    90 90
     
    
    91 91
     
    
    92 92
     For overloaded constructs (overloaded literals, lists, strings), and
    
    93 93
     rebindable constructs (e.g. if-then-else), our general plan is this,
    
    94 94
     using overloaded labels #foo as an example:
    
    95 95
     
    
    96
    -* In the RENAMER: transform
    
    96
    +* In the RENAMER (GHC.Tc.Rename.rnExpr):
    
    97
    +  Identify if we need to transform the rebindable construct
    
    98
    +  and store the appropriate `fromLabel` function in the RebindableSyntaxTable
    
    99
    +  field associated with HsOverLabel.
    
    100
    +
    
    97 101
           HsOverLabel "foo"
    
    98
    -      ==> XExpr (ExpandedThingRn (HsOverLabel #foo)
    
    99
    -                                 (fromLabel `HsAppType` "foo"))
    
    102
    +      ==> HsOverLabel (Rebindable [("fromLabel", fromLabelClassOpName)]) "foo"
    
    103
    +
    
    104
    +* In the EXPANSION (GHC.Tc.Gen.Expand.tcExpand):
    
    105
    +  Expand the HsOverLabel to an Expanded expression
    
    106
    +  using the fromLabel function stored in the rebindable syntax table
    
    107
    +
    
    108
    +      HsOverLabel (Rebindable [("fromLabel", fromLabelClassOpName)]) "foo"
    
    109
    +      ==> XExpr (ExpandedThingRn HSE { hse_ctxt = (HsOverLabel #foo)
    
    110
    +                                     , hse_exp  = L genLoc (fromLabel `HsAppType` "foo") })
    
    111
    +
    
    100 112
       We write this more compactly in concrete-syntax form like this
    
    113
    +
    
    101 114
           #foo  ==>  fromLabel @"foo"
    
    102 115
     
    
    103 116
       Recall that in (ExpandedThingRn orig expanded), 'orig' is the original term
    
    ... ... @@ -107,16 +120,18 @@ using overloaded labels #foo as an example:
    107 120
     * In the TYPECHECKER: typecheck the expansion, in this case
    
    108 121
           fromLabel @"foo"
    
    109 122
       The typechecker (and desugarer) will never see HsOverLabel
    
    123
    +  See Note [Typechecking by expansion: overview]
    
    110 124
     
    
    111
    -In effect, the renamer does a bit of desugaring. Recall GHC.Hs.Expr
    
    112
    -Note [Rebindable syntax and XXExprGhcRn], which describes the use of XXExprGhcRn.
    
    125
    +In effect, the renamer stores the rebindable syntax functions (ifThenElse, fromLabel, etc).
    
    126
    +in the rebindable syntax table, the expander build the actual AST before typechecking.
    
    127
    +Recall GHC.Hs.Expr Note [Rebindable syntax and XXExprGhcRn], which describes the use of XXExprGhcRn.
    
    113 128
     
    
    114 129
     RebindableSyntax:
    
    115 130
       If RebindableSyntax is off we use the built-in 'fromLabel', defined in
    
    116 131
          GHC.Builtin.Names.fromLabelClassOpName
    
    117 132
       If RebindableSyntax if ON, we look up "fromLabel" in the environment
    
    118 133
          to get whichever one is in scope.
    
    119
    -This is accomplished by lookupSyntaxName, and it applies to all the
    
    134
    +This is accomplished by `lookupSyntaxName`, and it applies to all the
    
    120 135
     constructs below.
    
    121 136
     
    
    122 137
     See also Note [Handling overloaded and rebindable patterns] in GHC.Rename.Pat
    
    ... ... @@ -149,9 +164,6 @@ but several have a little bit of special treatment:
    149 164
       where `leftSection` and `rightSection` are representation-polymorphic
    
    150 165
       wired-in Ids. See Note [Left and right sections]
    
    151 166
     
    
    152
    -* To understand why expansions for `OpApp` is done in `GHC.Tc.Gen.Head.splitHsApps`
    
    153
    -  see Note [Doing XXExprGhcRn in the Renamer vs Typechecker] below.
    
    154
    -
    
    155 167
     * RecordUpd: we desugar record updates into case expressions,
    
    156 168
       in GHC.Tc.Gen.Expr.tcExpr.
    
    157 169
     
    
    ... ... @@ -172,8 +184,23 @@ but several have a little bit of special treatment:
    172 184
     
    
    173 185
       See Note [Record Updates] in GHC.Tc.Gen.Expr for more details.
    
    174 186
     
    
    175
    -  To understand Why is this done in the typechecker, and not in the renamer
    
    176
    -  see Note [Doing XXExprGhcRn in the Renamer vs Typechecker]
    
    187
    +  This expansion is done in the typechecker on the fly (`GHC.Tc.Gen.tcExpr`), (until #27160 is fixed)
    
    188
    +  and not in the renamer for two reasons:
    
    189
    +
    
    190
    +    - (Until we implement GHC proposal #366)
    
    191
    +      We need to know the type of the record to disambiguate its fields.
    
    192
    +
    
    193
    +    - We use the type signature of the data constructor to provide `IdSigs`
    
    194
    +      to the let-bound variables (x', y' in the example of
    
    195
    +      See Note [Handling overloaded and rebindable constructs]).
    
    196
    +      This is needed to accept programs such as
    
    197
    +
    
    198
    +          data R b = MkR { f :: (forall a. a -> a) -> (Int,b), c :: Int }
    
    199
    +          foo r = r { f = \ k -> (k 3, k 'x') }
    
    200
    +
    
    201
    +      in which an updated field has a higher-rank type.
    
    202
    +      See Wrinkle [Using IdSig] in Note [Record Updates] in GHC.Tc.Gen.Expr.
    
    203
    +
    
    177 204
     
    
    178 205
     * HsDo: We expand `HsDo` statements in `Ghc.Tc.Gen.Do`.
    
    179 206
     
    
    ... ... @@ -188,8 +215,22 @@ but several have a little bit of special treatment:
    188 215
                                           (return (f x))))
    
    189 216
     
    
    190 217
          See Note [Expanding HsDo with XXExprGhcRn] in `Ghc.Tc.Gen.Do` for more details.
    
    191
    -     To understand why is this done in the typechecker and not in the renamer.
    
    192
    -     See Note [Doing XXExprGhcRn in the Renamer vs Typechecker]
    
    218
    +
    
    219
    +    - The expansion for do block statements is done on the fly right before typechecking
    
    220
    +      in `GHC.Tc.Gen.Expand.tcExpand` using `GHC.Tc.Gen.Do.expandDoStmts`.
    
    221
    +      There are 2 main reasons:
    
    222
    +
    
    223
    +      1. During the renaming phase, we may not have all the constructor details `HsConDetails` populated in the
    
    224
    +         data structure. This would result in an inaccurate irrefutability analysis causing
    
    225
    +         the continuation lambda body to be wrapped with `fail` alternatives when not needed.
    
    226
    +         See Part 1. of Note [Expanding HsDo with XXExprGhcRn] (test pattern-fails.hs)
    
    227
    +
    
    228
    +      2. If the expansion is done on the fly during renaming, expressions that
    
    229
    +         have explicit type applications using (-XTypeApplciations) will not work (cf. Let statements expansion)
    
    230
    +         as the name freshening happens from the root of the AST to the leaves,
    
    231
    +         but the expansion happens in the opposite direction (from leaves to the root),
    
    232
    +         causing the renamer to miss the scoped type variables.
    
    233
    +
    
    193 234
     
    
    194 235
     Note [Overloaded labels]
    
    195 236
     ~~~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -209,66 +250,6 @@ type-applying to "foo", so we get
    209 250
     
    
    210 251
     And those inferred kind quantifiers will indeed be instantiated when we
    
    211 252
     typecheck the renamed-syntax call (fromLabel @"foo").
    
    212
    -
    
    213
    -Note [Doing XXExprGhcRn in the Renamer vs Typechecker]
    
    214
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    215
    -We expand some `HsExpr GhcRn` code at various places, usually, on the fly,
    
    216
    -depending on when it is more convenient. It may be beneficial to have a
    
    217
    -separate `HsExpr GhcRn -> HsExpr GhcRn` pass that does this expansion uniformly
    
    218
    -in the future when we have enough cases to cater for. For the time being,
    
    219
    -this note documents which language feature is expanded at which phase,
    
    220
    -and the reasons for doing so.
    
    221
    -
    
    222
    -  ** `HsIf` Expansions
    
    223
    -  --------------------
    
    224
    -  `HsIf` expansions are expanded in the Renamer becuase it is more convinent
    
    225
    -  to do so there and then not worry about it in the later stage.
    
    226
    -  `-XRebindableSyntax` is used to decide whether we use the `HsIf` or user defined if
    
    227
    -
    
    228
    -
    
    229
    -  ** `OpApp` Expansions
    
    230
    -  ---------------------
    
    231
    -  The typechecker turns `OpApp` into a use of `XXExprGhcRn`
    
    232
    -  on the fly, in `GHC.Tc.Gen.Head.splitHsApps`.
    
    233
    -  The language extension `RebindableSyntax` does not affect this behaviour.
    
    234
    -
    
    235
    -  It's a bit painful to transform `OpApp e1 op e2` to a `XXExprGhcRn`
    
    236
    -  form, because the renamer does precedence rearrangement after name
    
    237
    -  resolution. So the renamer leaves an `OpApp` as an `OpApp`.
    
    238
    -
    
    239
    -  ** Record Update Syntax `RecordUpd` Expansions
    
    240
    -  ----------------------------------------------
    
    241
    -  This is done in the typechecker on the fly (`GHC.Tc.Expr.tcExpr`), and not the renamer, for two reasons:
    
    242
    -
    
    243
    -    - (Until we implement GHC proposal #366)
    
    244
    -      We need to know the type of the record to disambiguate its fields.
    
    245
    -
    
    246
    -    - We use the type signature of the data constructor to provide `IdSigs`
    
    247
    -      to the let-bound variables (x', y' in the example of
    
    248
    -      Note [Handling overloaded and rebindable constructs] above).
    
    249
    -      This is needed to accept programs such as
    
    250
    -
    
    251
    -          data R b = MkR { f :: (forall a. a -> a) -> (Int,b), c :: Int }
    
    252
    -          foo r = r { f = \ k -> (k 3, k 'x') }
    
    253
    -
    
    254
    -      in which an updated field has a higher-rank type.
    
    255
    -      See Wrinkle [Using IdSig] in Note [Record Updates] in GHC.Tc.Gen.Expr.
    
    256
    -
    
    257
    -  ** `HsDo` Statement Expansions
    
    258
    -  -----------------------------------
    
    259
    -  The expansion for do block statements is done on the fly right before typechecking in `GHC.Tc.Gen.Expr`
    
    260
    -  using `GHC.Tc.Gen.Do.expandDoStmts`. There are 2 main reasons:
    
    261
    -
    
    262
    -  -  During the renaming phase, we may not have all the constructor details `HsConDetails` populated in the
    
    263
    -     data structure. This would result in an inaccurate irrefutability analysis causing
    
    264
    -     the continuation lambda body to be wrapped with `fail` alternatives when not needed.
    
    265
    -     See Part 1. of Note [Expanding HsDo with XXExprGhcRn] (test pattern-fails.hs)
    
    266
    -
    
    267
    -  -  If the expansion is done on the fly during renaming, expressions that
    
    268
    -     have explicit type applications using (-XTypeApplciations) will not work (cf. Let statements expansion)
    
    269
    -     as the name freshening happens from the root of the AST to the leaves,
    
    270
    -     but the expansion happens in the opposite direction (from leaves to the root),
    
    271
    -     causing the renamer to miss the scoped type variables.
    
    272 253
     -}
    
    273 254
     
    
    274 255
     {-
    
    ... ... @@ -345,12 +326,9 @@ rnExpr (HsHole h)
    345 326
     -- HsOverLabel: see Note [Handling overloaded and rebindable constructs]
    
    346 327
     rnExpr (HsOverLabel src v)
    
    347 328
       = do { (from_label, fvs) <- lookupSyntaxName fromLabelClassOpName
    
    348
    -       ; return ( mkExpandedExpr (HsOverLabel src v) $
    
    349
    -                  HsAppType noExtField (genLHsVar from_label) hs_ty_arg
    
    350
    -                , fvs ) }
    
    351
    -  where
    
    352
    -    hs_ty_arg = mkEmptyWildCardBndrs $ wrapGenSpan $
    
    353
    -                HsTyLit noExtField (HsString NoSourceText v)
    
    329
    +       ; let rs_table = Rebindable [(nameOccName fromLabelClassOpName, from_label)]
    
    330
    +       ; return (HsOverLabel (src, rs_table) v, fvs)
    
    331
    +       }
    
    354 332
     
    
    355 333
     rnExpr (HsLit x lit) | HsString src s <- lit
    
    356 334
       = do { opt_OverloadedStrings <- xoptM LangExt.OverloadedStrings
    
    ... ... @@ -372,10 +350,12 @@ rnExpr (HsOverLit x lit)
    372 350
                      return (HsApp noExtField (noLocA neg) (noLocA (HsOverLit x lit'))
    
    373 351
                             , fvs ) }
    
    374 352
     
    
    375
    -rnExpr (HsQualLit x lit) = do
    
    376
    -  ((lit', desugaredExpr), fvs) <- rnQualLit lit
    
    377
    -  let origExpr = HsQualLit x lit'
    
    378
    -  return (mkExpandedExpr origExpr desugaredExpr, fvs)
    
    353
    +rnExpr (HsQualLit x QualLit{..})
    
    354
    + = do { (funName, fvs) <- lookupNameWithQualifier fromStringName ql_mod
    
    355
    +      ; let ql_val' = case ql_val of
    
    356
    +                        HsQualString st s -> HsQualString st s
    
    357
    +      ; return (HsQualLit x (QualLit (L noAnn funName) ql_mod ql_val'), fvs)
    
    358
    +      }
    
    379 359
     
    
    380 360
     rnExpr (HsApp x fun arg)
    
    381 361
       = do { (fun',fvFun) <- rnLExpr fun
    
    ... ... @@ -419,19 +399,15 @@ rnExpr (HsGetField _ e f)
    419 399
      = do { (getField, fv_getField) <- lookupSyntaxName getFieldName
    
    420 400
           ; (e, fv_e) <- rnLExpr e
    
    421 401
           ; let f' = rnDotFieldOcc <$> f
    
    422
    -      ; return ( mkExpandedExpr
    
    423
    -                   (HsGetField noExtField e f')
    
    424
    -                   (mkGetField getField e (fmap (unLoc . dfoLabel) f'))
    
    425
    -               , fv_e `plusFN` fv_getField ) }
    
    402
    +            rs_table = Rebindable  [(nameOccName getFieldName, getField)]
    
    403
    +      ; return (HsGetField rs_table e f', fv_e `plusFN` fv_getField) }
    
    426 404
     
    
    427 405
     rnExpr (HsProjection _ fs)
    
    428
    -  = do { (getField, fv_getField) <- lookupSyntaxName getFieldName
    
    429
    -       ; circ <- lookupOccRn WL_TermVariable compose_RDR
    
    406
    +  = do { (getFieldName, fv_getField) <- lookupSyntaxName getFieldName
    
    407
    +       ; circName <- lookupOccRn WL_TermVariable compose_RDR
    
    430 408
            ; let fs' = NE.map rnDotFieldOcc fs
    
    431
    -       ; return ( mkExpandedExpr
    
    432
    -                    (HsProjection noExtField fs')
    
    433
    -                    (mkProjection getField circ $ NE.map (unLoc . dfoLabel) fs')
    
    434
    -                , unitFN circ `plusFN` fv_getField) }
    
    409
    +             rs_table = Rebindable  [(nameOccName getFieldName , getFieldName), (rdrNameOcc compose_RDR, circName)]
    
    410
    +       ; return (HsProjection rs_table fs', unitFN circName `plusFN` fv_getField) }
    
    435 411
     
    
    436 412
     ------------------------------------------
    
    437 413
     -- Template Haskell extensions
    
    ... ... @@ -494,15 +470,12 @@ rnExpr (ExplicitList _ exps)
    494 470
       = do  { (exps', fvs) <- rnExprs exps
    
    495 471
             ; opt_OverloadedLists <- xoptM LangExt.OverloadedLists
    
    496 472
             ; if not opt_OverloadedLists
    
    497
    -          then return  (ExplicitList noExtField exps', fvs)
    
    473
    +          then return  (ExplicitList NoRebindable exps', fvs)
    
    498 474
               else
    
    499 475
         do { (from_list_n_name, fvs') <- lookupSyntaxName fromListNName
    
    500
    -       ; loc <- getSrcSpanM -- See Note [Source locations for implicit function calls]
    
    501
    -       ; let rn_list  = ExplicitList noExtField exps'
    
    502
    -             lit_n    = mkIntegralLit (length exps)
    
    503
    -             hs_lit   = genHsIntegralLit lit_n
    
    504
    -             exp_list = genHsApps' (wrapGenSpan' loc from_list_n_name) [hs_lit, wrapGenSpan rn_list]
    
    505
    -       ; return ( mkExpandedExpr rn_list exp_list
    
    476
    +       ; let rs_table = Rebindable  [(nameOccName fromListNName, from_list_n_name)]
    
    477
    +             rn_list  = ExplicitList rs_table exps'
    
    478
    +       ; return ( rn_list
    
    506 479
                     , fvs `plusFN` fvs') } }
    
    507 480
     
    
    508 481
     rnExpr (ExplicitTuple _ tup_args boxity)
    
    ... ... @@ -546,7 +519,7 @@ rnExpr (RecordUpd { rupd_expr = L l expr, rupd_flds = rbinds })
    546 519
                         RegularRecUpdFields
    
    547 520
                         { xRecUpdFields = parents
    
    548 521
                         , recUpdFields  = flds }
    
    549
    -            ; return ( RecordUpd noExtField (L l e) upd_flds
    
    522
    +            ; return ( RecordUpd NoRebindable (L l e) upd_flds
    
    550 523
                          , fv_e `plusFN` fv_flds ) }
    
    551 524
     
    
    552 525
           -- 'OverloadedRecordUpdate' is in effect. Record dot update desugaring.
    
    ... ... @@ -561,13 +534,13 @@ rnExpr (RecordUpd { rupd_expr = L l expr, rupd_flds = rbinds })
    561 534
                ; (setField, fv_setField) <- lookupSyntaxName setFieldName
    
    562 535
                ; (e, fv_e) <- rnExpr expr
    
    563 536
                ; (us, fv_us) <- rnHsUpdProjs flds
    
    564
    -            ; let upd_flds = OverloadedRecUpdFields
    
    537
    +           ; let upd_flds = OverloadedRecUpdFields
    
    565 538
                                 { xOLRecUpdFields = noExtField
    
    566 539
                                 , olRecUpdFields  = us }
    
    567
    -            ; return ( mkExpandedExpr
    
    568
    -                         (RecordUpd noExtField (L l e) upd_flds)
    
    569
    -                         (mkRecordDotUpd getField setField (L l e) us)
    
    570
    -                        , plusFNs [fv_getField, fv_setField, fv_e, fv_us] ) }
    
    540
    +                 rs_table = Rebindable [(nameOccName getField, getField) , (nameOccName setField, setField)]
    
    541
    +           ; return (RecordUpd rs_table (L l e) upd_flds
    
    542
    +                    , plusFNs [fv_getField, fv_setField, fv_e, fv_us] )
    
    543
    +           }
    
    571 544
     
    
    572 545
     
    
    573 546
     rnExpr (ExprWithTySig _ expr pty)
    
    ... ... @@ -632,6 +605,12 @@ rnExpr (HsFunArr _ mult arg res)
    632 605
           _ -> False
    
    633 606
         oneType = noLocA $ HsVar noExtField $ noLocA $ noUserRdr oneDataConName
    
    634 607
     
    
    608
    +rnExpr (XExpr (ReSynBinds m e'))
    
    609
    +  =  do { traceRn "XExpr ReSynBinds" (text "module:" <+> ppr m)
    
    610
    +        ; rnExpr e' -- for now just return the renamed expression
    
    611
    +          -- TODO: Bring into scope top level environment of the module m
    
    612
    +        }
    
    613
    +
    
    635 614
     {-
    
    636 615
     ************************************************************************
    
    637 616
     *                                                                      *
    
    ... ... @@ -717,155 +696,20 @@ rnSection :: HsExpr GhcPs -> RnM (HsExpr GhcRn, FreeNames)
    717 696
     -- Also see Note [Handling overloaded and rebindable constructs]
    
    718 697
     
    
    719 698
     rnSection section@(SectionR x op expr)
    
    720
    -  -- See Note [Left and right sections]
    
    721 699
       = do  { (op', fvs_op)     <- rnLExpr op
    
    722 700
             ; (expr', fvs_expr) <- rnLExpr expr
    
    723 701
             ; checkSectionPrec InfixR section op' expr'
    
    724
    -        ; let rn_section = SectionR x op' expr'
    
    725
    -              ds_section = genHsApps rightSectionName [op',expr']
    
    726
    -        ; return ( mkExpandedExpr rn_section ds_section
    
    727
    -                 , fvs_op `plusFN` fvs_expr) }
    
    702
    +        ; return $ (SectionR x op' expr' , fvs_op `plusFN`  fvs_expr) }
    
    728 703
     
    
    729 704
     rnSection section@(SectionL x expr op)
    
    730
    -  -- See Note [Left and right sections]
    
    731 705
       = do  { (expr', fvs_expr) <- rnLExpr expr
    
    732 706
             ; (op', fvs_op)     <- rnLExpr op
    
    733 707
             ; checkSectionPrec InfixL section op' expr'
    
    734
    -        ; postfix_ops <- xoptM LangExt.PostfixOperators
    
    735
    -                        -- Note [Left and right sections]
    
    736
    -        ; let rn_section = SectionL x expr' op'
    
    737
    -              ds_section
    
    738
    -                | postfix_ops = HsApp noExtField op' expr'
    
    739
    -                | otherwise   = genHsApps leftSectionName
    
    740
    -                                   [wrapGenSpan $ HsApp noExtField op' expr']
    
    741
    -        ; return ( mkExpandedExpr rn_section ds_section
    
    742
    -                 , fvs_op `plusFN` fvs_expr) }
    
    708
    +        ; return $ (SectionL x expr' op', fvs_op `plusFN` fvs_expr) }
    
    743 709
     
    
    744 710
     rnSection other = pprPanic "rnSection" (ppr other)
    
    745 711
     
    
    746
    -{- Note [Left and right sections]
    
    747
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    748
    -Dealing with left sections (x *) and right sections (* x) is
    
    749
    -surprisingly fiddly.  We expand like this
    
    750
    -     (`op` e) ==> rightSection op e
    
    751
    -     (e `op`) ==> leftSection  (op e)
    
    752
    -
    
    753
    -Using an auxiliary function in this way avoids the awkwardness of
    
    754
    -generating a lambda, esp if `e` is a redex, so we *don't* want
    
    755
    -to generate `(\x -> op x e)`. See Historical
    
    756
    -Note [Desugaring operator sections]
    
    757
    -
    
    758
    -Here are their definitions:
    
    759
    -   leftSection :: forall r1 r2 n (a::TYPE r1) (b::TYPE r2).
    
    760
    -                  (a %n-> b) -> a %n-> b
    
    761
    -   leftSection f x = f x
    
    762
    -
    
    763
    -   rightSection :: forall r1 r2 r3 n1 n2 (a::TYPE r1) (b::TYPE r2) (c::TYPE r3).
    
    764
    -                   (a %n1 -> b %n2-> c) -> b %n2-> a %n1-> c
    
    765
    -   rightSection f y x = f x y
    
    766
    -
    
    767
    -Note the wrinkles:
    
    768
    -
    
    769
    -* We do /not/ use lookupSyntaxName, which would make left and right
    
    770
    -  section fall under RebindableSyntax.  Reason: it would be a user-
    
    771
    -  facing change, and there are some tricky design choices (#19354).
    
    772
    -  Plus, infix operator applications would be trickier to make
    
    773
    -  rebindable, so it'd be inconsistent to do so for sections.
    
    774
    -
    
    775
    -  TL;DR: we still use the renamer-expansion mechanism for operator
    
    776
    -  sections, but only to eliminate special-purpose code paths in the
    
    777
    -  renamer and desugarer.
    
    778
    -
    
    779
    -* leftSection and rightSection must be representation-polymorphic, to allow
    
    780
    -  (+# 4#) and (4# +#) to work. See
    
    781
    -  Note [Wired-in Ids for rebindable syntax] in GHC.Types.Id.Make.
    
    782
    -
    
    783
    -* leftSection and rightSection must be multiplicity-polymorphic.
    
    784
    -  (Test linear/should_compile/OldList showed this up.)
    
    785
    -
    
    786
    -* Because they are representation-polymorphic, we have to define them
    
    787
    -  as wired-in Ids, with compulsory inlining.  See
    
    788
    -  GHC.Types.Id.Make.leftSectionId, rightSectionId.
    
    789
    -
    
    790
    -* leftSection is just ($) really; but unlike ($) it is
    
    791
    -  representation-polymorphic in the result type, so we can write
    
    792
    -  `(x +#)`, say.
    
    793
    -
    
    794
    -* The type of leftSection must have an arrow in its first argument,
    
    795
    -  because (x `ord`) should be rejected, because ord does not take two
    
    796
    -  arguments
    
    797
    -
    
    798
    -* It's important that we define leftSection in an eta-expanded way,
    
    799
    -  (i.e. not leftSection f = f), so that
    
    800
    -      (True `undefined`) `seq` ()
    
    801
    -      = (leftSection (undefined True) `seq` ())
    
    802
    -  evaluates to () and not undefined
    
    803
    -
    
    804
    -* If PostfixOperators is ON, then we expand a left section like this:
    
    805
    -      (e `op`)  ==>   op e
    
    806
    -  with no auxiliary function at all.  Simple!
    
    807
    -
    
    808
    -* leftSection and rightSection switch on ImpredicativeTypes locally,
    
    809
    -  during Quick Look; see GHC.Tc.Gen.App.wantQuickLook. Consider
    
    810
    -  test DeepSubsumption08:
    
    811
    -     type Setter st t a b = forall f. Identical f => blah
    
    812
    -     (.~) :: Setter s t a b -> b -> s -> t
    
    813
    -     clear :: Setter a a' b (Maybe b') -> a -> a'
    
    814
    -     clear = (.~ Nothing)
    
    815
    -   The expansion look like (rightSection (.~) Nothing).  So we must
    
    816
    -   instantiate `rightSection` first type argument to a polytype!
    
    817
    -   Hence the special magic in App.wantQuickLook.
    
    818
    -
    
    819
    -Historical Note [Desugaring operator sections]
    
    820
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    821
    -This Note explains some historical trickiness in desugaring left and
    
    822
    -right sections.  That trickiness has completely disappeared now that
    
    823
    -we desugar to calls to 'leftSection` and `rightSection`, but I'm
    
    824
    -leaving it here to remind us how nice the new story is.
    
    825
    -
    
    826
    -Desugaring left sections with -XPostfixOperators is straightforward: convert
    
    827
    -(expr `op`) to (op expr).
    
    828
    -
    
    829
    -Without -XPostfixOperators it's a bit more tricky. At first it looks as if we
    
    830
    -can convert
    
    831
    -
    
    832
    -    (expr `op`)
    
    833
    -
    
    834
    -naively to
    
    835
    -
    
    836
    -    \x -> op expr x
    
    837
    -
    
    838
    -But no!  expr might be a redex, and we can lose laziness badly this
    
    839
    -way.  Consider
    
    840
    -
    
    841
    -    map (expr `op`) xs
    
    842
    -
    
    843
    -for example. If expr were a redex then eta-expanding naively would
    
    844
    -result in multiple evaluations where the user might only have expected one.
    
    845
    -
    
    846
    -So we convert instead to
    
    847
    -
    
    848
    -    let y = expr in \x -> op y x
    
    849
    -
    
    850
    -Also, note that we must do this for both right and (perhaps surprisingly) left
    
    851
    -sections. Why are left sections necessary? Consider the program (found in #18151),
    
    852
    -
    
    853
    -    seq (True `undefined`) ()
    
    854
    -
    
    855
    -according to the Haskell Report this should reduce to () (as it specifies
    
    856
    -desugaring via eta expansion). However, if we fail to eta expand we will rather
    
    857
    -bottom. Consequently, we must eta expand even in the case of a left section.
    
    858
    -
    
    859
    -If `expr` is actually just a variable, say, then the simplifier
    
    860
    -will inline `y`, eliminating the redundant `let`.
    
    861
    -
    
    862
    -Note that this works even in the case that `expr` is unlifted. In this case
    
    863
    -bindNonRec will automatically do the right thing, giving us:
    
    864
    -
    
    865
    -    case expr of y -> (\x -> op y x)
    
    866
    -
    
    867
    -See #18151.
    
    868
    -
    
    712
    +{-
    
    869 713
     Note [Reporting unbound names]
    
    870 714
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    871 715
     Faced with an out-of-scope `RdrName` there are two courses of action
    
    ... ... @@ -2839,77 +2683,16 @@ rnHsIf p b1 b2
    2839 2683
            ; (b1', fvB1) <- rnLExpr b1
    
    2840 2684
            ; (b2', fvB2) <- rnLExpr b2
    
    2841 2685
            ; let fvs_if = plusFNs [fvP, fvB1, fvB2]
    
    2842
    -             rn_if  = HsIf noExtField  p' b1' b2'
    
    2843
    -
    
    2844 2686
            -- Deal with rebindable syntax
    
    2845 2687
            ; mb_ite <- lookupIfThenElse
    
    2846 2688
            ; case mb_ite of
    
    2847 2689
                 Nothing  -- Non rebindable-syntax case
    
    2848
    -              -> return (rn_if, fvs_if)
    
    2690
    +              -> return (HsIf NoRebindable  p' b1' b2', fvs_if)
    
    2849 2691
     
    
    2850 2692
                 Just ite_name   -- Rebindable-syntax case
    
    2851
    -              -> do { let ds_if = genHsApps ite_name [p', b1', b2']
    
    2852
    -                          fvs   = plusFNs [fvs_if, unitFN ite_name]
    
    2853
    -                    ; return (mkExpandedExpr rn_if ds_if, fvs) } }
    
    2693
    +              -> do { let fvs   = plusFNs [fvs_if, unitFN ite_name]
    
    2694
    +                    ; return (HsIf (Rebindable [(rdrNameOcc $ mkVarUnqual (fsLit "ifThenElse"), ite_name)]) p' b1' b2', fvs) } }
    
    2854 2695
     
    
    2855
    ------------------------------------------
    
    2856
    --- Bits and pieces for RecordDotSyntax.
    
    2857
    ---
    
    2858
    --- See Note [Overview of record dot syntax] in GHC.Hs.Expr.
    
    2859
    -
    
    2860
    --- mkGetField arg field calculates a get_field @field arg expression.
    
    2861
    --- e.g. z.x = mkGetField z x = get_field @x z
    
    2862
    -mkGetField :: Name -> LHsExpr GhcRn -> LocatedAn NoEpAnns FieldLabelString -> HsExpr GhcRn
    
    2863
    -mkGetField get_field arg field = unLoc (head $ mkGet get_field (arg :| []) field)
    
    2864
    -
    
    2865
    --- mkSetField a field b calculates a set_field @field expression.
    
    2866
    --- e.g mkSetSetField a field b = set_field @"field" a b (read as "set field 'field' to a on b").
    
    2867
    --- NB: the order of aruments is specified by GHC Proposal 583: HasField redesign.
    
    2868
    -mkSetField :: Name -> LHsExpr GhcRn -> LocatedAn NoEpAnns FieldLabelString -> LHsExpr GhcRn -> HsExpr GhcRn
    
    2869
    -mkSetField set_field a (L _ (FieldLabelString field)) b =
    
    2870
    -  genHsApp (genHsApp (genHsVar set_field `genAppType` genHsTyLit field) b) a
    
    2871
    -
    
    2872
    -mkGet :: Name -> NonEmpty (LHsExpr GhcRn) -> LocatedAn NoEpAnns FieldLabelString -> NonEmpty (LHsExpr GhcRn)
    
    2873
    -mkGet get_field l@(r :| _) (L _ (FieldLabelString field)) =
    
    2874
    -  wrapGenSpan (genHsApp (genHsVar get_field `genAppType` genHsTyLit field) r) NE.<| l
    
    2875
    -
    
    2876
    -mkSet :: Name -> LHsExpr GhcRn -> (LocatedAn NoEpAnns FieldLabelString, LHsExpr GhcRn) -> LHsExpr GhcRn
    
    2877
    -mkSet set_field acc (field, g) = wrapGenSpan (mkSetField set_field g field acc)
    
    2878
    -
    
    2879
    --- mkProjection fields calculates a projection.
    
    2880
    --- e.g. .x = mkProjection [x] = getField @"x"
    
    2881
    ---      .x.y = mkProjection [.x, .y] = (.y) . (.x) = getField @"y" . getField @"x"
    
    2882
    -mkProjection :: Name -> Name -> NonEmpty FieldLabelString -> HsExpr GhcRn
    
    2883
    -mkProjection getFieldName circName (field :| fields) = foldl' f (proj field) fields
    
    2884
    -  where
    
    2885
    -    f :: HsExpr GhcRn -> FieldLabelString -> HsExpr GhcRn
    
    2886
    -    f acc field = genHsApps circName $ map wrapGenSpan [proj field, acc]
    
    2887
    -
    
    2888
    -    proj :: FieldLabelString -> HsExpr GhcRn
    
    2889
    -    proj (FieldLabelString f) = genHsVar getFieldName `genAppType` genHsTyLit f
    
    2890
    -
    
    2891
    --- mkProjUpdateSetField calculates functions representing dot notation record updates.
    
    2892
    --- e.g. Suppose an update like foo.bar = 1.
    
    2893
    ---      We calculate the function \a -> setField @"foo" a (setField @"bar" (getField @"foo" a) 1).
    
    2894
    -mkProjUpdateSetField :: Name -> Name -> LHsRecProj GhcRn (LHsExpr GhcRn) -> (LHsExpr GhcRn -> LHsExpr GhcRn)
    
    2895
    -mkProjUpdateSetField get_field set_field (L _ (HsFieldBind { hfbLHS = (L _ (FieldLabelStrings flds')), hfbRHS = arg } ))
    
    2896
    -  = let {
    
    2897
    -      ; flds = NE.map (fmap (unLoc . dfoLabel)) flds'
    
    2898
    -      ; final = last flds  -- quux
    
    2899
    -      ; fields = init flds   -- [foo, bar, baz]
    
    2900
    -      ; getters = \a -> foldl' (mkGet get_field) (a :| []) fields  -- Ordered from deep to shallow.
    
    2901
    -          -- [getField@"baz"(getField@"bar"(getField@"foo" a), getField@"bar"(getField@"foo" a), getField@"foo" a, a]
    
    2902
    -      ; zips = \a -> (final, head (getters a)) : zip (reverse fields) (tail (getters a)) -- Ordered from deep to shallow.
    
    2903
    -          -- [("quux", getField@"baz"(getField@"bar"(getField@"foo" a)), ("baz", getField@"bar"(getField@"foo" a)), ("bar", getField@"foo" a), ("foo", a)]
    
    2904
    -      }
    
    2905
    -    in (\a -> foldl' (mkSet set_field) arg (zips a))
    
    2906
    -          -- setField@"foo" (a) (setField@"bar" (getField @"foo" (a))(setField@"baz" (getField @"bar" (getField @"foo" (a)))(setField@"quux" (getField @"baz" (getField @"bar" (getField @"foo" (a))))(quux))))
    
    2907
    -
    
    2908
    -mkRecordDotUpd :: Name -> Name -> LHsExpr GhcRn -> [LHsRecUpdProj GhcRn] -> HsExpr GhcRn
    
    2909
    -mkRecordDotUpd get_field set_field exp updates = foldl' fieldUpdate (unLoc exp) updates
    
    2910
    -  where
    
    2911
    -    fieldUpdate :: HsExpr GhcRn -> LHsRecUpdProj GhcRn -> HsExpr GhcRn
    
    2912
    -    fieldUpdate acc lpu =  unLoc $ (mkProjUpdateSetField get_field set_field lpu) (wrapGenSpan acc)
    
    2913 2696
     
    
    2914 2697
     rnHsUpdProjs :: [LHsRecUpdProj GhcPs] -> RnM ([LHsRecUpdProj GhcRn], FreeNames)
    
    2915 2698
     rnHsUpdProjs us = do
    

  • compiler/GHC/Rename/Splice.hs
    ... ... @@ -141,9 +141,8 @@ rnTypedBracket e br_body
    141 141
            ; recordThUse
    
    142 142
     
    
    143 143
            ; traceRn "Renaming typed TH bracket" empty
    
    144
    -       ; (body', fvs_e) <- setThLevel (Brack cur_level RnPendingTyped) $ rnLExpr br_body
    
    145
    -       ; return (HsTypedBracket noExtField body', fvs_e)
    
    146
    -
    
    144
    +       ; (body, fvs_e) <- setThLevel (Brack cur_level RnPendingTyped) $ rnLExpr br_body
    
    145
    +       ; return (HsTypedBracket noExtField body, fvs_e)
    
    147 146
            }
    
    148 147
     
    
    149 148
     rnUntypedBracket :: HsExpr GhcPs -> HsQuote GhcPs -> RnM (HsExpr GhcRn, FreeNames)
    
    ... ... @@ -176,6 +175,7 @@ rnUntypedBracket e br_body
    176 175
              setThLevel (UntypedBrack cur_level ps_var) $
    
    177 176
                       rn_utbracket br_body
    
    178 177
            ; pendings <- readMutVar ps_var
    
    178
    +
    
    179 179
            ; return (HsUntypedBracket pendings body', fvs_e)
    
    180 180
     
    
    181 181
            }
    
    ... ... @@ -613,6 +613,13 @@ problems, but keeps it on while processing typed TH quotes.
    613 613
     
    
    614 614
     This note and approach originated in #18102.
    
    615 615
     
    
    616
    +The MR!15868 (#27156) moved all the expansion/rebindable syntax (RS) mechanism into its own pass,
    
    617
    +done after renaming and right before typechecking.
    
    618
    +Before this patch, only some constructs (if then else, overloaded labels) were
    
    619
    +expanded in the renamer, but some (Do statements and record updates) were done after
    
    620
    +the renamer. This meant that the treatment of rebindable syntax and typed template haskell was
    
    621
    +not uniform across constructs. The MR!15868 makes the treatement of RS uniform for all constructs.
    
    622
    +
    
    616 623
     -}
    
    617 624
     
    
    618 625
     {- Note [Delaying modFinalizers in untyped splices]
    

  • compiler/GHC/Tc/Gen/Do.hs
    ... ... @@ -238,9 +238,6 @@ See Note [Handling overloaded and rebindable constructs] in GHC.Rename.Expr
    238 238
     To disabmiguate desugaring (`HsExpr GhcTc -> Core.Expr`) we use the phrase expansion
    
    239 239
     (`HsExpr GhcRn -> HsExpr GhcRn`)
    
    240 240
     
    
    241
    -This expansion is done after renaming and before typechecking
    
    242
    -See Part 2. of Note [Doing XXExprGhcRn in the Renamer vs Typechecker] in `GHC.Rename.Expr`
    
    243
    -
    
    244 241
     Historical note START
    
    245 242
     ---------------------
    
    246 243
     In previous versions of GHC, the `do`-notation wasn't expanded before typechecking,
    

  • compiler/GHC/Tc/Gen/Expand.hs
    ... ... @@ -7,17 +7,34 @@
    7 7
     
    
    8 8
     module GHC.Tc.Gen.Expand( tcExpand ) where
    
    9 9
     
    
    10
    -import GHC.Prelude
    
    11
    -
    
    12
    -import {-# SOURCE #-} GHC.Tc.Gen.Splice( getUntypedSpliceBody )
    
    10
    +import GHC.Prelude hiding (last, init, tail)
    
    11
    +import GHC.Data.FastString
    
    13 12
     
    
    14 13
     import GHC.Hs
    
    15 14
     
    
    16 15
     import GHC.Tc.Utils.Monad
    
    17 16
     import GHC.Tc.Types.ErrCtxt
    
    17
    +import GHC.Tc.Gen.Do
    
    18
    +import {-# SOURCE #-} GHC.Tc.Gen.Splice( getUntypedSpliceBody )
    
    19
    +
    
    20
    +import GHC.Types.Name
    
    21
    +import GHC.Types.Name.Reader
    
    22
    +import GHC.Types.Id.Make
    
    23
    +import GHC.Types.SrcLoc
    
    24
    +import GHC.Types.SourceText ( SourceText(..) )
    
    25
    +
    
    26
    +import GHC.Builtin.Names
    
    18 27
     
    
    19 28
     import GHC.Rename.Utils
    
    20 29
     
    
    30
    +import GHC.Utils.Panic
    
    31
    +import GHC.Utils.Outputable
    
    32
    +
    
    33
    +import qualified Data.List.NonEmpty as NE ( map, head, (<|) )
    
    34
    +import Data.List.NonEmpty ( NonEmpty(..), init, last, tail )
    
    35
    +
    
    36
    +import qualified GHC.LanguageExtensions as LangExt
    
    37
    +
    
    21 38
     {- Note [Typechecking by expansion: overview]
    
    22 39
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    23 40
     For many constructs, rather than typechecking the user-written code
    
    ... ... @@ -32,12 +49,11 @@ Example: Typechecking the do expression. The typechecker looks (somewhat) like t
    32 49
     
    
    33 50
     The `expandDoStmts` replaces the HsDo { x <- e1; return x }
    
    34 51
     with something like
    
    35
    -   HSE { hse_ctxt = ExprCtxt e
    
    52
    +   HSE { hse_ctxt = ExprCtxt (HsDo { x <- e1; return x })
    
    36 53
            , hse_exp  = e1 >>= \ x -> x }
    
    37 54
     and we then typecheck the expression `e1 >>= \ x -> x`
    
    38 55
     
    
    39 56
     See also Note [Handling overloaded and rebindable constructs]
    
    40
    -     and Note [Doing XXExprGhcRn in the Renamer vs Typechecker]
    
    41 57
          and Note [Rebindable syntax and XXExprGhcRn]
    
    42 58
     
    
    43 59
     The Big Question is how to ensure that error messages mention
    
    ... ... @@ -101,8 +117,39 @@ Wrinkle (TBE1)
    101 117
     
    
    102 118
     -}
    
    103 119
     
    
    104
    ----------------
    
    120
    +-- See Note [Typechecking by expansion: overview]
    
    105 121
     tcExpand :: HsExpr GhcRn -> TcM (Maybe (HsExpansion GhcRn))
    
    122
    +
    
    123
    +------------------------------------------
    
    124
    +-- Overloaded labels
    
    125
    +tcExpand e@(HsOverLabel (_, Rebindable rs_table) v)
    
    126
    +  | Just fromLabelName <- lookup (nameOccName fromLabelClassOpName) rs_table
    
    127
    +  , let hs_ty_arg = mkEmptyWildCardBndrs $ wrapGenSpan $
    
    128
    +                      HsTyLit noExtField (HsString NoSourceText v)
    
    129
    +  = return $ Just $
    
    130
    +    HSE { hse_ctxt = ExprCtxt e
    
    131
    +        , hse_exp = wrapGenSpan $ HsAppType noExtField (genLHsVar fromLabelName) hs_ty_arg
    
    132
    +        }
    
    133
    +
    
    134
    +  | otherwise
    
    135
    +  = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find fromLabel in rs_table"
    
    136
    +                              , ppr e] )
    
    137
    +
    
    138
    +------------------------------------------
    
    139
    +-- Qualified Literals
    
    140
    +tcExpand e@(HsQualLit _ QualLit{ql_val = ql_val, ql_ext = (L _ fromStringName)})
    
    141
    +  = do { let hsLit = case ql_val of
    
    142
    +                        -- See Note [Implementation of QualifiedStrings]
    
    143
    +                        HsQualString st s -> HsString st s
    
    144
    +       ; return $ Just $
    
    145
    +         HSE { hse_ctxt = ExprCtxt e
    
    146
    +             , hse_exp = wrapGenSpan $ genHsApps fromStringName [genLHsLit hsLit]
    
    147
    +             }
    
    148
    +       }
    
    149
    +
    
    150
    +
    
    151
    +------------------------------------------
    
    152
    +-- Operator Applications
    
    106 153
     tcExpand e@(OpApp _ arg1 op arg2)
    
    107 154
       = return $ Just $
    
    108 155
         HSE { hse_ctxt = ExprCtxt e
    
    ... ... @@ -110,14 +157,327 @@ tcExpand e@(OpApp _ arg1 op arg2)
    110 157
       where
    
    111 158
         ap f a = wrapGenSpan (HsApp noExtField f a)
    
    112 159
     
    
    113
    -tcExpand (XExpr (ExpandedThingRn hse))
    
    114
    -  = return (Just hse)
    
    160
    +------------------------------------------
    
    161
    +-- If
    
    162
    +
    
    163
    +-- NoRebindable <=> rebindable is turned off
    
    164
    +--             so we typecheck the HsIf in tcExprNoExpand
    
    165
    +tcExpand (HsIf NoRebindable _ _ _ )
    
    166
    +  = return Nothing
    
    167
    +tcExpand e@(HsIf (Rebindable rs_table) p b1 b2)
    
    168
    +  | Just ifThenElseName <- lookup (rdrNameOcc $ mkVarUnqual (fsLit "ifThenElse")) rs_table
    
    169
    +  = return $ Just $
    
    170
    +    HSE { hse_ctxt = ExprCtxt e
    
    171
    +        , hse_exp = wrapGenSpan $ genHsApps ifThenElseName [p, b1, b2]
    
    172
    +        }
    
    173
    +  | otherwise
    
    174
    +  = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find ifThenElse in rs_table"
    
    175
    +                              , ppr e ])
    
    176
    +
    
    177
    +------------------------------------------
    
    178
    +-- Record dot syntax
    
    179
    +
    
    180
    +tcExpand e@(HsGetField (Rebindable rs_table) expr f)
    
    181
    + | Just getField <- lookup (nameOccName getFieldName) rs_table
    
    182
    + = return $ Just $
    
    183
    +   HSE { hse_ctxt = ExprCtxt e
    
    184
    +       , hse_exp = wrapGenSpan $ (mkGetField getField expr (fmap (unLoc . dfoLabel) f)) }
    
    185
    + | otherwise
    
    186
    + = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find getField in rs_table"
    
    187
    +                             , ppr e ])
    
    188
    +
    
    189
    +tcExpand e@(HsProjection (Rebindable rs_table) fs)
    
    190
    + | Just getField <- lookup (nameOccName getFieldName) rs_table
    
    191
    + , Just circ <- lookup (rdrNameOcc compose_RDR) rs_table
    
    192
    + = return $ Just $
    
    193
    +   HSE { hse_ctxt = ExprCtxt e
    
    194
    +       , hse_exp = wrapGenSpan $ (mkProjection getField circ $ NE.map (unLoc . dfoLabel) fs) }
    
    195
    + | otherwise
    
    196
    + = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find getField or circ in rs_table"
    
    197
    +                             , ppr e])
    
    198
    +
    
    199
    +
    
    200
    +tcExpand (RecordUpd NoRebindable _ _ ) = return Nothing -- until #27160 is fixed
    
    201
    +
    
    202
    +tcExpand e@(RecordUpd (Rebindable rs_table) (L l expr) (OverloadedRecUpdFields { olRecUpdFields = us}))
    
    203
    + | Just getField <- lookup (nameOccName getFieldName) rs_table
    
    204
    + , Just setField <- lookup (nameOccName setFieldName) rs_table
    
    205
    + = return $ Just $
    
    206
    +   HSE { hse_ctxt = ExprCtxt e
    
    207
    +       , hse_exp = wrapGenSpan $ mkRecordDotUpd getField setField (L l expr) us }
    
    208
    + | otherwise
    
    209
    + = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find getField or setfield in rs_table"
    
    210
    +                             , ppr e ])
    
    211
    +
    
    212
    +------------------------------------------
    
    213
    +-- Left and Right Sections
    
    214
    +
    
    215
    +tcExpand e@(SectionR _ op expr)
    
    216
    +  -- See Note [Left and right sections]
    
    217
    +  = return $ Just $
    
    218
    +    HSE { hse_ctxt = ExprCtxt e
    
    219
    +        , hse_exp  = wrapGenSpan $ genHsApps rightSectionName [op, expr] }
    
    220
    +
    
    221
    +tcExpand e@(SectionL _ expr op)
    
    222
    +  -- Note [Left and right sections]
    
    223
    +  = do { postfix_ops <- xoptM LangExt.PostfixOperators
    
    224
    +        ; let ds_section
    
    225
    +                | postfix_ops = HsApp noExtField op expr
    
    226
    +                | otherwise   = genHsApps leftSectionName
    
    227
    +                                   [wrapGenSpan $ HsApp noExtField op expr]
    
    228
    +        ; return $ Just $
    
    229
    +          HSE { hse_ctxt = ExprCtxt e
    
    230
    +              , hse_exp = wrapGenSpan ds_section } }
    
    231
    +
    
    232
    +------------------------------------------
    
    233
    +-- Explicit Lists
    
    234
    +
    
    235
    +tcExpand (ExplicitList NoRebindable _ )
    
    236
    +  = return Nothing -- rebindable syntax is off
    
    237
    +tcExpand e@(ExplicitList (Rebindable rs_table) exps)
    
    238
    +  | Just from_list_n_name <- lookup (nameOccName fromListNName) rs_table
    
    239
    +  = do { loc <- getSrcSpanM -- See Note [Source locations for implicit function calls]
    
    240
    +       ; let lit_n    = mkIntegralLit (length exps)
    
    241
    +             hs_lit   = genHsIntegralLit lit_n
    
    242
    +             exp_list = genHsApps' (wrapGenSpan' loc from_list_n_name)
    
    243
    +                           [hs_lit, wrapGenSpan (ExplicitList NoRebindable exps)]
    
    244
    +                                                               -- important to make it NoRebindable
    
    245
    +                                                               -- Or we will go into an infinite loop
    
    246
    +       ; return $ Just $
    
    247
    +         HSE { hse_ctxt = ExprCtxt e
    
    248
    +             , hse_exp = wrapGenSpan $ exp_list }
    
    249
    +       }
    
    250
    +   | otherwise
    
    251
    +   = pprPanic "tcExpand" (vcat [text "Should Never Happen: could not find fromListN in rs_table"
    
    252
    +                               , ppr e] )
    
    253
    +
    
    254
    +
    
    255
    +------------------------------------------
    
    256
    +-- Do statements
    
    257
    +
    
    258
    +tcExpand (HsDo _ do_or_lc stmts)
    
    259
    +  | DoExpr{} <- do_or_lc
    
    260
    +  -- ApplicativeDo are typechecked using tcDoStmts
    
    261
    +  = do isApplicativeDo <- xoptM LangExt.ApplicativeDo
    
    262
    +       if isApplicativeDo
    
    263
    +         then return Nothing -- to be fixed by #24406
    
    264
    +         -- Expand expression on the fly otherwise
    
    265
    +         -- See Note [Typechecking by expansion: overview]
    
    266
    +         else do { hse <- expandDoStmts do_or_lc stmts
    
    267
    +                 ; return (Just hse) }
    
    268
    +  | MDoExpr{} <- do_or_lc
    
    269
    +  = do hse <- expandDoStmts do_or_lc stmts
    
    270
    +       return (Just hse)
    
    271
    +  | otherwise
    
    272
    +  -- ListComp and MonadComp are handled by legacy tcDoStmts for now,
    
    273
    +  -- The ultimate goal is to handle them via expandDoStmts.
    
    274
    +  -- GHCiStmts are handled completely separate
    
    275
    +  = return Nothing
    
    276
    +
    
    277
    +------------------------------------------
    
    278
    +-- Template Haskell Splices
    
    115 279
     
    
    116 280
     tcExpand e@(HsUntypedSplice splice_res _)
    
    117 281
     -- See Note [Looking through Template Haskell splices in splitHsApps]
    
    118 282
       = do { fun <- getUntypedSpliceBody splice_res
    
    119 283
            ; return $ Just $
    
    120
    -         HSE { hse_ctxt = ExprCtxt e
    
    121
    -             , hse_exp  = wrapGenSpan fun } }
    
    284
    +             HSE { hse_ctxt = ExprCtxt e
    
    285
    +                 , hse_exp  = wrapGenSpan fun }
    
    286
    +       }
    
    287
    +
    
    288
    +------------------------
    
    289
    +-- XExpr
    
    290
    +-- Expansions are idempotent, XExprs do not expand again
    
    291
    +tcExpand (XExpr (ExpandedThingRn hse))
    
    292
    +  = return $ Just hse
    
    293
    +
    
    294
    +tcExpand _ = return $ Nothing
    
    295
    +
    
    122 296
     
    
    123
    -tcExpand _ = return Nothing
    297
    +
    
    298
    +{- Note [Left and right sections]
    
    299
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    300
    +Dealing with left sections (x *) and right sections (* x) is
    
    301
    +surprisingly fiddly.  We expand like this
    
    302
    +     (`op` e) ==> rightSection op e
    
    303
    +     (e `op`) ==> leftSection  (op e)
    
    304
    +
    
    305
    +Using an auxiliary function in this way avoids the awkwardness of
    
    306
    +generating a lambda, esp if `e` is a redex, so we *don't* want
    
    307
    +to generate `(\x -> op x e)`. See Historical
    
    308
    +Note [Desugaring operator sections]
    
    309
    +
    
    310
    +Here are their definitions:
    
    311
    +   leftSection :: forall r1 r2 n (a::TYPE r1) (b::TYPE r2).
    
    312
    +                  (a %n-> b) -> a %n-> b
    
    313
    +   leftSection f x = f x
    
    314
    +
    
    315
    +   rightSection :: forall r1 r2 r3 n1 n2 (a::TYPE r1) (b::TYPE r2) (c::TYPE r3).
    
    316
    +                   (a %n1 -> b %n2-> c) -> b %n2-> a %n1-> c
    
    317
    +   rightSection f y x = f x y
    
    318
    +
    
    319
    +Note the wrinkles:
    
    320
    +
    
    321
    +* We do /not/ use lookupSyntaxName, which would make left and right
    
    322
    +  section fall under RebindableSyntax.  Reason: it would be a user-
    
    323
    +  facing change, and there are some tricky design choices (#19354).
    
    324
    +  Plus, infix operator applications would be trickier to make
    
    325
    +  rebindable, so it'd be inconsistent to do so for sections.
    
    326
    +
    
    327
    +  TL;DR: we still use the renamer-expansion mechanism for operator
    
    328
    +  sections, but only to eliminate special-purpose code paths in the
    
    329
    +  renamer and desugarer.
    
    330
    +
    
    331
    +* leftSection and rightSection must be representation-polymorphic, to allow
    
    332
    +  (+# 4#) and (4# +#) to work. See
    
    333
    +  Note [Wired-in Ids for rebindable syntax] in GHC.Types.Id.Make.
    
    334
    +
    
    335
    +* leftSection and rightSection must be multiplicity-polymorphic.
    
    336
    +  (Test linear/should_compile/OldList showed this up.)
    
    337
    +
    
    338
    +* Because they are representation-polymorphic, we have to define them
    
    339
    +  as wired-in Ids, with compulsory inlining.  See
    
    340
    +  GHC.Types.Id.Make.leftSectionId, rightSectionId.
    
    341
    +
    
    342
    +* leftSection is just ($) really; but unlike ($) it is
    
    343
    +  representation-polymorphic in the result type, so we can write
    
    344
    +  `(x +#)`, say.
    
    345
    +
    
    346
    +* The type of leftSection must have an arrow in its first argument,
    
    347
    +  because (x `ord`) should be rejected, because ord does not take two
    
    348
    +  arguments
    
    349
    +
    
    350
    +* It's important that we define leftSection in an eta-expanded way,
    
    351
    +  (i.e. not leftSection f = f), so that
    
    352
    +      (True `undefined`) `seq` ()
    
    353
    +      = (leftSection (undefined True) `seq` ())
    
    354
    +  evaluates to () and not undefined
    
    355
    +
    
    356
    +* If PostfixOperators is ON, then we expand a left section like this:
    
    357
    +      (e `op`)  ==>   op e
    
    358
    +  with no auxiliary function at all.  Simple!
    
    359
    +
    
    360
    +* leftSection and rightSection switch on ImpredicativeTypes locally,
    
    361
    +  during Quick Look; see GHC.Tc.Gen.App.wantQuickLook. Consider
    
    362
    +  test DeepSubsumption08:
    
    363
    +     type Setter st t a b = forall f. Identical f => blah
    
    364
    +     (.~) :: Setter s t a b -> b -> s -> t
    
    365
    +     clear :: Setter a a' b (Maybe b') -> a -> a'
    
    366
    +     clear = (.~ Nothing)
    
    367
    +   The expansion look like (rightSection (.~) Nothing).  So we must
    
    368
    +   instantiate `rightSection` first type argument to a polytype!
    
    369
    +   Hence the special magic in App.wantQuickLook.
    
    370
    +
    
    371
    +Historical Note [Desugaring operator sections]
    
    372
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    373
    +This Note explains some historical trickiness in desugaring left and
    
    374
    +right sections.  That trickiness has completely disappeared now that
    
    375
    +we desugar to calls to 'leftSection` and `rightSection`, but I'm
    
    376
    +leaving it here to remind us how nice the new story is.
    
    377
    +
    
    378
    +Desugaring left sections with -XPostfixOperators is straightforward: convert
    
    379
    +(expr `op`) to (op expr).
    
    380
    +
    
    381
    +Without -XPostfixOperators it's a bit more tricky. At first it looks as if we
    
    382
    +can convert
    
    383
    +
    
    384
    +    (expr `op`)
    
    385
    +
    
    386
    +naively to
    
    387
    +
    
    388
    +    \x -> op expr x
    
    389
    +
    
    390
    +But no!  expr might be a redex, and we can lose laziness badly this
    
    391
    +way.  Consider
    
    392
    +
    
    393
    +    map (expr `op`) xs
    
    394
    +
    
    395
    +for example. If expr were a redex then eta-expanding naively would
    
    396
    +result in multiple evaluations where the user might only have expected one.
    
    397
    +
    
    398
    +So we convert instead to
    
    399
    +
    
    400
    +    let y = expr in \x -> op y x
    
    401
    +
    
    402
    +Also, note that we must do this for both right and (perhaps surprisingly) left
    
    403
    +sections. Why are left sections necessary? Consider the program (found in #18151),
    
    404
    +
    
    405
    +    seq (True `undefined`) ()
    
    406
    +
    
    407
    +according to the Haskell Report this should reduce to () (as it specifies
    
    408
    +desugaring via eta expansion). However, if we fail to eta expand we will rather
    
    409
    +bottom. Consequently, we must eta expand even in the case of a left section.
    
    410
    +
    
    411
    +If `expr` is actually just a variable, say, then the simplifier
    
    412
    +will inline `y`, eliminating the redundant `let`.
    
    413
    +
    
    414
    +Note that this works even in the case that `expr` is unlifted. In this case
    
    415
    +bindNonRec will automatically do the right thing, giving us:
    
    416
    +
    
    417
    +    case expr of y -> (\x -> op y x)
    
    418
    +
    
    419
    +See #18151.
    
    420
    +-}
    
    421
    +
    
    422
    +
    
    423
    +
    
    424
    +
    
    425
    +
    
    426
    +-----------------------------------------
    
    427
    +-- Bits and pieces for RecordDotSyntax.
    
    428
    +--
    
    429
    +-- See Note [Overview of record dot syntax] in GHC.Hs.Expr.
    
    430
    +
    
    431
    +-- mkGetField arg field calculates a get_field @field arg expression.
    
    432
    +-- e.g. z.x = mkGetField z x = get_field @x z
    
    433
    +mkGetField :: Name -> LHsExpr GhcRn -> LocatedAn NoEpAnns FieldLabelString -> HsExpr GhcRn
    
    434
    +mkGetField get_field arg field = unLoc (NE.head $ mkGet get_field (arg :| []) field)
    
    435
    +
    
    436
    +-- mkSetField a field b calculates a set_field @field expression.
    
    437
    +-- e.g mkSetSetField a field b = set_field @"field" a b (read as "set field 'field' to a on b").
    
    438
    +-- NB: the order of aruments is specified by GHC Proposal 583: HasField redesign.
    
    439
    +mkSetField :: Name -> LHsExpr GhcRn -> LocatedAn NoEpAnns FieldLabelString -> LHsExpr GhcRn -> HsExpr GhcRn
    
    440
    +mkSetField set_field a (L _ (FieldLabelString field)) b =
    
    441
    +  genHsApp (genHsApp (genHsVar set_field `genAppType` genHsTyLit field) b) a
    
    442
    +
    
    443
    +mkGet :: Name -> NonEmpty (LHsExpr GhcRn) -> LocatedAn NoEpAnns FieldLabelString -> NonEmpty (LHsExpr GhcRn)
    
    444
    +mkGet get_field l@(r :| _) (L _ (FieldLabelString field)) =
    
    445
    +  wrapGenSpan (genHsApp (genHsVar get_field `genAppType` genHsTyLit field) r) NE.<| l
    
    446
    +
    
    447
    +mkSet :: Name -> LHsExpr GhcRn -> (LocatedAn NoEpAnns FieldLabelString, LHsExpr GhcRn) -> LHsExpr GhcRn
    
    448
    +mkSet set_field acc (field, g) = wrapGenSpan (mkSetField set_field g field acc)
    
    449
    +
    
    450
    +-- mkProjection fields calculates a projection.
    
    451
    +-- e.g. .x = mkProjection [x] = getField @"x"
    
    452
    +--      .x.y = mkProjection [.x, .y] = (.y) . (.x) = getField @"y" . getField @"x"
    
    453
    +mkProjection :: Name -> Name -> NonEmpty FieldLabelString -> HsExpr GhcRn
    
    454
    +mkProjection getFieldName circName (field :| fields) = foldl' f (proj field) fields
    
    455
    +  where
    
    456
    +    f :: HsExpr GhcRn -> FieldLabelString -> HsExpr GhcRn
    
    457
    +    f acc field = genHsApps circName $ map wrapGenSpan [proj field, acc]
    
    458
    +
    
    459
    +    proj :: FieldLabelString -> HsExpr GhcRn
    
    460
    +    proj (FieldLabelString f) = genHsVar getFieldName `genAppType` genHsTyLit f
    
    461
    +
    
    462
    +-- mkProjUpdateSetField calculates functions representing dot notation record updates.
    
    463
    +-- e.g. Suppose an update like foo.bar = 1.
    
    464
    +--      We calculate the function \a -> setField @"foo" a (setField @"bar" (getField @"foo" a) 1).
    
    465
    +mkProjUpdateSetField :: Name -> Name -> LHsRecProj GhcRn (LHsExpr GhcRn) -> (LHsExpr GhcRn -> LHsExpr GhcRn)
    
    466
    +mkProjUpdateSetField get_field set_field (L _ (HsFieldBind { hfbLHS = (L _ (FieldLabelStrings flds')), hfbRHS = arg } ))
    
    467
    +  = let {
    
    468
    +      ; flds = NE.map (fmap (unLoc . dfoLabel)) flds'
    
    469
    +      ; final = last flds  -- quux
    
    470
    +      ; fields = init flds   -- [foo, bar, baz]
    
    471
    +      ; getters = \a -> foldl' (mkGet get_field) (a :| []) fields  -- Ordered from deep to shallow.
    
    472
    +          -- [getField@"baz"(getField@"bar"(getField@"foo" a), getField@"bar"(getField@"foo" a), getField@"foo" a, a]
    
    473
    +      ; zips = \a -> (final, NE.head (getters a)) : zip (reverse fields) (tail (getters a)) -- Ordered from deep to shallow.
    
    474
    +          -- [("quux", getField@"baz"(getField@"bar"(getField@"foo" a)), ("baz", getField@"bar"(getField@"foo" a)), ("bar", getField@"foo" a), ("foo", a)]
    
    475
    +      }
    
    476
    +    in (\a -> foldl' (mkSet set_field) arg (zips a))
    
    477
    +          -- setField@"foo" (a) (setField@"bar" (getField @"foo" (a))(setField@"baz" (getField @"bar" (getField @"foo" (a)))(setField@"quux" (getField @"baz" (getField @"bar" (getField @"foo" (a))))(quux))))
    
    478
    +
    
    479
    +mkRecordDotUpd :: Name -> Name -> LHsExpr GhcRn -> [LHsRecUpdProj GhcRn] -> HsExpr GhcRn
    
    480
    +mkRecordDotUpd get_field set_field exp updates = foldl' fieldUpdate (unLoc exp) updates
    
    481
    +  where
    
    482
    +    fieldUpdate :: HsExpr GhcRn -> LHsRecUpdProj GhcRn -> HsExpr GhcRn
    
    483
    +    fieldUpdate acc lpu =  unLoc $ (mkProjUpdateSetField get_field set_field lpu) (wrapGenSpan acc)

  • compiler/GHC/Tc/Gen/Expr.hs
    ... ... @@ -36,7 +36,6 @@ import GHC.Rename.Env ( addUsedGRE, getUpdFieldLbls )
    36 36
     import GHC.Tc.Gen.Expand( tcExpand )
    
    37 37
     import GHC.Tc.Gen.App
    
    38 38
     import GHC.Tc.Gen.Head
    
    39
    -import GHC.Tc.Gen.Do
    
    40 39
     import GHC.Tc.Gen.Bind        ( tcLocalBinds )
    
    41 40
     import GHC.Tc.Gen.HsType
    
    42 41
     import GHC.Tc.Gen.Arrow
    
    ... ... @@ -94,8 +93,6 @@ import GHC.Data.FastString (fastStringToShortText)
    94 93
     import Control.Monad
    
    95 94
     import qualified Data.List.NonEmpty as NE
    
    96 95
     
    
    97
    -import qualified GHC.LanguageExtensions as LangExt
    
    98
    -
    
    99 96
     {-
    
    100 97
     ************************************************************************
    
    101 98
     *                                                                      *
    
    ... ... @@ -299,11 +296,19 @@ tcCollectApp the_app res_ty
    299 296
            ; tcApp the_app fun args res_ty }
    
    300 297
     
    
    301 298
     ---------------
    
    302
    -tcExpr :: HsExpr GhcRn
    
    299
    +tcExpr, tcExprNoExpand :: HsExpr GhcRn
    
    303 300
            -> ExpRhoType   -- DeepSubsumption <=> when checking, this type
    
    304 301
                            --                     is deeply skolemised
    
    305 302
            -> TcM (HsExpr GhcTc)
    
    306 303
     
    
    304
    +tcExpr e res_ty
    
    305
    +-- See Note [Typechecking by expansion: overview]
    
    306
    +  = do { mb_hse <- tcExpand e
    
    307
    +       ; case mb_hse of
    
    308
    +           Just hse -> tcHsExpansion hse res_ty
    
    309
    +           Nothing  -> tcExprNoExpand e res_ty }
    
    310
    +
    
    311
    +
    
    307 312
     -- Use tcApp to typecheck applications, which are treated specially
    
    308 313
     -- by Quick Look.  Specifically:
    
    309 314
     --   - HsVar           lone variables, to ensure that they can get an
    
    ... ... @@ -324,46 +329,46 @@ tcExpr :: HsExpr GhcRn
    324 329
     -- expression and try to break them up further
    
    325 330
     -- and then call tcApp on the maximal application chain.
    
    326 331
     -- See Note [Application chains and heads] in GHC.Tc.Gen.App
    
    327
    -tcExpr e@(HsVar {})              res_ty = tcApp e e [] res_ty
    
    328
    -tcExpr e@(ExprWithTySig {})      res_ty = tcApp e e [] res_ty
    
    329
    -tcExpr e@(XExpr (HsRecSelRn{}))  res_ty = tcApp e e [] res_ty
    
    330
    -tcExpr e@(HsAppType {})          res_ty = tcCollectApp e res_ty
    
    331
    -tcExpr e@(HsApp {})              res_ty = tcCollectApp e res_ty
    
    332
    +tcExprNoExpand e@(HsVar {})              res_ty = tcApp e e [] res_ty
    
    333
    +tcExprNoExpand e@(ExprWithTySig {})      res_ty = tcApp e e [] res_ty
    
    334
    +tcExprNoExpand e@(XExpr (HsRecSelRn{}))  res_ty = tcApp e e [] res_ty
    
    335
    +tcExprNoExpand e@(HsAppType {})          res_ty = tcCollectApp e res_ty
    
    336
    +tcExprNoExpand e@(HsApp {})              res_ty = tcCollectApp e res_ty
    
    332 337
     
    
    333 338
     -- Typecheck an occurrence of an unbound Id
    
    334 339
     --
    
    335 340
     -- Some of these started life as a true expression hole "_".
    
    336 341
     -- Others might simply be variables that accidentally have no binding site.
    
    337
    -tcExpr (HsHole (HoleVar locc@(L _ occ))) res_ty
    
    342
    +tcExprNoExpand (HsHole (HoleVar locc@(L _ occ))) res_ty
    
    338 343
       = do { ty <- expTypeToType res_ty    -- Allow Int# etc (#12531)
    
    339 344
            ; her <- emitNewExprHole occ ty
    
    340 345
            ; tcEmitBindingUsage bottomUE   -- Holes fit any usage environment
    
    341 346
                                            -- (#18491)
    
    342 347
            ; return (HsHole (HoleVar locc, her))
    
    343 348
            }
    
    344
    -tcExpr (HsHole HoleError) _ =
    
    349
    +tcExprNoExpand (HsHole HoleError) _ =
    
    345 350
       panic "GHC.Tc.Gen.Expr: tcExpr: HoleError: Not implemented"
    
    346 351
     
    
    347
    -tcExpr e@(HsLit x lit) res_ty
    
    352
    +tcExprNoExpand e@(HsLit x lit) res_ty
    
    348 353
       = do { let lit_ty = hsLitType lit
    
    349 354
            ; tcWrapResult e (HsLit x (convertLit lit)) lit_ty res_ty }
    
    350 355
     
    
    351
    -tcExpr (HsPar x expr) res_ty
    
    356
    +tcExprNoExpand (HsPar x expr) res_ty
    
    352 357
       = do { expr' <- tcMonoLExprNC expr res_ty
    
    353 358
            ; return (HsPar x expr') }
    
    354 359
     
    
    355
    -tcExpr (HsPragE x prag expr) res_ty
    
    360
    +tcExprNoExpand (HsPragE x prag expr) res_ty
    
    356 361
       = do { expr' <- tcMonoLExpr expr res_ty
    
    357 362
            ; return (HsPragE x (tcExprPrag prag) expr') }
    
    358 363
     
    
    359
    -tcExpr (NegApp x expr neg_expr) res_ty
    
    364
    +tcExprNoExpand (NegApp x expr neg_expr) res_ty
    
    360 365
       = do  { (expr', neg_expr')
    
    361 366
                 <- tcSyntaxOp NegateOrigin neg_expr [SynAny] res_ty $
    
    362 367
                    \[arg_ty] [arg_mult] ->
    
    363 368
                    tcScalingUsage arg_mult $ tcCheckMonoExpr expr arg_ty
    
    364 369
             ; return (NegApp x expr' neg_expr') }
    
    365 370
     
    
    366
    -tcExpr e@(HsIPVar _ x) res_ty
    
    371
    +tcExprNoExpand e@(HsIPVar _ x) res_ty
    
    367 372
       = do { ip_ty <- newFlexiTyVarTy liftedTypeKind
    
    368 373
               -- Create a unification type variable of kind 'Type'.
    
    369 374
               -- (The type of an implicit parameter must have kind 'Type'.)
    
    ... ... @@ -378,7 +383,7 @@ tcExpr e@(HsIPVar _ x) res_ty
    378 383
                    (mkHsWrap wrap (mkHsVar (noLocA ip_op)))
    
    379 384
                    ip_ty res_ty }
    
    380 385
     
    
    381
    -tcExpr e@(HsLam x lam_variant matches) res_ty
    
    386
    +tcExprNoExpand e@(HsLam x lam_variant matches) res_ty
    
    382 387
       = do { (wrap, matches') <- tcLambdaMatches e lam_variant matches [] res_ty
    
    383 388
            ; return (mkHsWrap wrap $ HsLam x lam_variant matches') }
    
    384 389
     
    
    ... ... @@ -390,7 +395,7 @@ tcExpr e@(HsLam x lam_variant matches) res_ty
    390 395
     ************************************************************************
    
    391 396
     -}
    
    392 397
     
    
    393
    -tcExpr e@(HsOverLit _ lit) res_ty
    
    398
    +tcExprNoExpand e@(HsOverLit _ lit) res_ty
    
    394 399
       = -- See Note [Typechecking overloaded literals]
    
    395 400
         do { mb_res <- tcShortCutLit lit res_ty
    
    396 401
              -- See Note [Short cut for overloaded literals] in GHC.Tc.Utils.TcMType
    
    ... ... @@ -426,7 +431,7 @@ tricky:
    426 431
       We can only take this short-cut if rebindable syntax is off; see `tcShortCutLit`.
    
    427 432
     -}
    
    428 433
     
    
    429
    -tcExpr e@HsQualLit{} _ = pprPanic "tcExpr: HsQualLit" (ppr e)
    
    434
    +tcExprNoExpand e@HsQualLit{} _ = pprPanic "tcExpr: HsQualLit" (ppr e)
    
    430 435
     
    
    431 436
     {-
    
    432 437
     ************************************************************************
    
    ... ... @@ -436,18 +441,19 @@ tcExpr e@HsQualLit{} _ = pprPanic "tcExpr: HsQualLit" (ppr e)
    436 441
     ************************************************************************
    
    437 442
     -}
    
    438 443
     
    
    439
    --- Explicit lists [e1,e2,e3] have been expanded already in the renamer
    
    444
    +-- Explicit lists [e1,e2,e3] have been expanded already in tcExpand
    
    440 445
     -- The expansion includes an ExplicitList, but it is always the built-in
    
    441 446
     -- list type, so that's all we need concern ourselves with here.  See
    
    442 447
     -- GHC.Rename.Expr. Note [Handling overloaded and rebindable constructs]
    
    443
    -tcExpr (ExplicitList _ exprs) res_ty
    
    444
    -  = do  { res_ty <- expTypeToType res_ty
    
    448
    +tcExprNoExpand (ExplicitList x exprs) res_ty
    
    449
    +  = assert (isNoRebindable x) $
    
    450
    +    do  { res_ty <- expTypeToType res_ty
    
    445 451
             ; (coi, elt_ty) <- matchExpectedListTy res_ty
    
    446 452
             ; let tc_elt expr = tcCheckPolyExpr expr elt_ty
    
    447 453
             ; exprs' <- mapM tc_elt exprs
    
    448 454
             ; return $ mkHsWrapCo coi $ ExplicitList elt_ty exprs' }
    
    449 455
     
    
    450
    -tcExpr expr@(ExplicitTuple x tup_args boxity) res_ty
    
    456
    +tcExprNoExpand expr@(ExplicitTuple x tup_args boxity) res_ty
    
    451 457
       | all tupArgPresent tup_args
    
    452 458
       = do { let arity  = length tup_args
    
    453 459
                  tup_tc = tupleTyCon boxity arity
    
    ... ... @@ -478,7 +484,7 @@ tcExpr expr@(ExplicitTuple x tup_args boxity) res_ty
    478 484
     
    
    479 485
            ; tcWrapResultMono expr expr' act_res_ty res_ty }
    
    480 486
     
    
    481
    -tcExpr (ExplicitSum _ alt arity expr) res_ty
    
    487
    +tcExprNoExpand (ExplicitSum _ alt arity expr) res_ty
    
    482 488
       = do { let sum_tc = sumTyCon arity
    
    483 489
            ; res_ty <- expTypeToType res_ty
    
    484 490
            ; (coi, arg_tys) <- matchExpectedTyConApp sum_tc res_ty
    
    ... ... @@ -505,12 +511,12 @@ tcExpr (ExplicitSum _ alt arity expr) res_ty
    505 511
     ************************************************************************
    
    506 512
     -}
    
    507 513
     
    
    508
    -tcExpr (HsLet x binds expr) res_ty
    
    514
    +tcExprNoExpand (HsLet x binds expr) res_ty
    
    509 515
       = do  { (binds', expr') <- tcLocalBinds binds $
    
    510 516
                                  tcMonoLExpr expr res_ty
    
    511 517
             ; return (HsLet x binds' expr') }
    
    512 518
     
    
    513
    -tcExpr (HsCase ctxt scrut matches) res_ty
    
    519
    +tcExprNoExpand (HsCase ctxt scrut matches) res_ty
    
    514 520
       = do  {  -- We used to typecheck the case alternatives first.
    
    515 521
                -- The case patterns tend to give good type info to use
    
    516 522
                -- when typechecking the scrutinee.  For example
    
    ... ... @@ -532,13 +538,16 @@ tcExpr (HsCase ctxt scrut matches) res_ty
    532 538
             ; matches' <- tcCaseMatches ctxt tcBody (Scaled mult scrut_ty) matches res_ty
    
    533 539
             ; return (HsCase ctxt scrut' matches') }
    
    534 540
     
    
    535
    -tcExpr (HsIf x pred b1 b2) res_ty
    
    536
    -  = do { pred'    <- tcCheckMonoExpr pred boolTy
    
    541
    +tcExprNoExpand (HsIf x pred b1 b2) res_ty
    
    542
    +  -- HsIf in rebindable case would be expanded out so we would not
    
    543
    +  -- have a Just RebindableSyntaxTable here, only Nothing
    
    544
    +  = assert (isNoRebindable x) $
    
    545
    +    do { pred'    <- tcCheckMonoExpr pred boolTy
    
    537 546
            ; let res_ty' = adjustExpTypeForCaseBranches res_ty [b1,b2]
    
    538 547
            ; (u1,b1') <- tcCollectingUsage $ tcMonoLExpr b1 res_ty'
    
    539 548
            ; (u2,b2') <- tcCollectingUsage $ tcMonoLExpr b2 res_ty'
    
    540 549
            ; tcEmitBindingUsage (supUE u1 u2)
    
    541
    -       ; return (HsIf x pred' b1' b2') }
    
    550
    +       ; return (HsIf noExtField pred' b1' b2') }
    
    542 551
     
    
    543 552
     {-
    
    544 553
     Note [MultiWayIf linearity checking]
    
    ... ... @@ -564,32 +573,16 @@ If we add linear guards, this code will have to be revisited.
    564 573
     Not using 'sup' caused #23814.
    
    565 574
     -}
    
    566 575
     
    
    567
    -tcExpr (HsMultiIf _ alts) res_ty
    
    576
    +tcExprNoExpand (HsMultiIf _ alts) res_ty
    
    568 577
       = do { alts' <- tcGRHSNE IfAlt tcBody alts res_ty
    
    569 578
                       -- See Note [MultiWayIf linearity checking]
    
    570 579
            ; res_ty <- readExpType res_ty
    
    571 580
            ; return (HsMultiIf res_ty alts') }
    
    572 581
     
    
    573
    -tcExpr (HsDo _ do_or_lc stmts) res_ty
    
    574
    -  | DoExpr{} <- do_or_lc
    
    575
    -  -- ApplicativeDo are typechecked using tcDoStmts
    
    576
    -  = do isApplicativeDo <- xoptM LangExt.ApplicativeDo
    
    577
    -       if isApplicativeDo
    
    578
    -         then tcDoStmts do_or_lc stmts res_ty
    
    579
    -         -- Expand expression on the fly otherwise
    
    580
    -         -- See Note [Typechecking by expansion: overview]
    
    581
    -         else do { hse <- expandDoStmts do_or_lc stmts
    
    582
    -                 ; tcHsExpansion hse res_ty }
    
    583
    -  | MDoExpr{} <- do_or_lc
    
    584
    -  = do hse <- expandDoStmts do_or_lc stmts
    
    585
    -       tcHsExpansion hse res_ty
    
    586
    -  | otherwise
    
    587
    -  -- ListComp and MonadComp are handled by legacy tcDoStmts for now,
    
    588
    -  -- The ultimate goal is to handle them via expandDoStmts.
    
    589
    -  -- GHCiStmts are handled completely separate
    
    582
    +tcExprNoExpand (HsDo _ do_or_lc stmts) res_ty
    
    590 583
       = tcDoStmts do_or_lc stmts res_ty
    
    591 584
     
    
    592
    -tcExpr (HsProc x pat cmd) res_ty
    
    585
    +tcExprNoExpand (HsProc x pat cmd) res_ty
    
    593 586
       = do  { (pat', cmd', coi) <- tcProc pat cmd res_ty
    
    594 587
             ; return $ mkHsWrapCo coi (HsProc x pat' cmd') }
    
    595 588
     
    
    ... ... @@ -601,7 +594,7 @@ tcExpr (HsProc x pat cmd) res_ty
    601 594
     -- and wrap (static e) in a call to
    
    602 595
     --    fromStaticPtr :: IsStatic p => StaticPtr a -> p a
    
    603 596
     
    
    604
    -tcExpr (HsStatic _ expr) res_ty
    
    597
    +tcExprNoExpand (HsStatic _ expr) res_ty
    
    605 598
       = do  { res_ty          <- expTypeToType res_ty
    
    606 599
             ; (co, (p_ty, expr_ty)) <- matchExpectedAppTy res_ty
    
    607 600
             ; (expr', lie) <- captureConstraints $
    
    ... ... @@ -636,11 +629,11 @@ tcExpr (HsStatic _ expr) res_ty
    636 629
                        expr''
    
    637 630
             }
    
    638 631
     
    
    639
    -tcExpr (HsEmbTy _ _)      _ = failWith (TcRnIllegalTypeExpr TypeKeywordSyntax)
    
    640
    -tcExpr (HsQual _ _ _)     _ = failWith (TcRnIllegalTypeExpr ContextArrowSyntax)
    
    641
    -tcExpr (HsForAll _ _ _)   _ = failWith (TcRnIllegalTypeExpr ForallTelescopeSyntax)
    
    642
    -tcExpr (HsFunArr _ _ _ _) _ = failWith (TcRnIllegalTypeExpr FunctionArrowSyntax)
    
    643
    -tcExpr (HsStar _)         _ = failWith (TcRnIllegalTypeExpr StarKindSyntax)
    
    632
    +tcExprNoExpand (HsEmbTy _ _)      _ = failWith (TcRnIllegalTypeExpr TypeKeywordSyntax)
    
    633
    +tcExprNoExpand (HsQual _ _ _)     _ = failWith (TcRnIllegalTypeExpr ContextArrowSyntax)
    
    634
    +tcExprNoExpand (HsForAll _ _ _)   _ = failWith (TcRnIllegalTypeExpr ForallTelescopeSyntax)
    
    635
    +tcExprNoExpand (HsFunArr _ _ _ _) _ = failWith (TcRnIllegalTypeExpr FunctionArrowSyntax)
    
    636
    +tcExprNoExpand (HsStar _)         _ = failWith (TcRnIllegalTypeExpr StarKindSyntax)
    
    644 637
     
    
    645 638
     {-
    
    646 639
     ************************************************************************
    
    ... ... @@ -650,7 +643,7 @@ tcExpr (HsStar _) _ = failWith (TcRnIllegalTypeExpr StarKindSyntax)
    650 643
     ************************************************************************
    
    651 644
     -}
    
    652 645
     
    
    653
    -tcExpr expr@(RecordCon { rcon_con = L loc qcon@(WithUserRdr _ con_name)
    
    646
    +tcExprNoExpand expr@(RecordCon { rcon_con = L loc qcon@(WithUserRdr _ con_name)
    
    654 647
                            , rcon_flds = rbinds }) res_ty
    
    655 648
       = do  { con_like <- tcLookupConLike qcon
    
    656 649
     
    
    ... ... @@ -688,11 +681,11 @@ tcExpr expr@(RecordCon { rcon_con = L loc qcon@(WithUserRdr _ con_name)
    688 681
         orig = OccurrenceOf con_name
    
    689 682
     
    
    690 683
     -- Record updates via dot syntax are replaced by expanded expressions
    
    691
    --- in the renamer. See Note [Overview of record dot syntax] in
    
    684
    +-- in GHC.Tc.Expand. See Note [Overview of record dot syntax] in
    
    692 685
     -- GHC.Hs.Expr. This is why we match on 'rupd_flds = Left rbnds' here
    
    693 686
     -- and panic otherwise.
    
    694
    --- WIP: To be fixed soon expandRecordUpd needs to return HsExpansion and not a separate ds_res_ty
    
    695
    -tcExpr expr@(RecordUpd { rupd_expr = record_expr
    
    687
    +-- WIP: To be fixed soon (#27160) expandRecordUpd needs to return HsExpansion and not a separate ds_res_ty
    
    688
    +tcExprNoExpand expr@(RecordUpd { rupd_expr = record_expr
    
    696 689
                            , rupd_flds =
    
    697 690
                                RegularRecUpdFields
    
    698 691
                                  { xRecUpdFields = possible_parents
    
    ... ... @@ -719,7 +712,7 @@ tcExpr expr@(RecordUpd { rupd_expr = record_expr
    719 712
                  }
    
    720 713
             }
    
    721 714
     
    
    722
    -tcExpr e@(RecordUpd { rupd_flds = OverloadedRecUpdFields {}}) _
    
    715
    +tcExprNoExpand e@(RecordUpd { rupd_flds = OverloadedRecUpdFields {}}) _
    
    723 716
       = pprPanic "tcExpr: unexpected overloaded-dot RecordUpd" $ ppr e
    
    724 717
     
    
    725 718
     {-
    
    ... ... @@ -732,7 +725,7 @@ tcExpr e@(RecordUpd { rupd_flds = OverloadedRecUpdFields {}}) _
    732 725
     ************************************************************************
    
    733 726
     -}
    
    734 727
     
    
    735
    -tcExpr (ArithSeq _ witness seq) res_ty
    
    728
    +tcExprNoExpand (ArithSeq _ witness seq) res_ty
    
    736 729
       = tcArithSeq witness seq res_ty
    
    737 730
     
    
    738 731
     {-
    
    ... ... @@ -745,24 +738,20 @@ tcExpr (ArithSeq _ witness seq) res_ty
    745 738
     
    
    746 739
     -- Here we get rid of it and add the finalizers to the global environment.
    
    747 740
     -- See Note [Delaying modFinalizers in untyped splices] in GHC.Rename.Splice.
    
    748
    -tcExpr (HsTypedSplice ext splice)   res_ty = tcTypedSplice ext splice res_ty
    
    749
    -tcExpr e@(HsTypedBracket _ext body) res_ty = tcTypedBracket e body res_ty
    
    750
    -tcExpr e@(HsUntypedBracket ps body) res_ty = tcUntypedBracket e body ps res_ty
    
    741
    +tcExprNoExpand (HsTypedSplice ext splice)   res_ty = tcTypedSplice ext splice res_ty
    
    742
    +tcExprNoExpand e@(HsTypedBracket _ext body) res_ty = tcTypedBracket e body res_ty
    
    743
    +tcExprNoExpand e@(HsUntypedBracket ps body) res_ty = tcUntypedBracket e body ps res_ty
    
    751 744
     
    
    752 745
     {-
    
    753 746
     ************************************************************************
    
    754 747
     *                                                                      *
    
    755
    -                Catch-all
    
    748
    +                Catch all Case
    
    756 749
     *                                                                      *
    
    757 750
     ************************************************************************
    
    758 751
     -}
    
    759 752
     
    
    760
    --- See Note [Typechecking by expansion: overview]
    
    761
    -tcExpr e res_ty
    
    762
    -  = do { mb_hse <- tcExpand e
    
    763
    -       ; case mb_hse of
    
    764
    -           Just hse -> tcHsExpansion hse res_ty
    
    765
    -           Nothing  -> pprPanic "tcExpr: unhandled case:" (ppr e) }
    
    753
    +-- We ought to have expanded out or handeled them above
    
    754
    +tcExprNoExpand e _ = pprPanic "tcExpr : unhandled case" $ ppr e
    
    766 755
     
    
    767 756
     {-
    
    768 757
     ************************************************************************
    
    ... ... @@ -1656,7 +1645,7 @@ disambiguateRecordBinds record_expr record_rho possible_parents rbnds res_ty
    1656 1645
                                  RegularRecUpdFields
    
    1657 1646
                                   { xRecUpdFields = parents
    
    1658 1647
                                   , recUpdFields  = rbnds }
    
    1659
    -                         , rupd_ext = noExtField }
    
    1648
    +                         , rupd_ext = NoRebindable }
    
    1660 1649
             loc  = getLocA (head rbnds)
    
    1661 1650
     
    
    1662 1651
     {-
    

  • compiler/GHC/Tc/TyCl/PatSyn.hs
    ... ... @@ -1087,7 +1087,7 @@ tcPatToExpr args pat = go pat
    1087 1087
         go1 (ParPat _ pat) = fmap (HsPar noExtField) (go pat)
    
    1088 1088
         go1 (ListPat _ pats)
    
    1089 1089
           = do { exprs <- mapM go pats
    
    1090
    -           ; return $ ExplicitList noExtField exprs }
    
    1090
    +           ; return $ ExplicitList NoRebindable exprs }
    
    1091 1091
         go1 (TuplePat _ pats box)       = do { exprs <- mapM go pats
    
    1092 1092
                                              ; return $ ExplicitTuple noExtField
    
    1093 1093
                                                (map (Present noExtField) exprs) box }
    

  • compiler/GHC/Tc/Types/Origin.hs
    ... ... @@ -641,6 +641,7 @@ exprCtOrigin (XExpr (ExpandedThingRn (HSE o _))) = hsCtxtCtOrigin o
    641 641
     exprCtOrigin (XExpr (HsRecSelRn f))  = OccurrenceOfRecSel $ L (getLoc $ foLabel f) (foExt f)
    
    642 642
     
    
    643 643
     hsCtxtCtOrigin :: HsCtxt -> CtOrigin
    
    644
    +hsCtxtCtOrigin (ExprCtxt (ExprWithTySig _ (L _ e) _)) = exprCtOrigin e
    
    644 645
     hsCtxtCtOrigin (ExprCtxt e) = exprCtOrigin e
    
    645 646
     hsCtxtCtOrigin (FunAppCtxt (FunAppCtxtExpr _ e) _) = exprCtOrigin e
    
    646 647
     hsCtxtCtOrigin (StmtErrCtxt{}) = DoStmtOrigin
    

  • compiler/GHC/ThToHs.hs
    ... ... @@ -1227,6 +1227,8 @@ cvtl e = wrapLA (cvt e)
    1227 1227
              ; let tele = setTelescopeBndrsNameSpace varName $
    
    1228 1228
                           mkHsForAllVisTele noAnn tvs'
    
    1229 1229
              ; return $ HsForAll noExtField tele body' }
    
    1230
    +    cvt (ReSynBindsE m e) = do { e' <- cvt e
    
    1231
    +                              ; return $ XExpr (ReSynBinds (mk_mod m) e') }
    
    1230 1232
     
    
    1231 1233
     {- | #16895 Ensure an infix expression's operator is a variable/constructor.
    
    1232 1234
     Consider this example:
    

  • libraries/ghc-boot-th/GHC/Boot/TH/Ppr.hs
    1
    -{-# LANGUAGE Trustworthy #-}
    
    2 1
     {-# LANGUAGE LambdaCase #-}
    
    3 2
     {-# OPTIONS_GHC -Wno-x-partial #-}
    
    4 3
     -- | contains a prettyprinter for the
    
    ... ... @@ -56,6 +55,9 @@ instance Ppr a => Ppr [a] where
    56 55
     instance Ppr Name where
    
    57 56
         ppr v = pprName v
    
    58 57
     
    
    58
    +instance Ppr ModName where
    
    59
    +    ppr (ModName s) = text s
    
    60
    +
    
    59 61
     ------------------------------
    
    60 62
     instance Ppr Info where
    
    61 63
         ppr (TyConI d)     = ppr d
    
    ... ... @@ -250,6 +252,7 @@ pprExp i (ForallE tvars body) =
    250 252
       parensIf (i >= funPrec) $ sep [pprForall tvars [], pprExp qualPrec body]
    
    251 253
     pprExp i (ConstrainedE ctx body) =
    
    252 254
       parensIf (i >= funPrec) $ sep [pprCtxWith pprExp ctx, pprExp qualPrec body]
    
    255
    +pprExp i (ReSynBindsE m e) = text "{{" <+> ppr m <+> text "}}" <+> pprExp i e
    
    253 256
     
    
    254 257
     pprFields :: [(Name,Exp)] -> Doc
    
    255 258
     pprFields = sep . punctuate comma . map (\(s,e) -> pprName' Applied s <+> equals <+> ppr e)
    

  • libraries/ghc-internal/src/GHC/Internal/TH/Syntax.hs
    ... ... @@ -902,6 +902,8 @@ data Exp
    902 902
       | ForallE [TyVarBndr Specificity] Exp -- ^ @forall \<vars\>. \<expr\>@
    
    903 903
       | ForallVisE [TyVarBndr ()] Exp      -- ^ @forall \<vars\> -> \<expr\>@
    
    904 904
       | ConstrainedE [Exp] Exp             -- ^ @\<ctxt\> => \<expr\>@
    
    905
    +  | ReSynBindsE ModName Exp            -- Remember to use bindings from the specified modname
    
    906
    +                                       -- while typechecking a typed splice for rebindable syntax
    
    905 907
       deriving( Show, Eq, Ord, Generic )
    
    906 908
     
    
    907 909
     -- | A (field name, expression) pair. See 'RecConE' and 'RecUpdE'.
    

  • testsuite/tests/ghc-api/T25121_status.stdout
    ... ... @@ -46,7 +46,9 @@ X(ExprWithTySig) mismatch
    46 46
     X(UntypedSplice) mismatch
    
    47 47
       >>> HsUntypedSpliceResult (HsExpr (GhcPass 'Renamed))
    
    48 48
       <<< HsUntypedSpliceResult (GenLocated (EpAnn [TrailingAnn]) (HsType (GhcPass 'Renamed)))
    
    49
    -X(ExplicitList) match = NoExtField
    
    49
    +X(ExplicitList) mismatch
    
    50
    +  >>> RebindableSyntaxTable
    
    51
    +  <<< NoExtField
    
    50 52
     X(ExplicitTuple) match = NoExtField
    
    51 53
     X(Hole) match = HoleKind
    
    52 54
     
    

  • testsuite/tests/parser/should_fail/RecordDotSyntaxFail8.stderr
    ... ... @@ -2,11 +2,11 @@ RecordDotSyntaxFail8.hs:47:17: error: [GHC-39999]
    2 2
         • No instance for ‘HasField "quux1" Quux Quux’
    
    3 3
             arising from selecting the field ‘quux1’
    
    4 4
           NB: ‘HasField’ is not the built-in ‘GHC.Internal.Records.HasField’ class.
    
    5
    -    • In the second argument of ‘($)’, namely ‘....bar.baz.quux1’
    
    6
    -      In a stmt of a 'do' block: print @Quux $ ....baz.quux1
    
    5
    +    • In the second argument of ‘($)’, namely ‘a.foo.bar.baz.quux1’
    
    6
    +      In a stmt of a 'do' block: print @Quux $ a.foo.bar.baz.quux1
    
    7 7
           In the expression:
    
    8 8
             do let a = Foo {foo = ...}
    
    9
    -           print @Quux $ ....quux1
    
    9
    +           print @Quux $ ....bar.baz.quux1
    
    10 10
                let b = myQuux
    
    11 11
                print @Quux $ b.quux2
    
    12 12
                let c = Foo {foo = ...}
    
    ... ... @@ -20,7 +20,7 @@ RecordDotSyntaxFail8.hs:50:17: error: [GHC-39999]
    20 20
           In a stmt of a 'do' block: print @Quux $ b.quux2
    
    21 21
           In the expression:
    
    22 22
             do let a = Foo {foo = ...}
    
    23
    -           print @Quux $ ....quux1
    
    23
    +           print @Quux $ ....bar.baz.quux1
    
    24 24
                let b = myQuux
    
    25 25
                print @Quux $ b.quux2
    
    26 26
                let c = Foo {foo = ...}
    
    ... ... @@ -30,11 +30,11 @@ RecordDotSyntaxFail8.hs:53:17: error: [GHC-39999]
    30 30
         • No instance for ‘HasField "quux3" Quux r0’
    
    31 31
             arising from selecting the field ‘quux3’
    
    32 32
           NB: ‘HasField’ is not the built-in ‘GHC.Internal.Records.HasField’ class.
    
    33
    -    • In the second argument of ‘($)’, namely ‘....baz.quux3.wob’
    
    34
    -      In a stmt of a 'do' block: print @Bool $ ....quux3.wob
    
    33
    +    • In the second argument of ‘($)’, namely ‘a.foo.bar.baz.quux3.wob’
    
    34
    +      In a stmt of a 'do' block: print @Bool $ a.foo.bar.baz.quux3.wob
    
    35 35
           In the expression:
    
    36 36
             do let a = Foo {foo = ...}
    
    37
    -           print @Quux $ ....quux1
    
    37
    +           print @Quux $ ....bar.baz.quux1
    
    38 38
                let b = myQuux
    
    39 39
                print @Quux $ b.quux2
    
    40 40
                let c = Foo {foo = ...}
    

  • testsuite/tests/parser/should_fail/RecordDotSyntaxFail9.stderr
    1 1
     RecordDotSyntaxFail9.hs:7:11: error: [GHC-18872]
    
    2 2
         • Couldn't match type ‘Int’ with ‘[Char]’
    
    3 3
             arising from selecting the field ‘foo’
    
    4
    -    • In the expression: a.foo
    
    4
    +    • In the expression: a.foo :: String
    
    5 5
           In a pattern binding: _ = a.foo :: String
    
    6 6
           In a stmt of a 'do' block: let _ = a.foo :: String
    
    7 7
     

  • testsuite/tests/rebindable/T19918.stdout
    ... ... @@ -13,4 +13,4 @@
    13 13
     [("negate",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 63, srcLocStartCol = 11, srcLocEndLine = 63, srcLocEndCol = 17})]
    
    14 14
     [("a use of syntactic negation",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 64, srcLocStartCol = 11, srcLocEndLine = 64, srcLocEndCol = 14})]
    
    15 15
     [(">>",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 65, srcLocStartCol = 14, srcLocEndLine = 65, srcLocEndCol = 16})]
    
    16
    -[("a do statement",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 66, srcLocStartCol = 16, srcLocEndLine = 66, srcLocEndCol = 18})]
    16
    +[("a do statement",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 66, srcLocStartCol = 11, srcLocEndLine = 66, srcLocEndCol = 24})]

  • testsuite/tests/th/T18102b.stdout
    1
    -25
    \ No newline at end of file
    1
    +10