23 Oct
2026
23 Oct
'26
11:59 p.m.
Apoorv Ingle pushed to branch wip/ani/T27156 at Glasgow Haskell Compiler / GHC
Commits:
122e97c6 by Apoorv Ingle at 2026-07-31T16:23:49-05:00
Work on #27156
- Add `RebindableSyntaxTable` to store function/operator names while renaming in the XBlah fields
- Expand the following expressions right before typechecking instead of in the renamer
* OverloadedLabel
* RecordDotSyntax: HsGetField and HsProjection
* ExplicitList
* RecordUpd
* HsIf
* HsDo (Vanilla cases)
- - - - -
0582455a by Apoorv Ingle at 2026-07-31T16:23:49-05:00
update notes
- - - - -
c9ce3acb by Apoorv Ingle at 2026-07-31T16:23:49-05:00
rebase changes
- - - - -
ba9730bd by Apoorv Ingle at 2026-07-31T16:51:29-05:00
revert th test
- - - - -
c22f51ed by Apoorv Ingle at 2026-10-23T17:54:33-05:00
make a new ReSynBinds to store the module name
- - - - -
18 changed files:
- + changelog.d/T27156
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/Hs/Instances.hs
- compiler/GHC/Rename/Expr.hs
- compiler/GHC/Rename/Splice.hs
- compiler/GHC/Tc/Gen/Do.hs
- compiler/GHC/Tc/Gen/Expand.hs
- compiler/GHC/Tc/Gen/Expr.hs
- compiler/GHC/Tc/TyCl/PatSyn.hs
- compiler/GHC/Tc/Types/Origin.hs
- compiler/GHC/ThToHs.hs
- libraries/ghc-boot-th/GHC/Boot/TH/Ppr.hs
- libraries/ghc-internal/src/GHC/Internal/TH/Syntax.hs
- testsuite/tests/ghc-api/T25121_status.stdout
- testsuite/tests/parser/should_fail/RecordDotSyntaxFail8.stderr
- testsuite/tests/parser/should_fail/RecordDotSyntaxFail9.stderr
- testsuite/tests/rebindable/T19918.stdout
- testsuite/tests/th/T18102b.stdout
Changes:
=====================================
changelog.d/T27156
=====================================
@@ -0,0 +1,10 @@
+section: compiler
+issues: #27156
+mrs: !15868
+synopsis:
+ Refactor code, to perform expansions related to rebindable sytax in their own pass
+description:
+ Expansions for some constructs (HsIf, Record Dot Syntax, Sections)
+ was done in the renamer while for others it was done in
+ the type checker. This patch moves all the expansions out of the renamer into its own pass.
+ 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
-- OverLabel not present in GhcTc pass; see GHC.Rename.Expr
-- Note [Handling overloaded and rebindable constructs]
type instance XOverLabel GhcPs = SourceText
-type instance XOverLabel GhcRn = SourceText
+type instance XOverLabel GhcRn = ( SourceText -- Needed for pretty printing
+ , RebindableSyntaxTable) -- contains the fromLabel Name
+
type instance XOverLabel GhcTc = DataConCantHappen
-- ---------------------------------------------------------------------
@@ -278,7 +280,7 @@ type instance XCase GhcRn = HsMatchContextRn
type instance XCase GhcTc = HsMatchContextRn
type instance XIf GhcPs = AnnsIf
-type instance XIf GhcRn = NoExtField
+type instance XIf GhcRn = RebindableSyntaxTable -- NoRebindable <=> RebindableSyntax is off
type instance XIf GhcTc = NoExtField
type instance XMultiIf GhcPs = (EpToken "if", EpToken "{", EpToken "}")
@@ -294,7 +296,7 @@ type instance XDo GhcRn = NoExtField
type instance XDo GhcTc = Type
type instance XExplicitList GhcPs = AnnList ()
-type instance XExplicitList GhcRn = NoExtField
+type instance XExplicitList GhcRn = RebindableSyntaxTable -- NoRebindable <=> RebindableSyntax is off
type instance XExplicitList GhcTc = Type
-- GhcPs: ExplicitList includes all source-level
-- list literals, including overloaded ones
@@ -308,8 +310,9 @@ type instance XRecordCon GhcPs = NoExtField
type instance XRecordCon GhcRn = NoExtField
type instance XRecordCon GhcTc = PostTcExpr -- Instantiated constructor function
+
type instance XRecordUpd GhcPs = (EpToken "{", EpToken "}")
-type instance XRecordUpd GhcRn = NoExtField
+type instance XRecordUpd GhcRn = RebindableSyntaxTable -- NoRebindable <=> RebindableSyntaxTable is off
type instance XRecordUpd GhcTc = DataConCantHappen
-- We desugar record updates in the typechecker.
-- See [Handling overloaded and rebindable constructs],
@@ -341,16 +344,16 @@ type instance XLHsRecUpdLabels GhcTc = DataConCantHappen
type instance XLHsOLRecUpdLabels p = NoExtField
type instance XGetField GhcPs = NoExtField
-type instance XGetField GhcRn = NoExtField
+type instance XGetField GhcRn = RebindableSyntaxTable
type instance XGetField GhcTc = DataConCantHappen
--- HsGetField is eliminated by the renamer. See [Handling overloaded
--- and rebindable constructs].
+-- HsGetField is eliminated by the expansion in GHC.Tc.Expand
+-- See [Handling overloaded and rebindable constructs].
type instance XProjection GhcPs = AnnProjection
-type instance XProjection GhcRn = NoExtField
+type instance XProjection GhcRn = RebindableSyntaxTable
type instance XProjection GhcTc = DataConCantHappen
--- HsProjection is eliminated by the renamer. See [Handling overloaded
--- and rebindable constructs].
+-- HsProjection is eliminated by the expansion in GHC.Tc.Expand
+-- See [Handling overloaded and rebindable constructs].
type instance XExprWithTySig GhcPs = TokDcolon
type instance XExprWithTySig GhcRn = NoExtField
@@ -644,7 +647,7 @@ tupArgsPresent_maybe = traverse tupArgPresent_maybe
* *
********************************************************************* -}
-type instance XXExpr GhcPs = DataConCantHappen
+type instance XXExpr GhcPs = XXExprGhcPs
type instance XXExpr GhcRn = XXExprGhcRn
type instance XXExpr GhcTc = XXExprGhcTc
-- XXExprGhcRn: see Note [Rebindable syntax and XXExprGhcRn] below
@@ -657,6 +660,10 @@ type instance XXExpr GhcTc = XXExprGhcTc
* *
********************************************************************* -}
+data XXExprGhcPs
+ = ReSynBinds ModuleName (HsExpr GhcPs)
+
+
-- See Note [Rebindable syntax and XXExprGhcRn]
-- See Note [Expanding HsDo with XXExprGhcRn] in `GHC.Tc.Gen.Do`
-- See Note [Typechecking by expansion: overview]
@@ -673,6 +680,7 @@ data XXExprGhcRn
-- See Note [Non-overloaded record field selectors] and
-- Note [Record selectors in the AST]
+
data XXExprGhcTc
= WrapExpr -- Type and evidence application and abstractions
HsWrapper (HsExpr GhcTc)
@@ -817,7 +825,7 @@ ppr_expr (HsHole x) = case (ghcPass @p, x) of
(GhcTc, (HoleError, _)) -> pprPrefixOcc unnamedHoleRdrName
ppr_expr (HsOverLabel s l) = case ghcPass @p of
GhcPs -> helper s
- GhcRn -> helper s
+ GhcRn -> helper (fst s)
GhcTc -> dataConCantHappen s
where helper :: SourceText -> SDoc
@@ -1021,9 +1029,12 @@ ppr_expr (HsFunArr _ arr arg res)
= sep [ppr_lexpr arg, pprHsModifiedFunArr arr <+> ppr_lexpr res]
ppr_expr (XExpr x) = case ghcPass @p of
+ GhcPs -> ppr x
GhcRn -> ppr x
GhcTc -> ppr x
+instance Outputable XXExprGhcPs where
+ ppr (ReSynBinds m e) = text "{{" <+> ppr m <+> text "}}" <+> ppr e
ppr_hse :: forall p. (IsPass p) => HsExpansion (GhcPass p) -> SDoc
ppr_hse hse
@@ -1080,10 +1091,14 @@ ppr_infix_expr (HsHole x) = Just $ pprInfixOcc $ case (ghcPass @p, x) of
(GhcTc, (HoleVar (L _ v), _)) -> v
_ -> unnamedHoleRdrName -- TODO: this is the HoleError case; this should print the source text instead of "_".
ppr_infix_expr (XExpr x) = case ghcPass @p of
+ GhcPs -> ppr_infix_expr_ps x
GhcRn -> ppr_infix_expr_rn x
GhcTc -> ppr_infix_expr_tc x
ppr_infix_expr _ = Nothing
+ppr_infix_expr_ps :: XXExprGhcPs -> Maybe SDoc
+ppr_infix_expr_ps (ReSynBinds{}) = Nothing
+
ppr_infix_expr_rn :: XXExprGhcRn -> Maybe SDoc
ppr_infix_expr_rn (ExpandedThingRn (HSE thing _)) = ppr_infix_hs_expansion thing
ppr_infix_expr_rn (HsRecSelRn f) = Just (pprInfixOcc f)
@@ -1174,9 +1189,13 @@ hsExprNeedsParens prec = go
go (HsQual{}) = prec >= funPrec
go (HsFunArr{}) = prec >= funPrec
go (XExpr x) = case ghcPass @p of
+ GhcPs -> go_x_ps x
GhcTc -> go_x_tc x
GhcRn -> go_x_rn x
+ go_x_ps :: XXExprGhcPs -> Bool
+ go_x_ps (ReSynBinds _ e) = hsExprNeedsParens prec e
+
go_x_tc :: XXExprGhcTc -> Bool
go_x_tc (WrapExpr _ e) = hsExprNeedsParens prec e
go_x_tc (ExpandedThingTc (HSE thing _)) = hsExpandedNeedsParens thing
@@ -1264,7 +1283,8 @@ instance Outputable (HsPragE (GhcPass p)) where
{- Note [Rebindable syntax and XXExprGhcRn]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We implement rebindable syntax (RS) support by performing an expansion
-in the renamer. We transform GhcPs expressions and patterns affected by
+right before typechecking and after renaming.
+We transform GhcRn expressions and patterns affected by
RS into the appropriate expanded form, but **annotated with the original
expression/pattern**.
@@ -1297,7 +1317,7 @@ original 'if' expression around too, using the TTG
XExpr extension point to allow GHC to construct an
'XXExprGhcRn' value that will keep track of the original
expression in its first field, and the desugared one in the
-second field. The resulting renamed AST would look like:
+second field. The resulting expanded AST would look like:
L locif (XExpr
(ExpandedThingRn (HSE
@@ -1357,25 +1377,26 @@ tcl_in_gen_code Bool to False.
---
-An overview of the constructs that are desugared in this way is laid out in
+An overview of the constructs that are expanded in this way is laid out in
Note [Handling overloaded and rebindable constructs] in GHC.Rename.Expr.
A general recipe to follow this approach for new constructs could go as follows:
- Remove any GhcRn-time SyntaxExpr extensions to the relevant constructor for your
construct, in HsExpr or related syntax data types.
-- At renaming-time:
+- At renaming-time (GHC.Tc.Gen.Rename.rnExpr) :
- take your original node of interest (HsIf above)
- rename its subexpressions/subpatterns (condition and true/false
branches above)
- construct the suitable "rebound"-and-renamed result (ifThenElse call
above), where the 'SrcSpan' attached to any _fabricated node_ (the
HsVar/HsApp nodes, above) is set to 'generatedSrcSpan'
+- At Expansion time (GHC.Tc.Gen.Expand.tcExpand)
- take both the original node and that rebound-and-renamed result and wrap
them into an expansion construct:
- for expressions, XExpr (ExpandedThingRn <original node> <desugared>)
+ for expressions, XExpr (ExpandedThingRn (HSE { hse_ctxt = <original node> hse_exp = <desugared> }))
for patterns, XPat (HsPatExpanded <original node> <desugared>)
- - At typechecking-time:
+ - At typechecking-time (GHC.Tc.Gen.tcExpr):
- remove any logic that was previously dealing with your rebindable
construct, typically involving [tc]SyntaxOp, SyntaxExpr and friends.
- the XExpr (ExpandedThingRn ... ...) case in tcExpr already makes sure that we
@@ -1482,6 +1503,14 @@ type instance XXCmd GhcTc = HsWrap HsCmd
type CmdSyntaxTable p = [(Name, HsExpr p)]
-- See Note [CmdSyntaxTable]
+-- | Syntax lookup table for rebindable constructs
+data RebindableSyntaxTable = NoRebindable | Rebindable [(OccName, Name)]
+-- See Note [RebindableSyntaxTable]
+
+isNoRebindable :: RebindableSyntaxTable -> Bool
+isNoRebindable NoRebindable = True
+isNoRebindable Rebindable{} = False
+
{-
Note [CmdSyntaxTable]
~~~~~~~~~~~~~~~~~~~~~
@@ -1518,6 +1547,32 @@ is Less Cool because
typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
-}
+{-
+Note [RebindableSyntaxTable]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+During renaming of constructs that support rebindable syntax (eg. HsIf),
+we store the function (eg. ifThenElse) in a rebindable syntax table. Then
+in the the expansion phase, right before typechecking, we use the
+function (eg. ifThenElse) to build the actual expression to be typechecked.
+
+Why do we need to do this?
+The renamer identifies the free variables of the expressions to perform dependency analysis.
+When rebindable sytax is turned on, we want to treat the expression
+
+ HsIf b e1 e2
+
+As if it is
+
+ ifThenElse b e1 e2
+
+Thus the renamer needs to return `ifThenElse` as a free variable.
+
+Rebindable syntax stores this `ifThenElse` name so that it can be
+used to build the correct expanded expression in GHC.Tc.Gen.Expand.tcExpand.
+
+-}
+
+
data CmdTopTc
= CmdTopTc
-- | Nested tuple of inputs on the command's stack
=====================================
compiler/GHC/Hs/Instances.hs
=====================================
@@ -355,6 +355,8 @@ deriving instance Data (RoleAnnotDecl GhcTc)
-- ---------------------------------------------------------------------
-- Data derivations from GHC.Hs.Expr -----------------------------------
+deriving instance Data RebindableSyntaxTable -- maybe don't traverse?
+
deriving instance Data (FieldLabelStrings GhcPs)
deriving instance Data (FieldLabelStrings GhcRn)
deriving instance Data (FieldLabelStrings GhcTc)
@@ -728,7 +730,7 @@ deriving instance Data (HsExpansion GhcTc)
deriving instance Data a => Data (WithUserRdr a)
-- -------------------------------
---------------------------------------
+deriving instance Data XXExprGhcPs
deriving instance Data XXExprGhcTc
deriving instance Data XXPatGhcTc
=====================================
compiler/GHC/Rename/Expr.hs
=====================================
@@ -3,6 +3,7 @@
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
+{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
@@ -39,7 +40,6 @@ import GHC.Rename.Unbound ( reportUnboundName )
import GHC.Rename.Splice ( rnTypedBracket, rnUntypedBracket, rnTypedSplice
, rnUntypedSpliceExpr, checkThLocalNameWithLift, checkThLocalNameNoLift )
import GHC.Rename.HsType
-import GHC.Rename.Lit
import GHC.Rename.Pat
import GHC.Driver.DynFlags
@@ -49,7 +49,6 @@ import GHC.Unit.Module ( isInteractiveModule )
import GHC.Types.Basic (TypeOrKind (TypeLevel))
import GHC.Types.FieldLabel
-import GHC.Types.Id.Make
import GHC.Types.Name
import GHC.Types.Name.Set
import GHC.Types.Name.Reader
@@ -72,7 +71,7 @@ import qualified GHC.LanguageExtensions as LangExt
import Control.Monad
import qualified Data.Foldable as Partial (maximum)
import Data.List (unzip4)
-import Data.List.NonEmpty ( NonEmpty(..), head, init, last, nonEmpty, scanl, tail )
+import Data.List.NonEmpty ( NonEmpty(..), head, nonEmpty, scanl, tail )
import Control.Arrow (first)
import Data.Ord
import Data.Array
@@ -84,20 +83,34 @@ import Data.Foldable (toList)
Nomenclature
-------------
-* Expansion (`HsExpr GhcRn -> HsExpr GhcRn`): expand between renaming and
- typechecking, using the `XXExprGhcRn` constructor of `HsExpr`.
-* Desugaring (`HsExpr GhcTc -> Core.Expr`): convert the typechecked `HsSyn` to Core. This is done in GHC.HsToCore
+* Expansion (`HsExpr GhcRn -> HsExpansion GhcRn`): expand after renaming and
+ right before typechecking, using the `XXExprGhcRn` constructor of `HsExpr`.
+* Desugaring (`HsExpr GhcTc -> Core.Expr`): convert the typechecked `HsSyn` to Core.
+ This is done in GHC.HsToCore
For overloaded constructs (overloaded literals, lists, strings), and
rebindable constructs (e.g. if-then-else), our general plan is this,
using overloaded labels #foo as an example:
-* In the RENAMER: transform
+* In the RENAMER (GHC.Tc.Rename.rnExpr):
+ Identify if we need to transform the rebindable construct
+ and store the appropriate `fromLabel` function in the RebindableSyntaxTable
+ field associated with HsOverLabel.
+
HsOverLabel "foo"
- ==> XExpr (ExpandedThingRn (HsOverLabel #foo)
- (fromLabel `HsAppType` "foo"))
+ ==> HsOverLabel (Rebindable [("fromLabel", fromLabelClassOpName)]) "foo"
+
+* In the EXPANSION (GHC.Tc.Gen.Expand.tcExpand):
+ Expand the HsOverLabel to an Expanded expression
+ using the fromLabel function stored in the rebindable syntax table
+
+ HsOverLabel (Rebindable [("fromLabel", fromLabelClassOpName)]) "foo"
+ ==> XExpr (ExpandedThingRn HSE { hse_ctxt = (HsOverLabel #foo)
+ , hse_exp = L genLoc (fromLabel `HsAppType` "foo") })
+
We write this more compactly in concrete-syntax form like this
+
#foo ==> fromLabel @"foo"
Recall that in (ExpandedThingRn orig expanded), 'orig' is the original term
@@ -107,16 +120,18 @@ using overloaded labels #foo as an example:
* In the TYPECHECKER: typecheck the expansion, in this case
fromLabel @"foo"
The typechecker (and desugarer) will never see HsOverLabel
+ See Note [Typechecking by expansion: overview]
-In effect, the renamer does a bit of desugaring. Recall GHC.Hs.Expr
-Note [Rebindable syntax and XXExprGhcRn], which describes the use of XXExprGhcRn.
+In effect, the renamer stores the rebindable syntax functions (ifThenElse, fromLabel, etc).
+in the rebindable syntax table, the expander build the actual AST before typechecking.
+Recall GHC.Hs.Expr Note [Rebindable syntax and XXExprGhcRn], which describes the use of XXExprGhcRn.
RebindableSyntax:
If RebindableSyntax is off we use the built-in 'fromLabel', defined in
GHC.Builtin.Names.fromLabelClassOpName
If RebindableSyntax if ON, we look up "fromLabel" in the environment
to get whichever one is in scope.
-This is accomplished by lookupSyntaxName, and it applies to all the
+This is accomplished by `lookupSyntaxName`, and it applies to all the
constructs below.
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:
where `leftSection` and `rightSection` are representation-polymorphic
wired-in Ids. See Note [Left and right sections]
-* To understand why expansions for `OpApp` is done in `GHC.Tc.Gen.Head.splitHsApps`
- see Note [Doing XXExprGhcRn in the Renamer vs Typechecker] below.
-
* RecordUpd: we desugar record updates into case expressions,
in GHC.Tc.Gen.Expr.tcExpr.
@@ -172,8 +184,23 @@ but several have a little bit of special treatment:
See Note [Record Updates] in GHC.Tc.Gen.Expr for more details.
- To understand Why is this done in the typechecker, and not in the renamer
- see Note [Doing XXExprGhcRn in the Renamer vs Typechecker]
+ This expansion is done in the typechecker on the fly (`GHC.Tc.Gen.tcExpr`), (until #27160 is fixed)
+ and not in the renamer for two reasons:
+
+ - (Until we implement GHC proposal #366)
+ We need to know the type of the record to disambiguate its fields.
+
+ - We use the type signature of the data constructor to provide `IdSigs`
+ to the let-bound variables (x', y' in the example of
+ See Note [Handling overloaded and rebindable constructs]).
+ This is needed to accept programs such as
+
+ data R b = MkR { f :: (forall a. a -> a) -> (Int,b), c :: Int }
+ foo r = r { f = \ k -> (k 3, k 'x') }
+
+ in which an updated field has a higher-rank type.
+ See Wrinkle [Using IdSig] in Note [Record Updates] in GHC.Tc.Gen.Expr.
+
* HsDo: We expand `HsDo` statements in `Ghc.Tc.Gen.Do`.
@@ -188,8 +215,22 @@ but several have a little bit of special treatment:
(return (f x))))
See Note [Expanding HsDo with XXExprGhcRn] in `Ghc.Tc.Gen.Do` for more details.
- To understand why is this done in the typechecker and not in the renamer.
- See Note [Doing XXExprGhcRn in the Renamer vs Typechecker]
+
+ - The expansion for do block statements is done on the fly right before typechecking
+ in `GHC.Tc.Gen.Expand.tcExpand` using `GHC.Tc.Gen.Do.expandDoStmts`.
+ There are 2 main reasons:
+
+ 1. During the renaming phase, we may not have all the constructor details `HsConDetails` populated in the
+ data structure. This would result in an inaccurate irrefutability analysis causing
+ the continuation lambda body to be wrapped with `fail` alternatives when not needed.
+ See Part 1. of Note [Expanding HsDo with XXExprGhcRn] (test pattern-fails.hs)
+
+ 2. If the expansion is done on the fly during renaming, expressions that
+ have explicit type applications using (-XTypeApplciations) will not work (cf. Let statements expansion)
+ as the name freshening happens from the root of the AST to the leaves,
+ but the expansion happens in the opposite direction (from leaves to the root),
+ causing the renamer to miss the scoped type variables.
+
Note [Overloaded labels]
~~~~~~~~~~~~~~~~~~~~~~~~
@@ -209,66 +250,6 @@ type-applying to "foo", so we get
And those inferred kind quantifiers will indeed be instantiated when we
typecheck the renamed-syntax call (fromLabel @"foo").
-
-Note [Doing XXExprGhcRn in the Renamer vs Typechecker]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We expand some `HsExpr GhcRn` code at various places, usually, on the fly,
-depending on when it is more convenient. It may be beneficial to have a
-separate `HsExpr GhcRn -> HsExpr GhcRn` pass that does this expansion uniformly
-in the future when we have enough cases to cater for. For the time being,
-this note documents which language feature is expanded at which phase,
-and the reasons for doing so.
-
- ** `HsIf` Expansions
- --------------------
- `HsIf` expansions are expanded in the Renamer becuase it is more convinent
- to do so there and then not worry about it in the later stage.
- `-XRebindableSyntax` is used to decide whether we use the `HsIf` or user defined if
-
-
- ** `OpApp` Expansions
- ---------------------
- The typechecker turns `OpApp` into a use of `XXExprGhcRn`
- on the fly, in `GHC.Tc.Gen.Head.splitHsApps`.
- The language extension `RebindableSyntax` does not affect this behaviour.
-
- It's a bit painful to transform `OpApp e1 op e2` to a `XXExprGhcRn`
- form, because the renamer does precedence rearrangement after name
- resolution. So the renamer leaves an `OpApp` as an `OpApp`.
-
- ** Record Update Syntax `RecordUpd` Expansions
- ----------------------------------------------
- This is done in the typechecker on the fly (`GHC.Tc.Expr.tcExpr`), and not the renamer, for two reasons:
-
- - (Until we implement GHC proposal #366)
- We need to know the type of the record to disambiguate its fields.
-
- - We use the type signature of the data constructor to provide `IdSigs`
- to the let-bound variables (x', y' in the example of
- Note [Handling overloaded and rebindable constructs] above).
- This is needed to accept programs such as
-
- data R b = MkR { f :: (forall a. a -> a) -> (Int,b), c :: Int }
- foo r = r { f = \ k -> (k 3, k 'x') }
-
- in which an updated field has a higher-rank type.
- See Wrinkle [Using IdSig] in Note [Record Updates] in GHC.Tc.Gen.Expr.
-
- ** `HsDo` Statement Expansions
- -----------------------------------
- The expansion for do block statements is done on the fly right before typechecking in `GHC.Tc.Gen.Expr`
- using `GHC.Tc.Gen.Do.expandDoStmts`. There are 2 main reasons:
-
- - During the renaming phase, we may not have all the constructor details `HsConDetails` populated in the
- data structure. This would result in an inaccurate irrefutability analysis causing
- the continuation lambda body to be wrapped with `fail` alternatives when not needed.
- See Part 1. of Note [Expanding HsDo with XXExprGhcRn] (test pattern-fails.hs)
-
- - If the expansion is done on the fly during renaming, expressions that
- have explicit type applications using (-XTypeApplciations) will not work (cf. Let statements expansion)
- as the name freshening happens from the root of the AST to the leaves,
- but the expansion happens in the opposite direction (from leaves to the root),
- causing the renamer to miss the scoped type variables.
-}
{-
@@ -345,12 +326,9 @@ rnExpr (HsHole h)
-- HsOverLabel: see Note [Handling overloaded and rebindable constructs]
rnExpr (HsOverLabel src v)
= do { (from_label, fvs) <- lookupSyntaxName fromLabelClassOpName
- ; return ( mkExpandedExpr (HsOverLabel src v) $
- HsAppType noExtField (genLHsVar from_label) hs_ty_arg
- , fvs ) }
- where
- hs_ty_arg = mkEmptyWildCardBndrs $ wrapGenSpan $
- HsTyLit noExtField (HsString NoSourceText v)
+ ; let rs_table = Rebindable [(nameOccName fromLabelClassOpName, from_label)]
+ ; return (HsOverLabel (src, rs_table) v, fvs)
+ }
rnExpr (HsLit x lit) | HsString src s <- lit
= do { opt_OverloadedStrings <- xoptM LangExt.OverloadedStrings
@@ -372,10 +350,12 @@ rnExpr (HsOverLit x lit)
return (HsApp noExtField (noLocA neg) (noLocA (HsOverLit x lit'))
, fvs ) }
-rnExpr (HsQualLit x lit) = do
- ((lit', desugaredExpr), fvs) <- rnQualLit lit
- let origExpr = HsQualLit x lit'
- return (mkExpandedExpr origExpr desugaredExpr, fvs)
+rnExpr (HsQualLit x QualLit{..})
+ = do { (funName, fvs) <- lookupNameWithQualifier fromStringName ql_mod
+ ; let ql_val' = case ql_val of
+ HsQualString st s -> HsQualString st s
+ ; return (HsQualLit x (QualLit (L noAnn funName) ql_mod ql_val'), fvs)
+ }
rnExpr (HsApp x fun arg)
= do { (fun',fvFun) <- rnLExpr fun
@@ -419,19 +399,15 @@ rnExpr (HsGetField _ e f)
= do { (getField, fv_getField) <- lookupSyntaxName getFieldName
; (e, fv_e) <- rnLExpr e
; let f' = rnDotFieldOcc <$> f
- ; return ( mkExpandedExpr
- (HsGetField noExtField e f')
- (mkGetField getField e (fmap (unLoc . dfoLabel) f'))
- , fv_e `plusFN` fv_getField ) }
+ rs_table = Rebindable [(nameOccName getFieldName, getField)]
+ ; return (HsGetField rs_table e f', fv_e `plusFN` fv_getField) }
rnExpr (HsProjection _ fs)
- = do { (getField, fv_getField) <- lookupSyntaxName getFieldName
- ; circ <- lookupOccRn WL_TermVariable compose_RDR
+ = do { (getFieldName, fv_getField) <- lookupSyntaxName getFieldName
+ ; circName <- lookupOccRn WL_TermVariable compose_RDR
; let fs' = NE.map rnDotFieldOcc fs
- ; return ( mkExpandedExpr
- (HsProjection noExtField fs')
- (mkProjection getField circ $ NE.map (unLoc . dfoLabel) fs')
- , unitFN circ `plusFN` fv_getField) }
+ rs_table = Rebindable [(nameOccName getFieldName , getFieldName), (rdrNameOcc compose_RDR, circName)]
+ ; return (HsProjection rs_table fs', unitFN circName `plusFN` fv_getField) }
------------------------------------------
-- Template Haskell extensions
@@ -494,15 +470,12 @@ rnExpr (ExplicitList _ exps)
= do { (exps', fvs) <- rnExprs exps
; opt_OverloadedLists <- xoptM LangExt.OverloadedLists
; if not opt_OverloadedLists
- then return (ExplicitList noExtField exps', fvs)
+ then return (ExplicitList NoRebindable exps', fvs)
else
do { (from_list_n_name, fvs') <- lookupSyntaxName fromListNName
- ; loc <- getSrcSpanM -- See Note [Source locations for implicit function calls]
- ; let rn_list = ExplicitList noExtField exps'
- lit_n = mkIntegralLit (length exps)
- hs_lit = genHsIntegralLit lit_n
- exp_list = genHsApps' (wrapGenSpan' loc from_list_n_name) [hs_lit, wrapGenSpan rn_list]
- ; return ( mkExpandedExpr rn_list exp_list
+ ; let rs_table = Rebindable [(nameOccName fromListNName, from_list_n_name)]
+ rn_list = ExplicitList rs_table exps'
+ ; return ( rn_list
, fvs `plusFN` fvs') } }
rnExpr (ExplicitTuple _ tup_args boxity)
@@ -546,7 +519,7 @@ rnExpr (RecordUpd { rupd_expr = L l expr, rupd_flds = rbinds })
RegularRecUpdFields
{ xRecUpdFields = parents
, recUpdFields = flds }
- ; return ( RecordUpd noExtField (L l e) upd_flds
+ ; return ( RecordUpd NoRebindable (L l e) upd_flds
, fv_e `plusFN` fv_flds ) }
-- 'OverloadedRecordUpdate' is in effect. Record dot update desugaring.
@@ -561,13 +534,13 @@ rnExpr (RecordUpd { rupd_expr = L l expr, rupd_flds = rbinds })
; (setField, fv_setField) <- lookupSyntaxName setFieldName
; (e, fv_e) <- rnExpr expr
; (us, fv_us) <- rnHsUpdProjs flds
- ; let upd_flds = OverloadedRecUpdFields
+ ; let upd_flds = OverloadedRecUpdFields
{ xOLRecUpdFields = noExtField
, olRecUpdFields = us }
- ; return ( mkExpandedExpr
- (RecordUpd noExtField (L l e) upd_flds)
- (mkRecordDotUpd getField setField (L l e) us)
- , plusFNs [fv_getField, fv_setField, fv_e, fv_us] ) }
+ rs_table = Rebindable [(nameOccName getField, getField) , (nameOccName setField, setField)]
+ ; return (RecordUpd rs_table (L l e) upd_flds
+ , plusFNs [fv_getField, fv_setField, fv_e, fv_us] )
+ }
rnExpr (ExprWithTySig _ expr pty)
@@ -632,6 +605,12 @@ rnExpr (HsFunArr _ mult arg res)
_ -> False
oneType = noLocA $ HsVar noExtField $ noLocA $ noUserRdr oneDataConName
+rnExpr (XExpr (ReSynBinds m e'))
+ = do { traceRn "XExpr ReSynBinds" (text "module:" <+> ppr m)
+ ; rnExpr e' -- for now just return the renamed expression
+ -- TODO: Bring into scope top level environment of the module m
+ }
+
{-
************************************************************************
* *
@@ -717,155 +696,20 @@ rnSection :: HsExpr GhcPs -> RnM (HsExpr GhcRn, FreeNames)
-- Also see Note [Handling overloaded and rebindable constructs]
rnSection section@(SectionR x op expr)
- -- See Note [Left and right sections]
= do { (op', fvs_op) <- rnLExpr op
; (expr', fvs_expr) <- rnLExpr expr
; checkSectionPrec InfixR section op' expr'
- ; let rn_section = SectionR x op' expr'
- ds_section = genHsApps rightSectionName [op',expr']
- ; return ( mkExpandedExpr rn_section ds_section
- , fvs_op `plusFN` fvs_expr) }
+ ; return $ (SectionR x op' expr' , fvs_op `plusFN` fvs_expr) }
rnSection section@(SectionL x expr op)
- -- See Note [Left and right sections]
= do { (expr', fvs_expr) <- rnLExpr expr
; (op', fvs_op) <- rnLExpr op
; checkSectionPrec InfixL section op' expr'
- ; postfix_ops <- xoptM LangExt.PostfixOperators
- -- Note [Left and right sections]
- ; let rn_section = SectionL x expr' op'
- ds_section
- | postfix_ops = HsApp noExtField op' expr'
- | otherwise = genHsApps leftSectionName
- [wrapGenSpan $ HsApp noExtField op' expr']
- ; return ( mkExpandedExpr rn_section ds_section
- , fvs_op `plusFN` fvs_expr) }
+ ; return $ (SectionL x expr' op', fvs_op `plusFN` fvs_expr) }
rnSection other = pprPanic "rnSection" (ppr other)
-{- Note [Left and right sections]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Dealing with left sections (x *) and right sections (* x) is
-surprisingly fiddly. We expand like this
- (`op` e) ==> rightSection op e
- (e `op`) ==> leftSection (op e)
-
-Using an auxiliary function in this way avoids the awkwardness of
-generating a lambda, esp if `e` is a redex, so we *don't* want
-to generate `(\x -> op x e)`. See Historical
-Note [Desugaring operator sections]
-
-Here are their definitions:
- leftSection :: forall r1 r2 n (a::TYPE r1) (b::TYPE r2).
- (a %n-> b) -> a %n-> b
- leftSection f x = f x
-
- rightSection :: forall r1 r2 r3 n1 n2 (a::TYPE r1) (b::TYPE r2) (c::TYPE r3).
- (a %n1 -> b %n2-> c) -> b %n2-> a %n1-> c
- rightSection f y x = f x y
-
-Note the wrinkles:
-
-* We do /not/ use lookupSyntaxName, which would make left and right
- section fall under RebindableSyntax. Reason: it would be a user-
- facing change, and there are some tricky design choices (#19354).
- Plus, infix operator applications would be trickier to make
- rebindable, so it'd be inconsistent to do so for sections.
-
- TL;DR: we still use the renamer-expansion mechanism for operator
- sections, but only to eliminate special-purpose code paths in the
- renamer and desugarer.
-
-* leftSection and rightSection must be representation-polymorphic, to allow
- (+# 4#) and (4# +#) to work. See
- Note [Wired-in Ids for rebindable syntax] in GHC.Types.Id.Make.
-
-* leftSection and rightSection must be multiplicity-polymorphic.
- (Test linear/should_compile/OldList showed this up.)
-
-* Because they are representation-polymorphic, we have to define them
- as wired-in Ids, with compulsory inlining. See
- GHC.Types.Id.Make.leftSectionId, rightSectionId.
-
-* leftSection is just ($) really; but unlike ($) it is
- representation-polymorphic in the result type, so we can write
- `(x +#)`, say.
-
-* The type of leftSection must have an arrow in its first argument,
- because (x `ord`) should be rejected, because ord does not take two
- arguments
-
-* It's important that we define leftSection in an eta-expanded way,
- (i.e. not leftSection f = f), so that
- (True `undefined`) `seq` ()
- = (leftSection (undefined True) `seq` ())
- evaluates to () and not undefined
-
-* If PostfixOperators is ON, then we expand a left section like this:
- (e `op`) ==> op e
- with no auxiliary function at all. Simple!
-
-* leftSection and rightSection switch on ImpredicativeTypes locally,
- during Quick Look; see GHC.Tc.Gen.App.wantQuickLook. Consider
- test DeepSubsumption08:
- type Setter st t a b = forall f. Identical f => blah
- (.~) :: Setter s t a b -> b -> s -> t
- clear :: Setter a a' b (Maybe b') -> a -> a'
- clear = (.~ Nothing)
- The expansion look like (rightSection (.~) Nothing). So we must
- instantiate `rightSection` first type argument to a polytype!
- Hence the special magic in App.wantQuickLook.
-
-Historical Note [Desugaring operator sections]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-This Note explains some historical trickiness in desugaring left and
-right sections. That trickiness has completely disappeared now that
-we desugar to calls to 'leftSection` and `rightSection`, but I'm
-leaving it here to remind us how nice the new story is.
-
-Desugaring left sections with -XPostfixOperators is straightforward: convert
-(expr `op`) to (op expr).
-
-Without -XPostfixOperators it's a bit more tricky. At first it looks as if we
-can convert
-
- (expr `op`)
-
-naively to
-
- \x -> op expr x
-
-But no! expr might be a redex, and we can lose laziness badly this
-way. Consider
-
- map (expr `op`) xs
-
-for example. If expr were a redex then eta-expanding naively would
-result in multiple evaluations where the user might only have expected one.
-
-So we convert instead to
-
- let y = expr in \x -> op y x
-
-Also, note that we must do this for both right and (perhaps surprisingly) left
-sections. Why are left sections necessary? Consider the program (found in #18151),
-
- seq (True `undefined`) ()
-
-according to the Haskell Report this should reduce to () (as it specifies
-desugaring via eta expansion). However, if we fail to eta expand we will rather
-bottom. Consequently, we must eta expand even in the case of a left section.
-
-If `expr` is actually just a variable, say, then the simplifier
-will inline `y`, eliminating the redundant `let`.
-
-Note that this works even in the case that `expr` is unlifted. In this case
-bindNonRec will automatically do the right thing, giving us:
-
- case expr of y -> (\x -> op y x)
-
-See #18151.
-
+{-
Note [Reporting unbound names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Faced with an out-of-scope `RdrName` there are two courses of action
@@ -2839,77 +2683,16 @@ rnHsIf p b1 b2
; (b1', fvB1) <- rnLExpr b1
; (b2', fvB2) <- rnLExpr b2
; let fvs_if = plusFNs [fvP, fvB1, fvB2]
- rn_if = HsIf noExtField p' b1' b2'
-
-- Deal with rebindable syntax
; mb_ite <- lookupIfThenElse
; case mb_ite of
Nothing -- Non rebindable-syntax case
- -> return (rn_if, fvs_if)
+ -> return (HsIf NoRebindable p' b1' b2', fvs_if)
Just ite_name -- Rebindable-syntax case
- -> do { let ds_if = genHsApps ite_name [p', b1', b2']
- fvs = plusFNs [fvs_if, unitFN ite_name]
- ; return (mkExpandedExpr rn_if ds_if, fvs) } }
+ -> do { let fvs = plusFNs [fvs_if, unitFN ite_name]
+ ; return (HsIf (Rebindable [(rdrNameOcc $ mkVarUnqual (fsLit "ifThenElse"), ite_name)]) p' b1' b2', fvs) } }
------------------------------------------
--- Bits and pieces for RecordDotSyntax.
---
--- See Note [Overview of record dot syntax] in GHC.Hs.Expr.
-
--- mkGetField arg field calculates a get_field @field arg expression.
--- e.g. z.x = mkGetField z x = get_field @x z
-mkGetField :: Name -> LHsExpr GhcRn -> LocatedAn NoEpAnns FieldLabelString -> HsExpr GhcRn
-mkGetField get_field arg field = unLoc (head $ mkGet get_field (arg :| []) field)
-
--- mkSetField a field b calculates a set_field @field expression.
--- e.g mkSetSetField a field b = set_field @"field" a b (read as "set field 'field' to a on b").
--- NB: the order of aruments is specified by GHC Proposal 583: HasField redesign.
-mkSetField :: Name -> LHsExpr GhcRn -> LocatedAn NoEpAnns FieldLabelString -> LHsExpr GhcRn -> HsExpr GhcRn
-mkSetField set_field a (L _ (FieldLabelString field)) b =
- genHsApp (genHsApp (genHsVar set_field `genAppType` genHsTyLit field) b) a
-
-mkGet :: Name -> NonEmpty (LHsExpr GhcRn) -> LocatedAn NoEpAnns FieldLabelString -> NonEmpty (LHsExpr GhcRn)
-mkGet get_field l@(r :| _) (L _ (FieldLabelString field)) =
- wrapGenSpan (genHsApp (genHsVar get_field `genAppType` genHsTyLit field) r) NE.<| l
-
-mkSet :: Name -> LHsExpr GhcRn -> (LocatedAn NoEpAnns FieldLabelString, LHsExpr GhcRn) -> LHsExpr GhcRn
-mkSet set_field acc (field, g) = wrapGenSpan (mkSetField set_field g field acc)
-
--- mkProjection fields calculates a projection.
--- e.g. .x = mkProjection [x] = getField @"x"
--- .x.y = mkProjection [.x, .y] = (.y) . (.x) = getField @"y" . getField @"x"
-mkProjection :: Name -> Name -> NonEmpty FieldLabelString -> HsExpr GhcRn
-mkProjection getFieldName circName (field :| fields) = foldl' f (proj field) fields
- where
- f :: HsExpr GhcRn -> FieldLabelString -> HsExpr GhcRn
- f acc field = genHsApps circName $ map wrapGenSpan [proj field, acc]
-
- proj :: FieldLabelString -> HsExpr GhcRn
- proj (FieldLabelString f) = genHsVar getFieldName `genAppType` genHsTyLit f
-
--- mkProjUpdateSetField calculates functions representing dot notation record updates.
--- e.g. Suppose an update like foo.bar = 1.
--- We calculate the function \a -> setField @"foo" a (setField @"bar" (getField @"foo" a) 1).
-mkProjUpdateSetField :: Name -> Name -> LHsRecProj GhcRn (LHsExpr GhcRn) -> (LHsExpr GhcRn -> LHsExpr GhcRn)
-mkProjUpdateSetField get_field set_field (L _ (HsFieldBind { hfbLHS = (L _ (FieldLabelStrings flds')), hfbRHS = arg } ))
- = let {
- ; flds = NE.map (fmap (unLoc . dfoLabel)) flds'
- ; final = last flds -- quux
- ; fields = init flds -- [foo, bar, baz]
- ; getters = \a -> foldl' (mkGet get_field) (a :| []) fields -- Ordered from deep to shallow.
- -- [getField@"baz"(getField@"bar"(getField@"foo" a), getField@"bar"(getField@"foo" a), getField@"foo" a, a]
- ; zips = \a -> (final, head (getters a)) : zip (reverse fields) (tail (getters a)) -- Ordered from deep to shallow.
- -- [("quux", getField@"baz"(getField@"bar"(getField@"foo" a)), ("baz", getField@"bar"(getField@"foo" a)), ("bar", getField@"foo" a), ("foo", a)]
- }
- in (\a -> foldl' (mkSet set_field) arg (zips a))
- -- 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))))
-
-mkRecordDotUpd :: Name -> Name -> LHsExpr GhcRn -> [LHsRecUpdProj GhcRn] -> HsExpr GhcRn
-mkRecordDotUpd get_field set_field exp updates = foldl' fieldUpdate (unLoc exp) updates
- where
- fieldUpdate :: HsExpr GhcRn -> LHsRecUpdProj GhcRn -> HsExpr GhcRn
- fieldUpdate acc lpu = unLoc $ (mkProjUpdateSetField get_field set_field lpu) (wrapGenSpan acc)
rnHsUpdProjs :: [LHsRecUpdProj GhcPs] -> RnM ([LHsRecUpdProj GhcRn], FreeNames)
rnHsUpdProjs us = do
=====================================
compiler/GHC/Rename/Splice.hs
=====================================
@@ -141,9 +141,8 @@ rnTypedBracket e br_body
; recordThUse
; traceRn "Renaming typed TH bracket" empty
- ; (body', fvs_e) <- setThLevel (Brack cur_level RnPendingTyped) $ rnLExpr br_body
- ; return (HsTypedBracket noExtField body', fvs_e)
-
+ ; (body, fvs_e) <- setThLevel (Brack cur_level RnPendingTyped) $ rnLExpr br_body
+ ; return (HsTypedBracket noExtField body, fvs_e)
}
rnUntypedBracket :: HsExpr GhcPs -> HsQuote GhcPs -> RnM (HsExpr GhcRn, FreeNames)
@@ -176,6 +175,7 @@ rnUntypedBracket e br_body
setThLevel (UntypedBrack cur_level ps_var) $
rn_utbracket br_body
; pendings <- readMutVar ps_var
+
; return (HsUntypedBracket pendings body', fvs_e)
}
@@ -613,6 +613,13 @@ problems, but keeps it on while processing typed TH quotes.
This note and approach originated in #18102.
+The MR!15868 (#27156) moved all the expansion/rebindable syntax (RS) mechanism into its own pass,
+done after renaming and right before typechecking.
+Before this patch, only some constructs (if then else, overloaded labels) were
+expanded in the renamer, but some (Do statements and record updates) were done after
+the renamer. This meant that the treatment of rebindable syntax and typed template haskell was
+not uniform across constructs. The MR!15868 makes the treatement of RS uniform for all constructs.
+
-}
{- 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
To disabmiguate desugaring (`HsExpr GhcTc -> Core.Expr`) we use the phrase expansion
(`HsExpr GhcRn -> HsExpr GhcRn`)
-This expansion is done after renaming and before typechecking
-See Part 2. of Note [Doing XXExprGhcRn in the Renamer vs Typechecker] in `GHC.Rename.Expr`
-
Historical note START
---------------------
In previous versions of GHC, the `do`-notation wasn't expanded before typechecking,
=====================================
compiler/GHC/Tc/Gen/Expand.hs
=====================================
@@ -7,17 +7,34 @@
module GHC.Tc.Gen.Expand( tcExpand ) where
-import GHC.Prelude
-
-import {-# SOURCE #-} GHC.Tc.Gen.Splice( getUntypedSpliceBody )
+import GHC.Prelude hiding (last, init, tail)
+import GHC.Data.FastString
import GHC.Hs
import GHC.Tc.Utils.Monad
import GHC.Tc.Types.ErrCtxt
+import GHC.Tc.Gen.Do
+import {-# SOURCE #-} GHC.Tc.Gen.Splice( getUntypedSpliceBody )
+
+import GHC.Types.Name
+import GHC.Types.Name.Reader
+import GHC.Types.Id.Make
+import GHC.Types.SrcLoc
+import GHC.Types.SourceText ( SourceText(..) )
+
+import GHC.Builtin.Names
import GHC.Rename.Utils
+import GHC.Utils.Panic
+import GHC.Utils.Outputable
+
+import qualified Data.List.NonEmpty as NE ( map, head, (<|) )
+import Data.List.NonEmpty ( NonEmpty(..), init, last, tail )
+
+import qualified GHC.LanguageExtensions as LangExt
+
{- Note [Typechecking by expansion: overview]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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
The `expandDoStmts` replaces the HsDo { x <- e1; return x }
with something like
- HSE { hse_ctxt = ExprCtxt e
+ HSE { hse_ctxt = ExprCtxt (HsDo { x <- e1; return x })
, hse_exp = e1 >>= \ x -> x }
and we then typecheck the expression `e1 >>= \ x -> x`
See also Note [Handling overloaded and rebindable constructs]
- and Note [Doing XXExprGhcRn in the Renamer vs Typechecker]
and Note [Rebindable syntax and XXExprGhcRn]
The Big Question is how to ensure that error messages mention
@@ -101,8 +117,39 @@ Wrinkle (TBE1)
-}
----------------
+-- See Note [Typechecking by expansion: overview]
tcExpand :: HsExpr GhcRn -> TcM (Maybe (HsExpansion GhcRn))
+
+------------------------------------------
+-- Overloaded labels
+tcExpand e@(HsOverLabel (_, Rebindable rs_table) v)
+ | Just fromLabelName <- lookup (nameOccName fromLabelClassOpName) rs_table
+ , let hs_ty_arg = mkEmptyWildCardBndrs $ wrapGenSpan $
+ HsTyLit noExtField (HsString NoSourceText v)
+ = return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan $ HsAppType noExtField (genLHsVar fromLabelName) hs_ty_arg
+ }
+
+ | otherwise
+ = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find fromLabel in rs_table"
+ , ppr e] )
+
+------------------------------------------
+-- Qualified Literals
+tcExpand e@(HsQualLit _ QualLit{ql_val = ql_val, ql_ext = (L _ fromStringName)})
+ = do { let hsLit = case ql_val of
+ -- See Note [Implementation of QualifiedStrings]
+ HsQualString st s -> HsString st s
+ ; return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan $ genHsApps fromStringName [genLHsLit hsLit]
+ }
+ }
+
+
+------------------------------------------
+-- Operator Applications
tcExpand e@(OpApp _ arg1 op arg2)
= return $ Just $
HSE { hse_ctxt = ExprCtxt e
@@ -110,14 +157,327 @@ tcExpand e@(OpApp _ arg1 op arg2)
where
ap f a = wrapGenSpan (HsApp noExtField f a)
-tcExpand (XExpr (ExpandedThingRn hse))
- = return (Just hse)
+------------------------------------------
+-- If
+
+-- NoRebindable <=> rebindable is turned off
+-- so we typecheck the HsIf in tcExprNoExpand
+tcExpand (HsIf NoRebindable _ _ _ )
+ = return Nothing
+tcExpand e@(HsIf (Rebindable rs_table) p b1 b2)
+ | Just ifThenElseName <- lookup (rdrNameOcc $ mkVarUnqual (fsLit "ifThenElse")) rs_table
+ = return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan $ genHsApps ifThenElseName [p, b1, b2]
+ }
+ | otherwise
+ = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find ifThenElse in rs_table"
+ , ppr e ])
+
+------------------------------------------
+-- Record dot syntax
+
+tcExpand e@(HsGetField (Rebindable rs_table) expr f)
+ | Just getField <- lookup (nameOccName getFieldName) rs_table
+ = return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan $ (mkGetField getField expr (fmap (unLoc . dfoLabel) f)) }
+ | otherwise
+ = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find getField in rs_table"
+ , ppr e ])
+
+tcExpand e@(HsProjection (Rebindable rs_table) fs)
+ | Just getField <- lookup (nameOccName getFieldName) rs_table
+ , Just circ <- lookup (rdrNameOcc compose_RDR) rs_table
+ = return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan $ (mkProjection getField circ $ NE.map (unLoc . dfoLabel) fs) }
+ | otherwise
+ = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find getField or circ in rs_table"
+ , ppr e])
+
+
+tcExpand (RecordUpd NoRebindable _ _ ) = return Nothing -- until #27160 is fixed
+
+tcExpand e@(RecordUpd (Rebindable rs_table) (L l expr) (OverloadedRecUpdFields { olRecUpdFields = us}))
+ | Just getField <- lookup (nameOccName getFieldName) rs_table
+ , Just setField <- lookup (nameOccName setFieldName) rs_table
+ = return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan $ mkRecordDotUpd getField setField (L l expr) us }
+ | otherwise
+ = pprPanic "tcExpand" (vcat [ text "Should Never Happen: could not find getField or setfield in rs_table"
+ , ppr e ])
+
+------------------------------------------
+-- Left and Right Sections
+
+tcExpand e@(SectionR _ op expr)
+ -- See Note [Left and right sections]
+ = return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan $ genHsApps rightSectionName [op, expr] }
+
+tcExpand e@(SectionL _ expr op)
+ -- Note [Left and right sections]
+ = do { postfix_ops <- xoptM LangExt.PostfixOperators
+ ; let ds_section
+ | postfix_ops = HsApp noExtField op expr
+ | otherwise = genHsApps leftSectionName
+ [wrapGenSpan $ HsApp noExtField op expr]
+ ; return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan ds_section } }
+
+------------------------------------------
+-- Explicit Lists
+
+tcExpand (ExplicitList NoRebindable _ )
+ = return Nothing -- rebindable syntax is off
+tcExpand e@(ExplicitList (Rebindable rs_table) exps)
+ | Just from_list_n_name <- lookup (nameOccName fromListNName) rs_table
+ = do { loc <- getSrcSpanM -- See Note [Source locations for implicit function calls]
+ ; let lit_n = mkIntegralLit (length exps)
+ hs_lit = genHsIntegralLit lit_n
+ exp_list = genHsApps' (wrapGenSpan' loc from_list_n_name)
+ [hs_lit, wrapGenSpan (ExplicitList NoRebindable exps)]
+ -- important to make it NoRebindable
+ -- Or we will go into an infinite loop
+ ; return $ Just $
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan $ exp_list }
+ }
+ | otherwise
+ = pprPanic "tcExpand" (vcat [text "Should Never Happen: could not find fromListN in rs_table"
+ , ppr e] )
+
+
+------------------------------------------
+-- Do statements
+
+tcExpand (HsDo _ do_or_lc stmts)
+ | DoExpr{} <- do_or_lc
+ -- ApplicativeDo are typechecked using tcDoStmts
+ = do isApplicativeDo <- xoptM LangExt.ApplicativeDo
+ if isApplicativeDo
+ then return Nothing -- to be fixed by #24406
+ -- Expand expression on the fly otherwise
+ -- See Note [Typechecking by expansion: overview]
+ else do { hse <- expandDoStmts do_or_lc stmts
+ ; return (Just hse) }
+ | MDoExpr{} <- do_or_lc
+ = do hse <- expandDoStmts do_or_lc stmts
+ return (Just hse)
+ | otherwise
+ -- ListComp and MonadComp are handled by legacy tcDoStmts for now,
+ -- The ultimate goal is to handle them via expandDoStmts.
+ -- GHCiStmts are handled completely separate
+ = return Nothing
+
+------------------------------------------
+-- Template Haskell Splices
tcExpand e@(HsUntypedSplice splice_res _)
-- See Note [Looking through Template Haskell splices in splitHsApps]
= do { fun <- getUntypedSpliceBody splice_res
; return $ Just $
- HSE { hse_ctxt = ExprCtxt e
- , hse_exp = wrapGenSpan fun } }
+ HSE { hse_ctxt = ExprCtxt e
+ , hse_exp = wrapGenSpan fun }
+ }
+
+------------------------
+-- XExpr
+-- Expansions are idempotent, XExprs do not expand again
+tcExpand (XExpr (ExpandedThingRn hse))
+ = return $ Just hse
+
+tcExpand _ = return $ Nothing
+
-tcExpand _ = return Nothing
+
+{- Note [Left and right sections]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Dealing with left sections (x *) and right sections (* x) is
+surprisingly fiddly. We expand like this
+ (`op` e) ==> rightSection op e
+ (e `op`) ==> leftSection (op e)
+
+Using an auxiliary function in this way avoids the awkwardness of
+generating a lambda, esp if `e` is a redex, so we *don't* want
+to generate `(\x -> op x e)`. See Historical
+Note [Desugaring operator sections]
+
+Here are their definitions:
+ leftSection :: forall r1 r2 n (a::TYPE r1) (b::TYPE r2).
+ (a %n-> b) -> a %n-> b
+ leftSection f x = f x
+
+ rightSection :: forall r1 r2 r3 n1 n2 (a::TYPE r1) (b::TYPE r2) (c::TYPE r3).
+ (a %n1 -> b %n2-> c) -> b %n2-> a %n1-> c
+ rightSection f y x = f x y
+
+Note the wrinkles:
+
+* We do /not/ use lookupSyntaxName, which would make left and right
+ section fall under RebindableSyntax. Reason: it would be a user-
+ facing change, and there are some tricky design choices (#19354).
+ Plus, infix operator applications would be trickier to make
+ rebindable, so it'd be inconsistent to do so for sections.
+
+ TL;DR: we still use the renamer-expansion mechanism for operator
+ sections, but only to eliminate special-purpose code paths in the
+ renamer and desugarer.
+
+* leftSection and rightSection must be representation-polymorphic, to allow
+ (+# 4#) and (4# +#) to work. See
+ Note [Wired-in Ids for rebindable syntax] in GHC.Types.Id.Make.
+
+* leftSection and rightSection must be multiplicity-polymorphic.
+ (Test linear/should_compile/OldList showed this up.)
+
+* Because they are representation-polymorphic, we have to define them
+ as wired-in Ids, with compulsory inlining. See
+ GHC.Types.Id.Make.leftSectionId, rightSectionId.
+
+* leftSection is just ($) really; but unlike ($) it is
+ representation-polymorphic in the result type, so we can write
+ `(x +#)`, say.
+
+* The type of leftSection must have an arrow in its first argument,
+ because (x `ord`) should be rejected, because ord does not take two
+ arguments
+
+* It's important that we define leftSection in an eta-expanded way,
+ (i.e. not leftSection f = f), so that
+ (True `undefined`) `seq` ()
+ = (leftSection (undefined True) `seq` ())
+ evaluates to () and not undefined
+
+* If PostfixOperators is ON, then we expand a left section like this:
+ (e `op`) ==> op e
+ with no auxiliary function at all. Simple!
+
+* leftSection and rightSection switch on ImpredicativeTypes locally,
+ during Quick Look; see GHC.Tc.Gen.App.wantQuickLook. Consider
+ test DeepSubsumption08:
+ type Setter st t a b = forall f. Identical f => blah
+ (.~) :: Setter s t a b -> b -> s -> t
+ clear :: Setter a a' b (Maybe b') -> a -> a'
+ clear = (.~ Nothing)
+ The expansion look like (rightSection (.~) Nothing). So we must
+ instantiate `rightSection` first type argument to a polytype!
+ Hence the special magic in App.wantQuickLook.
+
+Historical Note [Desugaring operator sections]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+This Note explains some historical trickiness in desugaring left and
+right sections. That trickiness has completely disappeared now that
+we desugar to calls to 'leftSection` and `rightSection`, but I'm
+leaving it here to remind us how nice the new story is.
+
+Desugaring left sections with -XPostfixOperators is straightforward: convert
+(expr `op`) to (op expr).
+
+Without -XPostfixOperators it's a bit more tricky. At first it looks as if we
+can convert
+
+ (expr `op`)
+
+naively to
+
+ \x -> op expr x
+
+But no! expr might be a redex, and we can lose laziness badly this
+way. Consider
+
+ map (expr `op`) xs
+
+for example. If expr were a redex then eta-expanding naively would
+result in multiple evaluations where the user might only have expected one.
+
+So we convert instead to
+
+ let y = expr in \x -> op y x
+
+Also, note that we must do this for both right and (perhaps surprisingly) left
+sections. Why are left sections necessary? Consider the program (found in #18151),
+
+ seq (True `undefined`) ()
+
+according to the Haskell Report this should reduce to () (as it specifies
+desugaring via eta expansion). However, if we fail to eta expand we will rather
+bottom. Consequently, we must eta expand even in the case of a left section.
+
+If `expr` is actually just a variable, say, then the simplifier
+will inline `y`, eliminating the redundant `let`.
+
+Note that this works even in the case that `expr` is unlifted. In this case
+bindNonRec will automatically do the right thing, giving us:
+
+ case expr of y -> (\x -> op y x)
+
+See #18151.
+-}
+
+
+
+
+
+-----------------------------------------
+-- Bits and pieces for RecordDotSyntax.
+--
+-- See Note [Overview of record dot syntax] in GHC.Hs.Expr.
+
+-- mkGetField arg field calculates a get_field @field arg expression.
+-- e.g. z.x = mkGetField z x = get_field @x z
+mkGetField :: Name -> LHsExpr GhcRn -> LocatedAn NoEpAnns FieldLabelString -> HsExpr GhcRn
+mkGetField get_field arg field = unLoc (NE.head $ mkGet get_field (arg :| []) field)
+
+-- mkSetField a field b calculates a set_field @field expression.
+-- e.g mkSetSetField a field b = set_field @"field" a b (read as "set field 'field' to a on b").
+-- NB: the order of aruments is specified by GHC Proposal 583: HasField redesign.
+mkSetField :: Name -> LHsExpr GhcRn -> LocatedAn NoEpAnns FieldLabelString -> LHsExpr GhcRn -> HsExpr GhcRn
+mkSetField set_field a (L _ (FieldLabelString field)) b =
+ genHsApp (genHsApp (genHsVar set_field `genAppType` genHsTyLit field) b) a
+
+mkGet :: Name -> NonEmpty (LHsExpr GhcRn) -> LocatedAn NoEpAnns FieldLabelString -> NonEmpty (LHsExpr GhcRn)
+mkGet get_field l@(r :| _) (L _ (FieldLabelString field)) =
+ wrapGenSpan (genHsApp (genHsVar get_field `genAppType` genHsTyLit field) r) NE.<| l
+
+mkSet :: Name -> LHsExpr GhcRn -> (LocatedAn NoEpAnns FieldLabelString, LHsExpr GhcRn) -> LHsExpr GhcRn
+mkSet set_field acc (field, g) = wrapGenSpan (mkSetField set_field g field acc)
+
+-- mkProjection fields calculates a projection.
+-- e.g. .x = mkProjection [x] = getField @"x"
+-- .x.y = mkProjection [.x, .y] = (.y) . (.x) = getField @"y" . getField @"x"
+mkProjection :: Name -> Name -> NonEmpty FieldLabelString -> HsExpr GhcRn
+mkProjection getFieldName circName (field :| fields) = foldl' f (proj field) fields
+ where
+ f :: HsExpr GhcRn -> FieldLabelString -> HsExpr GhcRn
+ f acc field = genHsApps circName $ map wrapGenSpan [proj field, acc]
+
+ proj :: FieldLabelString -> HsExpr GhcRn
+ proj (FieldLabelString f) = genHsVar getFieldName `genAppType` genHsTyLit f
+
+-- mkProjUpdateSetField calculates functions representing dot notation record updates.
+-- e.g. Suppose an update like foo.bar = 1.
+-- We calculate the function \a -> setField @"foo" a (setField @"bar" (getField @"foo" a) 1).
+mkProjUpdateSetField :: Name -> Name -> LHsRecProj GhcRn (LHsExpr GhcRn) -> (LHsExpr GhcRn -> LHsExpr GhcRn)
+mkProjUpdateSetField get_field set_field (L _ (HsFieldBind { hfbLHS = (L _ (FieldLabelStrings flds')), hfbRHS = arg } ))
+ = let {
+ ; flds = NE.map (fmap (unLoc . dfoLabel)) flds'
+ ; final = last flds -- quux
+ ; fields = init flds -- [foo, bar, baz]
+ ; getters = \a -> foldl' (mkGet get_field) (a :| []) fields -- Ordered from deep to shallow.
+ -- [getField@"baz"(getField@"bar"(getField@"foo" a), getField@"bar"(getField@"foo" a), getField@"foo" a, a]
+ ; zips = \a -> (final, NE.head (getters a)) : zip (reverse fields) (tail (getters a)) -- Ordered from deep to shallow.
+ -- [("quux", getField@"baz"(getField@"bar"(getField@"foo" a)), ("baz", getField@"bar"(getField@"foo" a)), ("bar", getField@"foo" a), ("foo", a)]
+ }
+ in (\a -> foldl' (mkSet set_field) arg (zips a))
+ -- 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))))
+
+mkRecordDotUpd :: Name -> Name -> LHsExpr GhcRn -> [LHsRecUpdProj GhcRn] -> HsExpr GhcRn
+mkRecordDotUpd get_field set_field exp updates = foldl' fieldUpdate (unLoc exp) updates
+ where
+ fieldUpdate :: HsExpr GhcRn -> LHsRecUpdProj GhcRn -> HsExpr GhcRn
+ 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 )
import GHC.Tc.Gen.Expand( tcExpand )
import GHC.Tc.Gen.App
import GHC.Tc.Gen.Head
-import GHC.Tc.Gen.Do
import GHC.Tc.Gen.Bind ( tcLocalBinds )
import GHC.Tc.Gen.HsType
import GHC.Tc.Gen.Arrow
@@ -94,8 +93,6 @@ import GHC.Data.FastString (fastStringToShortText)
import Control.Monad
import qualified Data.List.NonEmpty as NE
-import qualified GHC.LanguageExtensions as LangExt
-
{-
************************************************************************
* *
@@ -299,11 +296,19 @@ tcCollectApp the_app res_ty
; tcApp the_app fun args res_ty }
---------------
-tcExpr :: HsExpr GhcRn
+tcExpr, tcExprNoExpand :: HsExpr GhcRn
-> ExpRhoType -- DeepSubsumption <=> when checking, this type
-- is deeply skolemised
-> TcM (HsExpr GhcTc)
+tcExpr e res_ty
+-- See Note [Typechecking by expansion: overview]
+ = do { mb_hse <- tcExpand e
+ ; case mb_hse of
+ Just hse -> tcHsExpansion hse res_ty
+ Nothing -> tcExprNoExpand e res_ty }
+
+
-- Use tcApp to typecheck applications, which are treated specially
-- by Quick Look. Specifically:
-- - HsVar lone variables, to ensure that they can get an
@@ -324,46 +329,46 @@ tcExpr :: HsExpr GhcRn
-- expression and try to break them up further
-- and then call tcApp on the maximal application chain.
-- See Note [Application chains and heads] in GHC.Tc.Gen.App
-tcExpr e@(HsVar {}) res_ty = tcApp e e [] res_ty
-tcExpr e@(ExprWithTySig {}) res_ty = tcApp e e [] res_ty
-tcExpr e@(XExpr (HsRecSelRn{})) res_ty = tcApp e e [] res_ty
-tcExpr e@(HsAppType {}) res_ty = tcCollectApp e res_ty
-tcExpr e@(HsApp {}) res_ty = tcCollectApp e res_ty
+tcExprNoExpand e@(HsVar {}) res_ty = tcApp e e [] res_ty
+tcExprNoExpand e@(ExprWithTySig {}) res_ty = tcApp e e [] res_ty
+tcExprNoExpand e@(XExpr (HsRecSelRn{})) res_ty = tcApp e e [] res_ty
+tcExprNoExpand e@(HsAppType {}) res_ty = tcCollectApp e res_ty
+tcExprNoExpand e@(HsApp {}) res_ty = tcCollectApp e res_ty
-- Typecheck an occurrence of an unbound Id
--
-- Some of these started life as a true expression hole "_".
-- Others might simply be variables that accidentally have no binding site.
-tcExpr (HsHole (HoleVar locc@(L _ occ))) res_ty
+tcExprNoExpand (HsHole (HoleVar locc@(L _ occ))) res_ty
= do { ty <- expTypeToType res_ty -- Allow Int# etc (#12531)
; her <- emitNewExprHole occ ty
; tcEmitBindingUsage bottomUE -- Holes fit any usage environment
-- (#18491)
; return (HsHole (HoleVar locc, her))
}
-tcExpr (HsHole HoleError) _ =
+tcExprNoExpand (HsHole HoleError) _ =
panic "GHC.Tc.Gen.Expr: tcExpr: HoleError: Not implemented"
-tcExpr e@(HsLit x lit) res_ty
+tcExprNoExpand e@(HsLit x lit) res_ty
= do { let lit_ty = hsLitType lit
; tcWrapResult e (HsLit x (convertLit lit)) lit_ty res_ty }
-tcExpr (HsPar x expr) res_ty
+tcExprNoExpand (HsPar x expr) res_ty
= do { expr' <- tcMonoLExprNC expr res_ty
; return (HsPar x expr') }
-tcExpr (HsPragE x prag expr) res_ty
+tcExprNoExpand (HsPragE x prag expr) res_ty
= do { expr' <- tcMonoLExpr expr res_ty
; return (HsPragE x (tcExprPrag prag) expr') }
-tcExpr (NegApp x expr neg_expr) res_ty
+tcExprNoExpand (NegApp x expr neg_expr) res_ty
= do { (expr', neg_expr')
<- tcSyntaxOp NegateOrigin neg_expr [SynAny] res_ty $
\[arg_ty] [arg_mult] ->
tcScalingUsage arg_mult $ tcCheckMonoExpr expr arg_ty
; return (NegApp x expr' neg_expr') }
-tcExpr e@(HsIPVar _ x) res_ty
+tcExprNoExpand e@(HsIPVar _ x) res_ty
= do { ip_ty <- newFlexiTyVarTy liftedTypeKind
-- Create a unification type variable of kind 'Type'.
-- (The type of an implicit parameter must have kind 'Type'.)
@@ -378,7 +383,7 @@ tcExpr e@(HsIPVar _ x) res_ty
(mkHsWrap wrap (mkHsVar (noLocA ip_op)))
ip_ty res_ty }
-tcExpr e@(HsLam x lam_variant matches) res_ty
+tcExprNoExpand e@(HsLam x lam_variant matches) res_ty
= do { (wrap, matches') <- tcLambdaMatches e lam_variant matches [] res_ty
; return (mkHsWrap wrap $ HsLam x lam_variant matches') }
@@ -390,7 +395,7 @@ tcExpr e@(HsLam x lam_variant matches) res_ty
************************************************************************
-}
-tcExpr e@(HsOverLit _ lit) res_ty
+tcExprNoExpand e@(HsOverLit _ lit) res_ty
= -- See Note [Typechecking overloaded literals]
do { mb_res <- tcShortCutLit lit res_ty
-- See Note [Short cut for overloaded literals] in GHC.Tc.Utils.TcMType
@@ -426,7 +431,7 @@ tricky:
We can only take this short-cut if rebindable syntax is off; see `tcShortCutLit`.
-}
-tcExpr e@HsQualLit{} _ = pprPanic "tcExpr: HsQualLit" (ppr e)
+tcExprNoExpand e@HsQualLit{} _ = pprPanic "tcExpr: HsQualLit" (ppr e)
{-
************************************************************************
@@ -436,18 +441,19 @@ tcExpr e@HsQualLit{} _ = pprPanic "tcExpr: HsQualLit" (ppr e)
************************************************************************
-}
--- Explicit lists [e1,e2,e3] have been expanded already in the renamer
+-- Explicit lists [e1,e2,e3] have been expanded already in tcExpand
-- The expansion includes an ExplicitList, but it is always the built-in
-- list type, so that's all we need concern ourselves with here. See
-- GHC.Rename.Expr. Note [Handling overloaded and rebindable constructs]
-tcExpr (ExplicitList _ exprs) res_ty
- = do { res_ty <- expTypeToType res_ty
+tcExprNoExpand (ExplicitList x exprs) res_ty
+ = assert (isNoRebindable x) $
+ do { res_ty <- expTypeToType res_ty
; (coi, elt_ty) <- matchExpectedListTy res_ty
; let tc_elt expr = tcCheckPolyExpr expr elt_ty
; exprs' <- mapM tc_elt exprs
; return $ mkHsWrapCo coi $ ExplicitList elt_ty exprs' }
-tcExpr expr@(ExplicitTuple x tup_args boxity) res_ty
+tcExprNoExpand expr@(ExplicitTuple x tup_args boxity) res_ty
| all tupArgPresent tup_args
= do { let arity = length tup_args
tup_tc = tupleTyCon boxity arity
@@ -478,7 +484,7 @@ tcExpr expr@(ExplicitTuple x tup_args boxity) res_ty
; tcWrapResultMono expr expr' act_res_ty res_ty }
-tcExpr (ExplicitSum _ alt arity expr) res_ty
+tcExprNoExpand (ExplicitSum _ alt arity expr) res_ty
= do { let sum_tc = sumTyCon arity
; res_ty <- expTypeToType res_ty
; (coi, arg_tys) <- matchExpectedTyConApp sum_tc res_ty
@@ -505,12 +511,12 @@ tcExpr (ExplicitSum _ alt arity expr) res_ty
************************************************************************
-}
-tcExpr (HsLet x binds expr) res_ty
+tcExprNoExpand (HsLet x binds expr) res_ty
= do { (binds', expr') <- tcLocalBinds binds $
tcMonoLExpr expr res_ty
; return (HsLet x binds' expr') }
-tcExpr (HsCase ctxt scrut matches) res_ty
+tcExprNoExpand (HsCase ctxt scrut matches) res_ty
= do { -- We used to typecheck the case alternatives first.
-- The case patterns tend to give good type info to use
-- when typechecking the scrutinee. For example
@@ -532,13 +538,16 @@ tcExpr (HsCase ctxt scrut matches) res_ty
; matches' <- tcCaseMatches ctxt tcBody (Scaled mult scrut_ty) matches res_ty
; return (HsCase ctxt scrut' matches') }
-tcExpr (HsIf x pred b1 b2) res_ty
- = do { pred' <- tcCheckMonoExpr pred boolTy
+tcExprNoExpand (HsIf x pred b1 b2) res_ty
+ -- HsIf in rebindable case would be expanded out so we would not
+ -- have a Just RebindableSyntaxTable here, only Nothing
+ = assert (isNoRebindable x) $
+ do { pred' <- tcCheckMonoExpr pred boolTy
; let res_ty' = adjustExpTypeForCaseBranches res_ty [b1,b2]
; (u1,b1') <- tcCollectingUsage $ tcMonoLExpr b1 res_ty'
; (u2,b2') <- tcCollectingUsage $ tcMonoLExpr b2 res_ty'
; tcEmitBindingUsage (supUE u1 u2)
- ; return (HsIf x pred' b1' b2') }
+ ; return (HsIf noExtField pred' b1' b2') }
{-
Note [MultiWayIf linearity checking]
@@ -564,32 +573,16 @@ If we add linear guards, this code will have to be revisited.
Not using 'sup' caused #23814.
-}
-tcExpr (HsMultiIf _ alts) res_ty
+tcExprNoExpand (HsMultiIf _ alts) res_ty
= do { alts' <- tcGRHSNE IfAlt tcBody alts res_ty
-- See Note [MultiWayIf linearity checking]
; res_ty <- readExpType res_ty
; return (HsMultiIf res_ty alts') }
-tcExpr (HsDo _ do_or_lc stmts) res_ty
- | DoExpr{} <- do_or_lc
- -- ApplicativeDo are typechecked using tcDoStmts
- = do isApplicativeDo <- xoptM LangExt.ApplicativeDo
- if isApplicativeDo
- then tcDoStmts do_or_lc stmts res_ty
- -- Expand expression on the fly otherwise
- -- See Note [Typechecking by expansion: overview]
- else do { hse <- expandDoStmts do_or_lc stmts
- ; tcHsExpansion hse res_ty }
- | MDoExpr{} <- do_or_lc
- = do hse <- expandDoStmts do_or_lc stmts
- tcHsExpansion hse res_ty
- | otherwise
- -- ListComp and MonadComp are handled by legacy tcDoStmts for now,
- -- The ultimate goal is to handle them via expandDoStmts.
- -- GHCiStmts are handled completely separate
+tcExprNoExpand (HsDo _ do_or_lc stmts) res_ty
= tcDoStmts do_or_lc stmts res_ty
-tcExpr (HsProc x pat cmd) res_ty
+tcExprNoExpand (HsProc x pat cmd) res_ty
= do { (pat', cmd', coi) <- tcProc pat cmd res_ty
; return $ mkHsWrapCo coi (HsProc x pat' cmd') }
@@ -601,7 +594,7 @@ tcExpr (HsProc x pat cmd) res_ty
-- and wrap (static e) in a call to
-- fromStaticPtr :: IsStatic p => StaticPtr a -> p a
-tcExpr (HsStatic _ expr) res_ty
+tcExprNoExpand (HsStatic _ expr) res_ty
= do { res_ty <- expTypeToType res_ty
; (co, (p_ty, expr_ty)) <- matchExpectedAppTy res_ty
; (expr', lie) <- captureConstraints $
@@ -636,11 +629,11 @@ tcExpr (HsStatic _ expr) res_ty
expr''
}
-tcExpr (HsEmbTy _ _) _ = failWith (TcRnIllegalTypeExpr TypeKeywordSyntax)
-tcExpr (HsQual _ _ _) _ = failWith (TcRnIllegalTypeExpr ContextArrowSyntax)
-tcExpr (HsForAll _ _ _) _ = failWith (TcRnIllegalTypeExpr ForallTelescopeSyntax)
-tcExpr (HsFunArr _ _ _ _) _ = failWith (TcRnIllegalTypeExpr FunctionArrowSyntax)
-tcExpr (HsStar _) _ = failWith (TcRnIllegalTypeExpr StarKindSyntax)
+tcExprNoExpand (HsEmbTy _ _) _ = failWith (TcRnIllegalTypeExpr TypeKeywordSyntax)
+tcExprNoExpand (HsQual _ _ _) _ = failWith (TcRnIllegalTypeExpr ContextArrowSyntax)
+tcExprNoExpand (HsForAll _ _ _) _ = failWith (TcRnIllegalTypeExpr ForallTelescopeSyntax)
+tcExprNoExpand (HsFunArr _ _ _ _) _ = failWith (TcRnIllegalTypeExpr FunctionArrowSyntax)
+tcExprNoExpand (HsStar _) _ = failWith (TcRnIllegalTypeExpr StarKindSyntax)
{-
************************************************************************
@@ -650,7 +643,7 @@ tcExpr (HsStar _) _ = failWith (TcRnIllegalTypeExpr StarKindSyntax)
************************************************************************
-}
-tcExpr expr@(RecordCon { rcon_con = L loc qcon@(WithUserRdr _ con_name)
+tcExprNoExpand expr@(RecordCon { rcon_con = L loc qcon@(WithUserRdr _ con_name)
, rcon_flds = rbinds }) res_ty
= do { con_like <- tcLookupConLike qcon
@@ -688,11 +681,11 @@ tcExpr expr@(RecordCon { rcon_con = L loc qcon@(WithUserRdr _ con_name)
orig = OccurrenceOf con_name
-- Record updates via dot syntax are replaced by expanded expressions
--- in the renamer. See Note [Overview of record dot syntax] in
+-- in GHC.Tc.Expand. See Note [Overview of record dot syntax] in
-- GHC.Hs.Expr. This is why we match on 'rupd_flds = Left rbnds' here
-- and panic otherwise.
--- WIP: To be fixed soon expandRecordUpd needs to return HsExpansion and not a separate ds_res_ty
-tcExpr expr@(RecordUpd { rupd_expr = record_expr
+-- WIP: To be fixed soon (#27160) expandRecordUpd needs to return HsExpansion and not a separate ds_res_ty
+tcExprNoExpand expr@(RecordUpd { rupd_expr = record_expr
, rupd_flds =
RegularRecUpdFields
{ xRecUpdFields = possible_parents
@@ -719,7 +712,7 @@ tcExpr expr@(RecordUpd { rupd_expr = record_expr
}
}
-tcExpr e@(RecordUpd { rupd_flds = OverloadedRecUpdFields {}}) _
+tcExprNoExpand e@(RecordUpd { rupd_flds = OverloadedRecUpdFields {}}) _
= pprPanic "tcExpr: unexpected overloaded-dot RecordUpd" $ ppr e
{-
@@ -732,7 +725,7 @@ tcExpr e@(RecordUpd { rupd_flds = OverloadedRecUpdFields {}}) _
************************************************************************
-}
-tcExpr (ArithSeq _ witness seq) res_ty
+tcExprNoExpand (ArithSeq _ witness seq) res_ty
= tcArithSeq witness seq res_ty
{-
@@ -745,24 +738,20 @@ tcExpr (ArithSeq _ witness seq) res_ty
-- Here we get rid of it and add the finalizers to the global environment.
-- See Note [Delaying modFinalizers in untyped splices] in GHC.Rename.Splice.
-tcExpr (HsTypedSplice ext splice) res_ty = tcTypedSplice ext splice res_ty
-tcExpr e@(HsTypedBracket _ext body) res_ty = tcTypedBracket e body res_ty
-tcExpr e@(HsUntypedBracket ps body) res_ty = tcUntypedBracket e body ps res_ty
+tcExprNoExpand (HsTypedSplice ext splice) res_ty = tcTypedSplice ext splice res_ty
+tcExprNoExpand e@(HsTypedBracket _ext body) res_ty = tcTypedBracket e body res_ty
+tcExprNoExpand e@(HsUntypedBracket ps body) res_ty = tcUntypedBracket e body ps res_ty
{-
************************************************************************
* *
- Catch-all
+ Catch all Case
* *
************************************************************************
-}
--- See Note [Typechecking by expansion: overview]
-tcExpr e res_ty
- = do { mb_hse <- tcExpand e
- ; case mb_hse of
- Just hse -> tcHsExpansion hse res_ty
- Nothing -> pprPanic "tcExpr: unhandled case:" (ppr e) }
+-- We ought to have expanded out or handeled them above
+tcExprNoExpand e _ = pprPanic "tcExpr : unhandled case" $ ppr e
{-
************************************************************************
@@ -1656,7 +1645,7 @@ disambiguateRecordBinds record_expr record_rho possible_parents rbnds res_ty
RegularRecUpdFields
{ xRecUpdFields = parents
, recUpdFields = rbnds }
- , rupd_ext = noExtField }
+ , rupd_ext = NoRebindable }
loc = getLocA (head rbnds)
{-
=====================================
compiler/GHC/Tc/TyCl/PatSyn.hs
=====================================
@@ -1087,7 +1087,7 @@ tcPatToExpr args pat = go pat
go1 (ParPat _ pat) = fmap (HsPar noExtField) (go pat)
go1 (ListPat _ pats)
= do { exprs <- mapM go pats
- ; return $ ExplicitList noExtField exprs }
+ ; return $ ExplicitList NoRebindable exprs }
go1 (TuplePat _ pats box) = do { exprs <- mapM go pats
; return $ ExplicitTuple noExtField
(map (Present noExtField) exprs) box }
=====================================
compiler/GHC/Tc/Types/Origin.hs
=====================================
@@ -641,6 +641,7 @@ exprCtOrigin (XExpr (ExpandedThingRn (HSE o _))) = hsCtxtCtOrigin o
exprCtOrigin (XExpr (HsRecSelRn f)) = OccurrenceOfRecSel $ L (getLoc $ foLabel f) (foExt f)
hsCtxtCtOrigin :: HsCtxt -> CtOrigin
+hsCtxtCtOrigin (ExprCtxt (ExprWithTySig _ (L _ e) _)) = exprCtOrigin e
hsCtxtCtOrigin (ExprCtxt e) = exprCtOrigin e
hsCtxtCtOrigin (FunAppCtxt (FunAppCtxtExpr _ e) _) = exprCtOrigin e
hsCtxtCtOrigin (StmtErrCtxt{}) = DoStmtOrigin
=====================================
compiler/GHC/ThToHs.hs
=====================================
@@ -1227,6 +1227,8 @@ cvtl e = wrapLA (cvt e)
; let tele = setTelescopeBndrsNameSpace varName $
mkHsForAllVisTele noAnn tvs'
; return $ HsForAll noExtField tele body' }
+ cvt (ReSynBindsE m e) = do { e' <- cvt e
+ ; return $ XExpr (ReSynBinds (mk_mod m) e') }
{- | #16895 Ensure an infix expression's operator is a variable/constructor.
Consider this example:
=====================================
libraries/ghc-boot-th/GHC/Boot/TH/Ppr.hs
=====================================
@@ -1,4 +1,3 @@
-{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE LambdaCase #-}
{-# OPTIONS_GHC -Wno-x-partial #-}
-- | contains a prettyprinter for the
@@ -56,6 +55,9 @@ instance Ppr a => Ppr [a] where
instance Ppr Name where
ppr v = pprName v
+instance Ppr ModName where
+ ppr (ModName s) = text s
+
------------------------------
instance Ppr Info where
ppr (TyConI d) = ppr d
@@ -250,6 +252,7 @@ pprExp i (ForallE tvars body) =
parensIf (i >= funPrec) $ sep [pprForall tvars [], pprExp qualPrec body]
pprExp i (ConstrainedE ctx body) =
parensIf (i >= funPrec) $ sep [pprCtxWith pprExp ctx, pprExp qualPrec body]
+pprExp i (ReSynBindsE m e) = text "{{" <+> ppr m <+> text "}}" <+> pprExp i e
pprFields :: [(Name,Exp)] -> Doc
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
| ForallE [TyVarBndr Specificity] Exp -- ^ @forall \<vars\>. \<expr\>@
| ForallVisE [TyVarBndr ()] Exp -- ^ @forall \<vars\> -> \<expr\>@
| ConstrainedE [Exp] Exp -- ^ @\<ctxt\> => \<expr\>@
+ | ReSynBindsE ModName Exp -- Remember to use bindings from the specified modname
+ -- while typechecking a typed splice for rebindable syntax
deriving( Show, Eq, Ord, Generic )
-- | A (field name, expression) pair. See 'RecConE' and 'RecUpdE'.
=====================================
testsuite/tests/ghc-api/T25121_status.stdout
=====================================
@@ -46,7 +46,9 @@ X(ExprWithTySig) mismatch
X(UntypedSplice) mismatch
>>> HsUntypedSpliceResult (HsExpr (GhcPass 'Renamed))
<<< HsUntypedSpliceResult (GenLocated (EpAnn [TrailingAnn]) (HsType (GhcPass 'Renamed)))
-X(ExplicitList) match = NoExtField
+X(ExplicitList) mismatch
+ >>> RebindableSyntaxTable
+ <<< NoExtField
X(ExplicitTuple) match = NoExtField
X(Hole) match = HoleKind
=====================================
testsuite/tests/parser/should_fail/RecordDotSyntaxFail8.stderr
=====================================
@@ -2,11 +2,11 @@ RecordDotSyntaxFail8.hs:47:17: error: [GHC-39999]
• No instance for ‘HasField "quux1" Quux Quux’
arising from selecting the field ‘quux1’
NB: ‘HasField’ is not the built-in ‘GHC.Internal.Records.HasField’ class.
- • In the second argument of ‘($)’, namely ‘....bar.baz.quux1’
- In a stmt of a 'do' block: print @Quux $ ....baz.quux1
+ • In the second argument of ‘($)’, namely ‘a.foo.bar.baz.quux1’
+ In a stmt of a 'do' block: print @Quux $ a.foo.bar.baz.quux1
In the expression:
do let a = Foo {foo = ...}
- print @Quux $ ....quux1
+ print @Quux $ ....bar.baz.quux1
let b = myQuux
print @Quux $ b.quux2
let c = Foo {foo = ...}
@@ -20,7 +20,7 @@ RecordDotSyntaxFail8.hs:50:17: error: [GHC-39999]
In a stmt of a 'do' block: print @Quux $ b.quux2
In the expression:
do let a = Foo {foo = ...}
- print @Quux $ ....quux1
+ print @Quux $ ....bar.baz.quux1
let b = myQuux
print @Quux $ b.quux2
let c = Foo {foo = ...}
@@ -30,11 +30,11 @@ RecordDotSyntaxFail8.hs:53:17: error: [GHC-39999]
• No instance for ‘HasField "quux3" Quux r0’
arising from selecting the field ‘quux3’
NB: ‘HasField’ is not the built-in ‘GHC.Internal.Records.HasField’ class.
- • In the second argument of ‘($)’, namely ‘....baz.quux3.wob’
- In a stmt of a 'do' block: print @Bool $ ....quux3.wob
+ • In the second argument of ‘($)’, namely ‘a.foo.bar.baz.quux3.wob’
+ In a stmt of a 'do' block: print @Bool $ a.foo.bar.baz.quux3.wob
In the expression:
do let a = Foo {foo = ...}
- print @Quux $ ....quux1
+ print @Quux $ ....bar.baz.quux1
let b = myQuux
print @Quux $ b.quux2
let c = Foo {foo = ...}
=====================================
testsuite/tests/parser/should_fail/RecordDotSyntaxFail9.stderr
=====================================
@@ -1,7 +1,7 @@
RecordDotSyntaxFail9.hs:7:11: error: [GHC-18872]
• Couldn't match type ‘Int’ with ‘[Char]’
arising from selecting the field ‘foo’
- • In the expression: a.foo
+ • In the expression: a.foo :: String
In a pattern binding: _ = a.foo :: String
In a stmt of a 'do' block: let _ = a.foo :: String
=====================================
testsuite/tests/rebindable/T19918.stdout
=====================================
@@ -13,4 +13,4 @@
[("negate",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 63, srcLocStartCol = 11, srcLocEndLine = 63, srcLocEndCol = 17})]
[("a use of syntactic negation",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 64, srcLocStartCol = 11, srcLocEndLine = 64, srcLocEndCol = 14})]
[(">>",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 65, srcLocStartCol = 14, srcLocEndLine = 65, srcLocEndCol = 16})]
-[("a do statement",SrcLoc {srcLocPackage = "main", srcLocModule = "Main", srcLocFile = "T19918.hs", srcLocStartLine = 66, srcLocStartCol = 16, srcLocEndLine = 66, srcLocEndCol = 18})]
+[("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 +1 @@
-25
\ No newline at end of file
+10
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/bb7d52fd6397872f27a99b8dd7414d214c5d966e...c22f51edbf90011a7fda7a9a38cf73e3869ef995
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/bb7d52fd6397872f27a99b8dd7414d214c5d966e...c22f51edbf90011a7fda7a9a38cf73e3869ef995
You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help