[Git][ghc/ghc][master] GHC.HsToCore.Quote: Quote \cases with the correct type
by Marge Bot (@marge-bot) 22 Nov '26
by Marge Bot (@marge-bot) 22 Nov '26
22 Nov '26
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
cfd4fb67 by Ryan Scott at 2026-11-22T16:36:59-05:00
GHC.HsToCore.Quote: Quote \cases with the correct type
Previously, `\cases` expressions inside of Template Haskell quotes would
incorrectly use the `Match` type instead of `Clause` for the element type. We
now use `nonEmptyCoreList` when quoting `\cases`, which infers the correct type
automatically. This works because `\cases` has an invariant that the list of
clauses is always non-empty.
Fixes #27826.
- - - - -
3 changed files:
- compiler/GHC/HsToCore/Quote.hs
- + testsuite/tests/th/T27826.hs
- testsuite/tests/th/all.T
Changes:
=====================================
compiler/GHC/HsToCore/Quote.hs
=====================================
@@ -1604,7 +1604,10 @@ repE (HsLam _ LamCase (MG { mg_alts = L _ ms }))
; repLamCase core_ms }
repE (HsLam _ LamCases (MG { mg_alts = (L _ ms) }))
= do { ms' <- mapM repClauseTup ms
- ; core_ms <- coreListM matchTyConOcc ms'
+ -- Safety: \cases has an invariant that `mg_alts` is
+ -- non-empty, so calling `nonEmptyCoreList` below is
+ -- always safe.
+ ; let core_ms = nonEmptyCoreList ms'
; repLamCases core_ms }
repE (HsApp _ x y) = do {a <- repLE x; b <- repLE y; repApp a b}
repE (HsAppType _ e t) = do { a <- repLE e
=====================================
testsuite/tests/th/T27826.hs
=====================================
@@ -0,0 +1,8 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE TemplateHaskellQuotes #-}
+module T27826 where
+
+import Language.Haskell.TH
+
+foo :: Q Exp
+foo = [| \cases x -> x |]
=====================================
testsuite/tests/th/all.T
=====================================
@@ -657,6 +657,7 @@ test('T8306_th', only_ways(['ghci']), ghci_script, ['T8306_th.script'])
test('T26862_th', only_ways(['ghci']), ghci_script, ['T26862_th.script'])
test('T27022', normal, compile_and_run, [''])
test('T27034', normal, compile, ['-v0 -ddump-splices -dsuppress-uniques'])
+test('T27826', normal, compile, [''])
test('T20902', normal, compile, [''])
test('TH_cvt_DefaultDataInstDecl', normal, compile_fail, ['-v0'])
test('TH_cvt_IllegalDeclaration', normal, compile_fail, ['-v0'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/cfd4fb67e963e0202e142cb4d1919f3…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/cfd4fb67e963e0202e142cb4d1919f3…
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
1
0
[Git][ghc/ghc][master] `ghc -M`: Add support for link nodes to json output
by Marge Bot (@marge-bot) 22 Nov '26
by Marge Bot (@marge-bot) 22 Nov '26
22 Nov '26
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
2091b89a by fendor at 2026-11-22T16:36:17-05:00
`ghc -M`: Add support for link nodes to json output
`LinkNode`s are part of the module graph and indicate that a certain
linking artefact is to be produced from other module graph nodes.
We expose `LinkNode`s in the output of `ghc -M -dep-json`, allowing
consumers to see when a linking artefact is to be produced.
Only the JSON output format of `ghc -M` supports `LinkNode` as it is
unclear how the Makefile output should be retrofitted to express the
dependencies, and whether it would require a feature guard.
Closes #28007
- - - - -
24 changed files:
- + changelog.d/make-depends-link-nodes
- compiler/GHC/Driver/MakeFile.hs
- docs/users_guide/make-depends-json-schema-1_0.json
- testsuite/tests/driver/mkdepend/all.T
- + testsuite/tests/driver/mkdepend/mhu04/app/Main.hs
- + testsuite/tests/driver/mkdepend/mhu04/app/Utils.hs
- + testsuite/tests/driver/mkdepend/mhu04/lib/Lib.hs
- + testsuite/tests/driver/mkdepend/mhu04/lib/Lib/Internal.hs
- + testsuite/tests/driver/mkdepend/mhu04/unitApp
- + testsuite/tests/driver/mkdepend/mhu04/unitLib
- + testsuite/tests/driver/mkdepend/mhu05/app/Main.hs
- + testsuite/tests/driver/mkdepend/mhu05/lib/Lib.hs
- + testsuite/tests/driver/mkdepend/mhu05/lib/Lib/Internal.hs
- + testsuite/tests/driver/mkdepend/mhu05/test/Spec.hs
- + testsuite/tests/driver/mkdepend/mhu05/unitApp
- + testsuite/tests/driver/mkdepend/mhu05/unitLib
- + testsuite/tests/driver/mkdepend/mhu05/unitTest
- + testsuite/tests/driver/mkdepend/mkdepend02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend02/Main.hs
- + testsuite/tests/driver/mkdepend/mkdepend_bkp_01/bkp01.bkp
- + testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-makefile
Changes:
=====================================
changelog.d/make-depends-link-nodes
=====================================
@@ -0,0 +1,4 @@
+section: compiler
+synopsis: Expose link nodes in `ghc -M -dep-json` output
+issues: #28007
+mrs: !16848
=====================================
compiler/GHC/Driver/MakeFile.hs
=====================================
@@ -44,6 +44,7 @@ import GHC.Types.Unique.Set (UniqSet)
import GHC.Types.Unique.Set qualified as UniqSet
import GHC.Types.UnresolvedImport
+import GHC.Unit.Env qualified as UnitEnv
import GHC.Unit.Finder
import GHC.Unit.Home.Graph (HomeUnitEnv (homeUnitEnv_dflags))
import GHC.Unit.Info
@@ -189,9 +190,11 @@ doMkDependModuleGraph dflags module_graph = do
-- | A 'DepNode' is a direct translation of a 'ModuleGraphNode' that
-- can be serialised to a Makefile or json lines format.
-data DepNode =
- ModuleDepNode HomeModuleNode [Dep]
- -- ^ A dependency node of a home module with its dependencies
+data DepNode
+ = ModuleDepNode HomeModuleNode [Dep]
+ -- ^ A dependency node of a home module with its dependencies.
+ | LinkDepNode DepLink [DepLinkNode]
+ -- ^ A link node is the result of linking some elements from the module graph.
-- | A home module node.
-- Everything we know about home modules that can be serialised.
@@ -221,6 +224,7 @@ data PreprocessingNode = PreprocessingNode
{ pn_preprocessor :: String
-- ^ The preprocessor.
, pn_arguments :: [String]
+ -- ^ Arguments to be passed to the preprocessor.
}
-- | A dependency edge on another module, or cpp path.
@@ -249,6 +253,33 @@ data Dep
-- ^ Path to the @#include@d path.
}
+-- | A link node in the module graph.
+data DepLink
+ = DepLink
+ { link_output :: !UnitId
+ -- ^ The 'UnitId' of the home unit we are performing linking on.
+ , link_type :: !GhcLink
+ -- ^ What is the type of this link node?
+ }
+
+-- | A linking dependency that makes up the requirements to link something.
+data DepLinkNode
+ = DepLink_Unit !UnitId
+ -- ^ A dependency on an ad-hoc instantiated unit.
+ --
+ -- At this point of time, such a dependency won't be generated, as @-M@
+ -- doesn't work with backpack, thus there will never be an ad-hoc instantiated unit.
+ | DepLink_Module !ModuleNameWithIsBoot !UnitId
+ -- ^ A dependency on a home module.
+ | DepLink_HomeUnit {-# UNPACK #-} !UnitId
+ -- ^ A dependency on the linking node of a home unit.
+ -- This is useful when the linking output of a home unit depends on the linking node of
+ -- another home unit.
+ | DepLink_ExtUnit {-# UNPACK #-} !UnitId
+ -- ^ A dependency on an external unit, i.e. a dependency loaded from the 'UnitState'.
+ --
+ -- At this point of time, such a dependency won't be generated by 'downsweep'.
+
-- | 'DependencyWriter' is a backend for outputting 'DepNode' in a specific
-- output format.
data DependencyWriter = DependencyWriter
@@ -386,7 +417,21 @@ processDeps hsc_env _ (AcyclicSCC (InstantiationNode _uid node))
mkPlainErrorMsgEnvelope noSrcSpan $
GhcDriverMessage $ DriverInstantiationNodeInDependencyGeneration node
-processDeps _ _ (AcyclicSCC (LinkNode {})) = return Nothing
+processDeps hsc_env _ (AcyclicSCC (LinkNode keys unitId)) = do
+ let
+ toLinkNodeDep = \ case
+ NodeKey_Unit iu -> DepLink_Unit $ virtualUnitId iu
+ NodeKey_Module node -> DepLink_Module (mnkModuleName node) (mnkUnitId node)
+ NodeKey_Link uid -> DepLink_HomeUnit uid
+ NodeKey_ExternalUnit uid -> DepLink_ExtUnit uid
+
+ linkNode = DepLink
+ { link_output = unitId
+ , link_type = ghcLink $ UnitEnv.ue_unitFlags unitId (hsc_unit_env hsc_env)
+ }
+
+ pure $ Just $ LinkDepNode linkNode (map toLinkNodeDep keys)
+
processDeps _ _ (AcyclicSCC (UnitNode {})) = return Nothing
processDeps _ _ (AcyclicSCC (ModuleNode _ (ModuleNodeFixed {})))
-- No dependencies needed for fixed modules (already compiled)
@@ -507,6 +552,9 @@ initFileDepWriter logger root tmpfs tmpdir suffixes output = do
{ dw_writeDependency = \ case
ModuleDepNode node deps -> do
traverse_ (depStream_write stream) (dependencyRules root suffixes node deps)
+ LinkDepNode _node _deps -> do
+ -- Makefile can't handle 'LinkDepNode'
+ pure ()
, dw_endWriter = depStream_close stream
, dw_onError = depStream_onError stream
}
@@ -690,6 +738,8 @@ initJsonDepWriter logger tmpfs tmpdir output = do
depStream_write stream (renderJsonl payload)
-- Cache external deps we already reported in the past
updateJson json_var $ cacheExternalDepsJson newExtUnits
+ LinkDepNode node deps -> do
+ depStream_write stream $ renderJsonl $ linkNodeJson node deps
, dw_endWriter = depStream_close stream
, dw_onError = depStream_onError stream
}
@@ -757,7 +807,7 @@ renderJsonl output =
-- Payload for -dep-json
-- | State of the @-dep-json@ dependency generation.
-data DepJson = DepJson
+newtype DepJson = DepJson
{ externalDeps :: Set.Set ExtUnitDep
-- ^ The external units we have already published/generated.
-- We show each external unit exactly once, before the first time they are referenced.
@@ -769,13 +819,13 @@ data DepJson = DepJson
-- when a sensible default can be assumed.
-- For example, the @boot@ is only present in the final json object, if it is 'IsBoot'.
data HomeUnitDep = HomeUnitDep
- { unitId :: UnitId
- , packageName :: Maybe String
- , modWithIsBoot :: ModuleWithIsBoot
- , source :: OsPath
- , imports :: ImportDeps
- , cpp :: Set.Set OsPath
- , preprocessor :: Maybe PreprocessingNode
+ { unitId :: !UnitId
+ , packageName :: !(Maybe String)
+ , modWithIsBoot :: !ModuleWithIsBoot
+ , source :: !OsPath
+ , imports :: !ImportDeps
+ , cpp :: !(Set.Set OsPath)
+ , preprocessor :: !(Maybe PreprocessingNode)
}
addImport :: ImportDep -> HomeUnitDep -> HomeUnitDep
@@ -805,9 +855,9 @@ newtype ImportDeps = ImportDeps
-- 'IsBootInterface' if it is 'IsBoot'. This allows us to express the default case (a normal, non-source import)
-- as simply the module name.
data ImportDep = ImportDep
- { imp_mod :: Module
- , imp_level :: ImportLevel
- , imp_isBoot :: IsBootInterface
+ { imp_mod :: !Module
+ , imp_level :: !ImportLevel
+ , imp_isBoot :: !IsBootInterface
} deriving (Eq, Ord)
mkImportDep :: Module -> ImportLevel -> IsBootInterface -> ImportDep
@@ -818,10 +868,10 @@ mkImportDep modl level isBoot = ImportDep
}
data ExtUnitDep = ExtUnitDep
- { extUnitId :: UnitId
+ { extUnitId :: !UnitId
-- ^ The 'UnitId' of a unit. This is assumed to be globally unique.
, extUnitName :: String
- , extUnitPackageId :: DPackageId
+ , extUnitPackageId :: !DPackageId
} deriving (Eq, Ord)
newtype DPackageId = DPackageId PackageId
@@ -830,11 +880,30 @@ newtype DPackageId = DPackageId PackageId
instance Ord DPackageId where
DPackageId (PackageId d1) `compare` DPackageId (PackageId d2) = d1 `lexicalCompareFS` d2
+-- | Json representation of a 'LinkNode'.
+data LinkNodeDep = LinkNodeDep
+ { linkNodeUid :: !UnitId
+ -- ^ The 'UnitId' of the home unit we are producing a link node for.
+ , linkNodeType :: !GhcLink
+ , linkNodeModuleDeps :: !(Map.Map UnitId (Set.Set ModuleNameWithIsBoot))
+ -- ^ Module dependencies grouped by 'UnitId'.
+ , linkNodeUnitDeps :: !(Set.Set UnitId)
+ -- ^ Backpack unit instantiation.
+ , linkNodeHomeUnitDeps :: !(Set.Set UnitId)
+ -- ^ Dependencies on other home unit 'LinkNode's.
+ , linkNodeExtUnitDeps :: !(Set.Set UnitId)
+ -- ^ Dependencies on external 'UnitId's.
+ }
{- Note [ghc -M -dep-json output format]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-The instance of 'ToJson' 'DepJson' must conform to the JSON schema
-specified in docs/users_guide/make-depends-json-schema-1_0.json.
+The following instances must conform to the JSON schema:
+
+* 'ToJson' 'HomeUnitDep'
+* 'ToJson' 'ExtUnitDep'
+* 'ToJson' 'LinkNodeDep'
+
+The instances must conform to docs/users_guide/make-depends-json-schema-1_0.json.
When the schema is altered, please bump the version.
If the content is altered in a backwards compatible way,
update the minor version (e.g. 1.3 ~> 1.4).
@@ -933,6 +1002,50 @@ instance ToJson ExtUnitDep where
where
showPackageId (DPackageId (PackageId pid)) = unpackFS pid
+-- See Note [ghc -M -dep-json output format]
+instance ToJson LinkNodeDep where
+ json LinkNodeDep{linkNodeUid, linkNodeType, linkNodeModuleDeps, linkNodeUnitDeps, linkNodeHomeUnitDeps, linkNodeExtUnitDeps} =
+ JSObject
+ [ ("unit-id", JSString $ unitIdString linkNodeUid)
+ , ("link-type", linkTypeJson linkNodeType)
+ , ("links", JSArray $ concat
+ [ map renderMods (Map.toList linkNodeModuleDeps)
+ , map (JSString . unitIdString) (Set.toList linkNodeUnitDeps)
+ , map (JSString . unitIdString) (Set.toList linkNodeHomeUnitDeps)
+ , map (JSString . unitIdString) (Set.toList linkNodeExtUnitDeps)
+ ])
+ ]
+ where
+ linkTypeJson :: GhcLink -> JsonDoc
+ linkTypeJson = JSString . \ case
+ NoLink{} -> panic "Received -no-link, but a link node must not exist with -no-link."
+ LinkExecutable{} -> "executable"
+ LinkInMemory{} -> "in-memory"
+ LinkDynLib{} -> "dynamic-library"
+ LinkBytecodeLib{} -> "bytecode-library"
+ LinkStaticLib{} -> "static-library"
+ LinkMergedObj{} -> "merged-object"
+
+ renderMods (u, ms) =
+ JSObject
+ [ ("unit-id", JSString $ unitIdString u)
+ , ("modules", JSArray $ map moduleKey (Set.toList ms))
+ ]
+
+
+ moduleNameJson m = JSString $ moduleNameString m
+
+ moduleKey :: ModuleNameWithIsBoot -> JsonDoc
+ moduleKey t =
+ case gwib_isBoot t of
+ NotBoot -> moduleNameJson (gwib_mod t)
+ IsBoot -> JSObject
+ [ ("module", moduleNameJson (gwib_mod t))
+ -- Redundant check, but the compiler will fix it and
+ -- this feels like it might avoid bugs in the future.
+ , ("boot", JSBool $ gwib_isBoot t == IsBoot)
+ ]
+
cacheExternalDepsJson :: Set.Set ExtUnitDep -> DepJson -> DepJson
cacheExternalDepsJson extUnits (DepJson e0) =
DepJson
@@ -955,7 +1068,7 @@ homeUnitDeps HomeModuleNode {..} deps =
, imports = ImportDeps Map.empty
}
- go (extDeps, node_data) = \ case
+ go (!extDeps, node_data) = \ case
DepHi {dep_mod, dep_local, dep_unit, dep_boot, dep_level}
| dep_local
-> (extDeps, addImport (mkImportDep dep_mod dep_level dep_boot) node_data)
@@ -982,6 +1095,32 @@ homeUnitDeps HomeModuleNode {..} deps =
DepCpp {dep_path} ->
(extDeps, addCpp dep_path node_data)
+linkNodeJson :: DepLink -> [DepLinkNode] -> LinkNodeDep
+linkNodeJson (DepLink uid linkType) deps =
+ LinkNodeDep
+ { linkNodeUid = uid
+ , linkNodeType = linkType
+ , linkNodeModuleDeps = allMods
+ , linkNodeUnitDeps = units
+ , linkNodeHomeUnitDeps = homeUids
+ , linkNodeExtUnitDeps = extUids
+ }
+ where
+ (!extUids, !homeUids, !units, !allMods) = foldl' go (Set.empty, Set.empty, Set.empty, Map.empty) deps
+
+ go (ext, homeUid, unit, mods) = \ case
+ DepLink_Module modName u ->
+ let
+ newMods = Map.insertWith (Set.union) u (Set.singleton modName) mods
+ in
+ (ext, homeUid, unit, newMods)
+ DepLink_Unit uid ->
+ (ext, homeUid, Set.insert uid unit, mods)
+ DepLink_HomeUnit uid ->
+ (ext, Set.insert uid homeUid, unit, mods)
+ DepLink_ExtUnit uid ->
+ (Set.insert uid ext, homeUid, unit, mods)
+
-----------------------------------------------------------------
-- Module cycles
-----------------------------------------------------------------
=====================================
docs/users_guide/make-depends-json-schema-1_0.json
=====================================
@@ -3,8 +3,9 @@
"title": "GHC dependencies",
"description": "The dependency graph of a Haskell program.",
"oneOf": [
- { "$ref": "#/definitions/home-module" },
- { "$ref": "#/definitions/external-unit" }
+ { "$ref": "#/definitions/external-unit" },
+ { "$ref": "#/definitions/module" },
+ { "$ref": "#/definitions/link" }
],
"definitions": {
"external-unit": {
@@ -29,17 +30,17 @@
"module-name": {
"type": "string"
},
- "home-module": {
+ "module": {
"type": "object",
"properties": {
"module": { "$ref": "#/definitions/module-name" },
"unit-id": { "$ref": "#/definitions/unit-id" },
"package-name": { "$ref": "#/definitions/package-name" },
- "source": { "$ref": "#/definitions/home-module-source" },
- "boot": { "type": "boolean" },
+ "source": { "$ref": "#/definitions/module-source" },
+ "boot": { "$ref": "#/definitions/boot" },
"includes": {
"type": "array",
- "items": { "$ref": "#/definitions/home-module-include" }
+ "items": { "$ref": "#/definitions/module-include" }
},
"imports": {
"type": "object",
@@ -48,15 +49,15 @@
"items": { "$ref": "#/definitions/import" }
}
},
- "preprocessor": { "$ref": "#/definitions/home-module-preprocessor" }
+ "preprocessor": { "$ref": "#/definitions/module-preprocessor" }
},
"required": ["module", "unit-id", "source"],
"unevaluatedProperties": false
},
- "home-module-source": {
+ "module-source": {
"type": "string"
},
- "home-module-include": {
+ "module-include": {
"type": "string"
},
"home-module-preprocessor": {
@@ -81,17 +82,66 @@
"properties": {
"module": { "$ref": "#/definitions/module-name" },
"level": { "$ref": "#/definitions/import-level" },
- "boot": { "type": "boolean" }
+ "boot": { "$ref": "#/definitions/boot" }
},
"required": ["module"],
"unevaluatedProperties": false
}
]
},
+ "boot": {
+ "type": "boolean",
+ "default": false
+ },
"import-level": {
"type": "string",
"enum": ["normal", "quote", "splice"],
"default": "normal"
+ },
+ "link": {
+ "type": "object",
+ "link-type": { "$ref": "#/definitions/link-type" },
+ "properties": {
+ "links": {
+ "type": "array",
+ "items": { "$ref": "#/definitions/link-unit" }
+ }
+ }
+ },
+ "link-type": {
+ "type": "string",
+ "enum": [
+ "executable",
+ "in-memory",
+ "dynamic-library",
+ "bytecode-library",
+ "static-library",
+ "merged-object"
+ ]
+ },
+ "link-unit": {
+ "type": "object",
+ "properties": {
+ "unit-id": { "$ref": "#/definitions/unit-id" },
+ "modules": {
+ "type": "array",
+ "items": { "$ref": "#/definitions/link-module" }
+ }
+ },
+ "required": ["unit-id"]
+ },
+ "link-module": {
+ "oneOf": [
+ { "$ref": "#/definitions/module-name" },
+ {
+ "type": "object",
+ "properties": {
+ "module": { "$ref": "#/definitions/module-name" },
+ "boot": { "$ref": "#/definitions/boot" }
+ },
+ "required": ["module"]
+ }
+ ]
}
}
}
=====================================
testsuite/tests/driver/mkdepend/all.T
=====================================
@@ -41,9 +41,23 @@ test('mkdepend_mhu03',
, when(opsys('mingw32'), skip) # shell script preprocessor
],
make_depend_multiunit, [['mhu03/unitA'], ''])
+# Link nodes
+test('mkdepend_mhu04',
+ [ extra_files(['mhu04/']), dep_makefile, dep_json ],
+ make_depend_multiunit, [['mhu04/unitLib', 'mhu04/unitApp'], ''])
+test('mkdepend_mhu05',
+ [ extra_files(['mhu05/']), dep_makefile, dep_json ],
+ make_depend_multiunit, [['mhu05/unitLib', 'mhu05/unitApp', 'mhu05/unitTest'], ''])
# Honour -F
test('mkdepend01',
[ extra_files(['mkdepend01/']), dep_makefile, dep_json ],
make_depend, [['mkdepend01/A.hs'], '-pgmF pp'])
-
+# Link nodes
+test('mkdepend02',
+ [ extra_files(['mkdepend02/']), dep_json ],
+ make_depend, [['mkdepend02/Main.hs'], ''])
+# Backpack
+test('mkdepend_bkp_01',
+ [ extra_files(['mkdepend_bkp_01/']), dep_json, expect_fail ],
+ make_depend, [['mkdepend_bkp_01/bkp01.bkp'], ''])
=====================================
testsuite/tests/driver/mkdepend/mhu04/app/Main.hs
=====================================
@@ -0,0 +1,7 @@
+module Main (main) where
+
+import Lib (greeting)
+import Utils (shout)
+
+main :: IO ()
+main = putStrLn (shout greeting)
=====================================
testsuite/tests/driver/mkdepend/mhu04/app/Utils.hs
=====================================
@@ -0,0 +1,6 @@
+module Utils (shout) where
+
+import Data.Char (toUpper)
+
+shout :: String -> String
+shout = map toUpper
=====================================
testsuite/tests/driver/mkdepend/mhu04/lib/Lib.hs
=====================================
@@ -0,0 +1,6 @@
+module Lib (greeting) where
+
+import Lib.Internal (name)
+
+greeting :: String
+greeting = "Hello, " ++ name
=====================================
testsuite/tests/driver/mkdepend/mhu04/lib/Lib/Internal.hs
=====================================
@@ -0,0 +1,4 @@
+module Lib.Internal (name) where
+
+name :: String
+name = "world"
=====================================
testsuite/tests/driver/mkdepend/mhu04/unitApp
=====================================
@@ -0,0 +1 @@
+-i -i. -working-dir=mhu04/app -this-unit-id app -this-package-name app -package-id lib -o app Main
=====================================
testsuite/tests/driver/mkdepend/mhu04/unitLib
=====================================
@@ -0,0 +1 @@
+-i -i. -working-dir=mhu04/lib -this-unit-id lib -this-package-name lib Lib Lib.Internal
=====================================
testsuite/tests/driver/mkdepend/mhu05/app/Main.hs
=====================================
@@ -0,0 +1,6 @@
+module Main (main) where
+
+import Lib (greeting)
+
+main :: IO ()
+main = putStrLn greeting
=====================================
testsuite/tests/driver/mkdepend/mhu05/lib/Lib.hs
=====================================
@@ -0,0 +1,6 @@
+module Lib (greeting) where
+
+import Lib.Internal (name)
+
+greeting :: String
+greeting = "Hello, " ++ name
=====================================
testsuite/tests/driver/mkdepend/mhu05/lib/Lib/Internal.hs
=====================================
@@ -0,0 +1,4 @@
+module Lib.Internal (name) where
+
+name :: String
+name = "world"
=====================================
testsuite/tests/driver/mkdepend/mhu05/test/Spec.hs
=====================================
@@ -0,0 +1,9 @@
+module Spec (main) where
+
+import Lib (greeting)
+import Lib.Internal (name)
+
+main :: IO ()
+main
+ | greeting == "Hello, " ++ name = putStrLn "OK"
+ | otherwise = error "unexpected greeting"
=====================================
testsuite/tests/driver/mkdepend/mhu05/unitApp
=====================================
@@ -0,0 +1 @@
+-i -i. -working-dir=mhu05/app -this-unit-id app -this-package-name app -package-id lib -o app Main
=====================================
testsuite/tests/driver/mkdepend/mhu05/unitLib
=====================================
@@ -0,0 +1 @@
+-i -i. -working-dir=mhu05/lib -this-unit-id lib -this-package-name lib -staticlib Lib Lib.Internal
=====================================
testsuite/tests/driver/mkdepend/mhu05/unitTest
=====================================
@@ -0,0 +1 @@
+-i -i. -working-dir=mhu05/test -this-unit-id test -this-package-name test -package-id lib -main-is Spec -o test Spec
=====================================
testsuite/tests/driver/mkdepend/mkdepend02.dep-json
=====================================
@@ -0,0 +1,2 @@
+{"module":"Main","unit-id":"main","imports":{},"source":"mkdepend02/Main.hs"}
+{"unit-id":"main","link-type":"executable","links":[{"unit-id":"main","modules":["Main"]}]}
=====================================
testsuite/tests/driver/mkdepend/mkdepend02/Main.hs
=====================================
@@ -0,0 +1,3 @@
+module Main where
+
+main = putStrLn "Hello, World"
=====================================
testsuite/tests/driver/mkdepend/mkdepend_bkp_01/bkp01.bkp
=====================================
@@ -0,0 +1,20 @@
+unit p where
+ signature H where
+ data T
+ x :: Bool
+ module A where
+ import H
+ data A = MkA T
+ y = x
+
+unit q where
+ dependency p[H=<H>]
+
+unit h where
+ module H where
+ data T = T
+ x = True
+
+unit r where
+ dependency h
+ dependency q[H=h:H]
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-json
=====================================
@@ -0,0 +1,5 @@
+{"module":"Lib.Internal","unit-id":"lib","imports":{},"package-name":"lib","source":"mhu04/lib/Lib/Internal.hs"}
+{"module":"Lib","unit-id":"lib","imports":{"lib":["Lib.Internal"]},"package-name":"lib","source":"mhu04/lib/Lib.hs"}
+{"module":"Utils","unit-id":"app","imports":{},"package-name":"app","source":"mhu04/app/Utils.hs"}
+{"module":"Main","unit-id":"app","imports":{"app":["Utils"],"lib":["Lib"]},"package-name":"app","source":"mhu04/app/Main.hs"}
+{"unit-id":"app","link-type":"executable","links":[{"unit-id":"app","modules":["Main","Utils"]}]}
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-makefile
=====================================
@@ -0,0 +1,9 @@
+# DO NOT DELETE: Beginning of Haskell dependencies
+mhu04/lib/Lib/Internal.o : mhu04/lib/Lib/Internal.hs
+mhu04/lib/Lib.o : mhu04/lib/Lib.hs
+mhu04/lib/Lib.o : mhu04/lib/Lib/Internal.hi
+mhu04/app/Utils.o : mhu04/app/Utils.hs
+mhu04/app/Main.o : mhu04/app/Main.hs
+mhu04/app/Main.o : mhu04/app/Utils.hi
+mhu04/app/Main.o : mhu04/lib/Lib.hi
+# DO NOT DELETE: End of Haskell dependencies
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-json
=====================================
@@ -0,0 +1,7 @@
+{"module":"Lib.Internal","unit-id":"lib","imports":{},"package-name":"lib","source":"mhu05/lib/Lib/Internal.hs"}
+{"module":"Lib","unit-id":"lib","imports":{"lib":["Lib.Internal"]},"package-name":"lib","source":"mhu05/lib/Lib.hs"}
+{"unit-id":"lib","link-type":"static-library","links":[{"unit-id":"lib","modules":["Lib","Lib.Internal"]}]}
+{"module":"Main","unit-id":"app","imports":{"lib":["Lib"]},"package-name":"app","source":"mhu05/app/Main.hs"}
+{"unit-id":"app","link-type":"executable","links":[{"unit-id":"app","modules":["Main"]}]}
+{"module":"Spec","unit-id":"test","imports":{"lib":["Lib","Lib.Internal"]},"package-name":"test","source":"mhu05/test/Spec.hs"}
+{"unit-id":"test","link-type":"executable","links":[{"unit-id":"test","modules":["Spec"]}]}
=====================================
testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-makefile
=====================================
@@ -0,0 +1,10 @@
+# DO NOT DELETE: Beginning of Haskell dependencies
+mhu05/lib/Lib/Internal.o : mhu05/lib/Lib/Internal.hs
+mhu05/lib/Lib.o : mhu05/lib/Lib.hs
+mhu05/lib/Lib.o : mhu05/lib/Lib/Internal.hi
+mhu05/app/Main.o : mhu05/app/Main.hs
+mhu05/app/Main.o : mhu05/lib/Lib.hi
+mhu05/test/Spec.o : mhu05/test/Spec.hs
+mhu05/test/Spec.o : mhu05/lib/Lib/Internal.hi
+mhu05/test/Spec.o : mhu05/lib/Lib.hi
+# DO NOT DELETE: End of Haskell dependencies
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/2091b89a2ebd8ac38c71bf0028e5ebe…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/2091b89a2ebd8ac38c71bf0028e5ebe…
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
1
0
[Git][ghc/ghc][master] 3 commits: NCG: List each destination of a jump table once
by Marge Bot (@marge-bot) 22 Nov '26
by Marge Bot (@marge-bot) 22 Nov '26
22 Nov '26
Marge Bot pushed to branch master at Glasgow Haskell Compiler / GHC
Commits:
01a5b0ac by Sylvain Henry at 2026-11-22T16:35:34-05:00
NCG: List each destination of a jump table once
jumpDestsOfInstr listed a block once per jump table entry that named
it. The linear register allocator makes a fixup block per listed
destination, so such a block got several fixup blocks. The patch of
the jump sends every entry to the first one. The other fixup blocks
were dead code, and the CFG had an edge to each of them.
jumpDestsOfInstr now lists each destination once, in every backend.
joinToTargets asserts it in debug builds.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
e4498112 by Andreas Klebinger at 2026-11-22T16:35:34-05:00
x86 ncg: Track the current block in NatM to keep the CFG in sync
The x86 NCG uses a CFG for code layout. When instruction selection
makes new blocks (word2Float#, cmpxchg loops, 64-bit shifts on i386),
it must add them to the CFG. Some sites did not. The CFG went out of
sync, the layout was bad, and the register allocator panicked when it
added fixup blocks (#27694, #27915).
NatM now keeps the current block in its state. Combinators update the
CFG and the current block together. See Note [Updating the CFG during
CodeGen] in GHC.CmmToAsm.Monad.
Other changes:
* -dasm-lint checks that the jumps in the code and the edges in the
CFG agree in both directions. This found a second desync: the CFG
did not follow the jumps that allocMoreStack retargets. The new
addPreentryBlock fixes it.
* The code must be emitted in generation order, because the CFG
records new blocks in that order. A store now generates the code of
its value before the code of its address, in the order it emits
them. Atomic operations take their address from the new
getNonClobberedAmode, so the code of their other operands cannot
clobber it.
Fixes #27694, #27915
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
f59fb957 by Sylvain Henry at 2026-11-22T16:35:34-05:00
x86 ncg: Maintain the CFG on i386
The i386 NCG now keeps its CFG in sync with the code (see the previous
commit), so backendMaintainsCfg is now True for i386. i386 gets the
CFG based code layout, dead code elimination and the -dasm-lint check,
like x86-64.
The compiler allocates more on i386: the CFG now goes through the
register allocator, branch shortcutting and optimizeCFG, which i386
skipped before. x86-64 already does this work.
Metric Increase:
CoOpt_Read
ManyAlternatives
T10421
T12425
T12707
T13056
T13253
T13253-spj
T13960
T15164
T15304
T15630
T15630a
T15703
T16577
T17516
T17836
T18140
T18282
T18304
T18698a
T18698b
T18730
T18923
T19695
T20049
T21839c
T24471
T26425
T26989
T5642
T6048
T783
T9233
T9630
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
24 changed files:
- + changelog.d/27694
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/AArch64/CodeGen.hs
- compiler/GHC/CmmToAsm/AArch64/Instr.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/Instr.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- + testsuite/tests/codeGen/should_compile/T27694.hs
- + testsuite/tests/codeGen/should_compile/T27694c.hs
- + testsuite/tests/codeGen/should_compile/T27694d.hs
- testsuite/tests/codeGen/should_compile/all.T
- + testsuite/tests/codeGen/should_run/T27694b.hs
- + testsuite/tests/codeGen/should_run/T27694b.stdout
- + testsuite/tests/codeGen/should_run/T27915.hs
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-32
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-64
- testsuite/tests/codeGen/should_run/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/83038fbee5efea8e3ebd5090b2ff55…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/83038fbee5efea8e3ebd5090b2ff55…
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
1
0
[Git][ghc/ghc] Pushed new branch wip/apk/fix-join-real-reg
by Andreas Klebinger (@AndreasK) 22 Nov '26
by Andreas Klebinger (@AndreasK) 22 Nov '26
22 Nov '26
Andreas Klebinger pushed new branch wip/apk/fix-join-real-reg at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/apk/fix-join-real-reg
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
1
0
[Git][ghc/ghc][wip/T28014] Pmc: Make pattern synonym matches lazy
by Sebastian Graf (@sgraf812) 22 Nov '26
by Sebastian Graf (@sgraf812) 22 Nov '26
22 Nov '26
Sebastian Graf pushed to branch wip/T28014 at Glasgow Haskell Compiler / GHC
Commits:
edd13012 by Sebastian Graf at 2026-11-22T19:14:57+01:00
Pmc: Make pattern synonym matches lazy
A match on a pattern synonym no longer implies that the scrutinee is not
bottom. The scrutinee is not bottom only when it failed to match a member of
an applicable COMPLETE pragma and no member of that pragma can match it.
Fixes #28014 and #17357.
- - - - -
10 changed files:
- + changelog.d/28014
- compiler/GHC/HsToCore/Pmc/Check.hs
- compiler/GHC/HsToCore/Pmc/Solver.hs
- compiler/GHC/HsToCore/Pmc/Solver/Types.hs
- testsuite/tests/pmcheck/should_compile/T17357.stderr
- + testsuite/tests/pmcheck/should_compile/T28014.hs
- + testsuite/tests/pmcheck/should_compile/T28014.stderr
- + testsuite/tests/pmcheck/should_compile/T28014b.hs
- + testsuite/tests/pmcheck/should_compile/T28014b.stderr
- testsuite/tests/pmcheck/should_compile/all.T
Changes:
=====================================
changelog.d/28014
=====================================
@@ -0,0 +1,14 @@
+section: compiler
+synopsis: The pattern-match checker no longer assumes that pattern synonym matches force their argument
+description:
+ A match on a pattern synonym excludes ⊥ as a value of the scrutinee only
+ through a ``COMPLETE`` set: when every member that can match at the type of
+ the scrutinee failed to match, and that type has a value other than ⊥.
+ Hence ``-Wredundant-bang-patterns`` and ``-Woverlapping-patterns`` no longer
+ report bangs or clauses as redundant or inaccessible when deleting them
+ would change the semantics, and ``-Wincomplete-patterns`` reports matches
+ that fail on ⊥ fields that a pattern synonym does not force. Redundancy that
+ rests on the strictness of a pattern synonym outside of an exhausted
+ ``COMPLETE`` set is no longer reported.
+issues: #28014 #17357
+mrs: !17033
=====================================
compiler/GHC/HsToCore/Pmc/Check.hs
=====================================
@@ -144,7 +144,7 @@ checkGrd grd = CA $ \inc -> case grd of
, cr_approx = Precise }
-- Con: Fall through on x ≁ K and refine with x ~ K ys and type info
PmCon x con tvs dicts args -> do
- !div <- if isPmAltConMatchStrict con
+ !div <- if isPmAltConMatchStrict con /= Just False
then addPhiCtNablas inc (PhiBotCt x)
else pure mempty
!matched <- addPhiCtNablas inc (PhiConCt x con tvs (map evVarPred dicts) args)
=====================================
compiler/GHC/HsToCore/Pmc/Solver.hs
=====================================
@@ -538,7 +538,7 @@ This distinction becomes apparent in #17248:
If we treat Newtypes like we treat regular DataCons, we would mark the third
clause as redundant, which clearly is unsound. The solution:
-1. 'isPmAltConMatchStrict' returns False for newtypes, indicating that a
+1. 'isPmAltConMatchStrict' returns @Just False@ for newtypes, indicating that a
newtype match is lazy.
2. When we find @x ~ T2 y@, transfer all constraints on @x@ (which involve @⊥@)
to @y@, similar to what 'equate' does, and don't add a @x ≁ ⊥@ constraint.
@@ -547,6 +547,117 @@ clause as redundant, which clearly is unsound. The solution:
3. Immediately reject when we find @x ≁ T2@.
Handling of Newtypes is also described in the Appendix of the Lower Your Guards paper,
where you can find the solution in a perhaps more digestible format.
+
+Note [Strictness of pattern synonym matches]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+TODO(sgraf): formulate. Points:
+
+* A match on a data constructor K forces x, so both x ~ K and x ≁ K imply
+ x ≁ ⊥. A match on a pattern synonym P need not force x (#28014, #17357):
+
+ pattern F :: a
+ pattern F <- (const False -> True)
+
+ withBang :: Bool -> Int
+ withBang F = 1
+ withBang !_ = 2 -- Bang not redundant: withBang undefined is ⊥,
+ -- but 2 without the bang
+
+ So neither x ~ P nor x ≁ P implies x ≁ ⊥ ('isPmAltConMatchStrict' is
+ 'Nothing').
+
+* A match on P may still diverge on ⊥, so the divergent set gets x ~ ⊥
+ ('isPmAltConMatchStrict' is not @Just False@). Example from #17357:
+
+ strictConst :: a -> b -> a
+ strictConst a b = seq b a
+ pattern SF <- (strictConst False -> True)
+
+ f2 :: Bool -> Bool -> ()
+ f2 _ True = ()
+ f2 SF True = () -- Inaccessible RHS, not redundant
+ f2 !_ True = ()
+ f2 _ _ = ()
+
+* Rule. Let C be a COMPLETE set from a pragma that applies at the type τ
+ of x. If x failed to match a member of C, and no member of C can match x,
+ then x ≁ ⊥. A member P cannot match x when x failed to match P, or when the
+ provided constraints of P contradict τ. The pragma asserts that matching
+ any value of τ, ⊥ included, against the members of C succeeds or diverges.
+ x ≁ ⊥ is a fact, so redundancy and coverage both use it.
+
+* Type constraints alone leave ⊥. Here no member of C = {G1, G2} (below)
+ can match at G Char, and x failed to match only F:
+
+ data U = MkU (G Char)
+ hc :: U -> Int
+ hc (MkU F) = 1 -- Not matched: MkU _
+
+* Matcher lemma, for the pragma assertion at a τ with a non-⊥ value.
+ $mP :: forall r. τ -> (args -> r) -> (Void# -> r) -> r.
+ By parametricity, $mP v k e ∈ {⊥, k args, e (##)}. By monotonicity in v,
+ if P fails on ⊥ without diverging, P fails on every value.
+ A non-⊥ value v of τ matches some member P of C. If P failed on ⊥
+ without diverging, P fails on v. Contradiction.
+
+* The vanilla COMPLETE set of a data type needs no rule. A failed match on a
+ data constructor gives x ≁ ⊥ already. If no data constructor failed but
+ the set has no inhabitant, τ has no data constructor, and ⊥ stays:
+
+ data T = MkT Void
+ h :: T -> Int
+ h (MkT F) = 1 -- Not matched: MkT _. Indeed h (MkT undefined) fails.
+
+* Implementation in the inhabitation test ('instantiate'). A residual
+ COMPLETE set from a pragma that lost a member witnesses a failed match on
+ that member ('matchedPragmaSets'). This covers synonyms with a required
+ theta, which are not in 'vi_neg'
+ (Note [Completeness checking with required Thetas]).
+ - Without such a set, offer ⊥ first, as before.
+ - Otherwise, search the residual COMPLETE sets for a non-⊥ inhabitant
+ ('instCompleteSets'). If there is none, offer ⊥ when each of these sets
+ has an inhabitant ('allInhabited').
+ The order is only a matter of performance
+ (Note [Shortcutting the inhabitation test]).
+ 'generateInhabitingPatterns' decides on a wildcard the same way.
+ Wrinkle: 'instCompleteSet' also removes a member that cannot match at the
+ type of x at the time of the test. A later type refinement that rules out
+ the remaining members then rules out ⊥ as well.
+
+* Example: every member failed.
+
+ pattern Nil :: [a]
+ pattern Nil <- (null -> True)
+ pattern Cons :: a -> [a] -> [a]
+ pattern Cons x xs <- (uncons -> Just (x, xs))
+ {-# COMPLETE Nil, Cons #-}
+
+ g :: [a] -> Int
+ g Nil = 0
+ g (Cons _ _) = 1 -- Exhaustive
+ g _ = 2 -- Redundant
+
+* Example: members that cannot match at τ.
+
+ data G a where { G1' :: G Int; G2' :: G Bool }
+ pattern G1 :: () => (a ~ Int) => G a
+ pattern G1 = G1'
+ pattern G2 :: () => (a ~ Bool) => G a
+ pattern G2 = G2'
+ {-# COMPLETE G1, G2 #-}
+
+ fb :: G Int -> Int
+ fb G1 = 1 -- Exhaustive: G2 cannot match at G Int
+
+* Precision loss: redundancy that rests on the strictness of P outside an
+ exhausted COMPLETE set is not reported.
+
+ pattern J :: a -> Maybe a
+ pattern J x = Just x
+
+ k :: Maybe Int -> Int
+ k (J _) = 1
+ k !_ = 2 -- Bang is dead, but not reported
-}
-------------------------
@@ -729,7 +840,7 @@ addNotConCt nabla x nalt = do
-- otherwise return updated entry and `Just x'` if `x` should be marked dirty,
-- where `x'` is the representative of `x`.
go :: VarInfo -> MaybeT DsM (Maybe Id, VarInfo)
- go vi@(VI x' pos neg _ rcm) = do
+ go vi@(VI x' pos neg bot rcm) = do
-- 1. Bail out quickly when nalt contradicts a solution
let contradicts nalt sol = eqPmAltCon (paca_con sol) nalt == Equal
guard (not (any (contradicts nalt) pos))
@@ -741,8 +852,10 @@ addNotConCt nabla x nalt = do
-- See Note [Completeness checking with required Thetas]
| hasRequiredTheta nalt = neg
| otherwise = extendPmAltConSet neg nalt
- massert (isPmAltConMatchStrict nalt)
- let vi' = vi{ vi_neg = neg', vi_bot = IsNotBot }
+ -- See Note [Strictness of pattern synonym matches]
+ let bot' | isPmAltConMatchStrict nalt == Just True = IsNotBot
+ | otherwise = bot
+ let vi' = vi{ vi_neg = neg', vi_bot = bot' }
-- 3. Make sure there's at least one other possible constructor
mb_rcm' <- lift (markMatched nalt rcm)
pure $ case mb_rcm' of
@@ -796,8 +909,9 @@ addConCt nabla@MkNabla{ nabla_tm_st = ts@TmSt{ ts_facts=env } } x alt tvs args =
MaybeBot -> pure (nabla_with MaybeBot)
IsBot -> addBotCt (nabla_with MaybeBot) y
IsNotBot -> addNotBotCt (nabla_with MaybeBot) y
- _ -> assert (isPmAltConMatchStrict alt )
- pure (nabla_with IsNotBot) -- strict match ==> not ⊥
+ _ | isPmAltConMatchStrict alt == Just True -> pure (nabla_with IsNotBot) -- strict match ==> not ⊥
+ -- See Note [Strictness of pattern synonym matches]
+ | otherwise -> pure (nabla_with bot)
equateTys :: [Type] -> [Type] -> [PhiCt]
equateTys ts us =
@@ -1372,8 +1486,31 @@ varNeedsTesting old_ty_st MkNabla{nabla_ty_st=new_ty_st} vi = do
-- remain that do not satisfy it. This lazy approach just
-- avoids doing unnecessary work.
instantiate :: Int -> Nabla -> VarInfo -> MaybeT DsM VarInfo
-instantiate fuel nabla vi = {-# SCC "instantiate" #-}
- (instBot fuel nabla vi <|> instCompleteSets fuel nabla vi)
+instantiate fuel nabla vi = {-# SCC "instantiate" #-} do
+ -- See Note [Strictness of pattern synonym matches]
+ matched <- lift (matchedPragmaSets vi)
+ if null matched
+ then instBot fuel nabla vi <|> instCompleteSets fuel nabla vi
+ else instCompleteSets fuel nabla vi <|> do
+ guard =<< lift (allInhabited fuel nabla (vi_id vi) matched)
+ instBot fuel nabla vi
+
+-- | The residual COMPLETE sets from pragmas that lost a member, for a variable
+-- that might be ⊥. When one of them has no inhabitant, the variable is not ⊥.
+-- See Note [Strictness of pattern synonym matches].
+matchedPragmaSets :: VarInfo -> DsM DsCompleteMatches
+matchedPragmaSets VI{ vi_bot = IsNotBot } = pure []
+matchedPragmaSets VI{ vi_rcm = rcm } = case rcm_pragmas rcm of
+ Nothing -> pure []
+ Just residuals -> do
+ originals <- dsGetCompleteMatches
+ let lost_member orig res = sizeUniqDSet (cmConLikes res) < sizeUniqDSet (cmConLikes orig)
+ pure [ res | (orig, res) <- zip originals residuals, lost_member orig res ]
+
+-- | Whether each of the COMPLETE sets has an inhabitant at the variable.
+allInhabited :: Int -> Nabla -> Id -> DsCompleteMatches -> DsM Bool
+allInhabited fuel nabla x cms =
+ isJust <$> runMaybeT (foldM (\nabla cm -> instCompleteSet fuel nabla x cm) nabla cms)
-- | The \(⊢_{Bot}\) rule from the paper
instBot :: Int -> Nabla -> VarInfo -> MaybeT DsM VarInfo
@@ -1986,7 +2123,11 @@ generateInhabitingPatterns mode (x:xs) n nabla = do
Just clss -> do
-- Try each COMPLETE set.
nablass' <- forM clss (instantiate_cons y rep_ty xs n newty_nabla)
- if any null nablass' && vi_bot vi /= IsNotBot
+ -- See Note [Strictness of pattern synonym matches]
+ bot_possible <- if any null nablass' && vi_bot vi /= IsNotBot
+ then matchedPragmaSets vi >>= allInhabited initFuel newty_nabla y
+ else pure False
+ if bot_possible
then generateInhabitingPatterns mode xs n newty_nabla -- bot is still possible. Display a wildcard!
else do
-- Pick the residual COMPLETE set with the smallest cost (see 'completeSetCost').
=====================================
compiler/GHC/HsToCore/Pmc/Solver/Types.hs
=====================================
@@ -586,13 +586,14 @@ pmAltConType (PmAltLit lit) _arg_tys = assert (null _arg_tys ) $ pmLitType l
pmAltConType (PmAltConLike con) arg_tys = conLikeResTy con arg_tys
-- | Is a match on this constructor forcing the match variable?
--- True of data constructors, literals and pattern synonyms (#17357), but not of
--- newtypes.
--- See Note [Coverage checking Newtype matches] in GHC.HsToCore.Pmc.Solver.
-isPmAltConMatchStrict :: PmAltCon -> Bool
-isPmAltConMatchStrict PmAltLit{} = True
-isPmAltConMatchStrict (PmAltConLike PatSynCon{}) = True -- #17357
-isPmAltConMatchStrict (PmAltConLike (RealDataCon dc)) = not (isNewDataCon dc)
+-- @Just True@ for data constructors and literals, @Just False@ for newtypes,
+-- and 'Nothing' for pattern synonyms, whose matchers may or may not force it.
+-- See Note [Coverage checking Newtype matches] and
+-- Note [Strictness of pattern synonym matches] in GHC.HsToCore.Pmc.Solver.
+isPmAltConMatchStrict :: PmAltCon -> Maybe Bool
+isPmAltConMatchStrict PmAltLit{} = Just True
+isPmAltConMatchStrict (PmAltConLike PatSynCon{}) = Nothing
+isPmAltConMatchStrict (PmAltConLike (RealDataCon dc)) = Just (not (isNewDataCon dc))
pmAltConImplBangs :: PmAltCon -> [HsImplBang]
pmAltConImplBangs PmAltLit{} = []
=====================================
testsuite/tests/pmcheck/should_compile/T17357.stderr
=====================================
@@ -1,20 +1,20 @@
-
-T17357.hs:22:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:22:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
Pattern match has inaccessible right hand side
In an equation for ‘f’: f F True = ...
-T17357.hs:23:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:23:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
Pattern match has inaccessible right hand side
In an equation for ‘f’: f !_ True = ...
-T17357.hs:30:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:30:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
Pattern match has inaccessible right hand side
In an equation for ‘f2’: f2 SF True = ...
-T17357.hs:31:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:31:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
Pattern match has inaccessible right hand side
In an equation for ‘f2’: f2 !_ True = ...
-T17357.hs:42:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:42:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
Pattern match is redundant
In an equation for ‘f3’: f3 !_ = ...
+
=====================================
testsuite/tests/pmcheck/should_compile/T28014.hs
=====================================
@@ -0,0 +1,82 @@
+{-# LANGUAGE BangPatterns, GADTs, PatternSynonyms, ViewPatterns #-}
+module T28014 where
+
+import Data.List (uncons)
+import Data.Void
+
+-- | Never matches, and does not force its argument.
+pattern F :: a
+pattern F <- (const False -> True)
+
+-- | The bang is not redundant: withBang undefined is ⊥, but would be 2
+-- without the bang.
+withBang :: Bool -> Int
+withBang F = 1
+withBang !_ = 2
+
+data T = MkT Void
+
+-- | Not exhaustive: h (MkT undefined) fails to match.
+h :: T -> Int
+h (MkT F) = 1
+
+pattern Nil :: [a]
+pattern Nil <- (null -> True)
+pattern Cons :: a -> [a] -> [a]
+pattern Cons x xs <- (uncons -> Just (x, xs))
+{-# COMPLETE Nil, Cons #-}
+
+-- | Exhaustive, and the last clause is redundant.
+g :: [a] -> Int
+g Nil = 0
+g (Cons _ _) = 1
+g _ = 2
+
+-- | The last clause is redundant.
+gBang :: [a] -> Int
+gBang Nil = 0
+gBang (Cons _ _) = 1
+gBang !_ = 2
+
+data G a where
+ G1' :: G Int
+ G2' :: G Bool
+
+pattern G1 :: () => (a ~ Int) => G a
+pattern G1 = G1'
+pattern G2 :: () => (a ~ Bool) => G a
+pattern G2 = G2'
+{-# COMPLETE G1, G2 #-}
+
+-- | Exhaustive: G2 cannot match at G Int.
+fb :: G Int -> Int
+fb G1 = 1
+
+data U = MkU (G Char)
+
+-- | Exhaustive, by the COMPLETE pragma.
+hu :: U -> Int
+hu (MkU G1) = 1
+
+-- | Not exhaustive: no member of the COMPLETE set for G can match at G Char,
+-- and hc (MkU F) fails on MkU undefined.
+hc :: U -> Int
+hc (MkU F) = 1
+
+-- | E Int has no constructor.
+data E a where
+ E1 :: E Bool
+
+-- | No clause is inaccessible: w undefined G1' is 2.
+w :: E a -> G a -> Int
+w F _ = 1
+w _ G1' = 2
+w _ G2' = 3
+
+pattern J :: a -> Maybe a
+pattern J x = Just x
+
+-- | The bang is dead, but the checker can't see that J forces its argument.
+k :: Maybe Int -> Int
+k (J _) = 1
+k !_ = 2
=====================================
testsuite/tests/pmcheck/should_compile/T28014.stderr
=====================================
@@ -0,0 +1,32 @@
+T28014.hs:21:1: warning: [GHC-62161] [-Wincomplete-patterns (in -Wextra)]
+ Pattern match(es) are non-exhaustive
+ In an equation for ‘h’:
+ Patterns of type ‘T’ not matched: MkT p where p is not one of {F}
+
+T28014.hs:33:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match is redundant
+ In an equation for ‘g’: g _ = ...
+
+T28014.hs:39:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match is redundant
+ In an equation for ‘gBang’: gBang !_ = ...
+
+T28014.hs:59:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match has inaccessible right hand side
+ In an equation for ‘hu’: hu (MkU G1) = ...
+
+T28014.hs:59:9: warning: [GHC-40564] [-Winaccessible-code (in -Wdefault)]
+ • Inaccessible code in
+ a pattern with pattern synonym:
+ G1 :: forall a. () => (a ~ Int) => G a,
+ in an equation for ‘hu’
+ Couldn't match type ‘Char’ with ‘Int’
+ • In the pattern: G1
+ In the pattern: MkU G1
+ In an equation for ‘hu’: hu (MkU G1) = 1
+
+T28014.hs:64:1: warning: [GHC-62161] [-Wincomplete-patterns (in -Wextra)]
+ Pattern match(es) are non-exhaustive
+ In an equation for ‘hc’:
+ Patterns of type ‘U’ not matched: MkU p where p is not one of {F}
+
=====================================
testsuite/tests/pmcheck/should_compile/T28014b.hs
=====================================
@@ -0,0 +1,19 @@
+{-# LANGUAGE GADTs, PatternSynonyms, ViewPatterns #-}
+module T28014b where
+
+pattern F :: a
+pattern F <- (const False -> True)
+{-# COMPLETE F #-}
+
+data G a where
+ G1' :: G Int
+ G2' :: G Bool
+
+data E a where
+ E1 :: E Bool
+
+-- | By the COMPLETE pragma, the first clause covers everything.
+w :: E a -> G a -> Int
+w F _ = 1
+w _ G1' = 2
+w _ G2' = 3
=====================================
testsuite/tests/pmcheck/should_compile/T28014b.stderr
=====================================
@@ -0,0 +1,8 @@
+T28014b.hs:18:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match is redundant
+ In an equation for ‘w’: w _ G1' = ...
+
+T28014b.hs:19:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match is redundant
+ In an equation for ‘w’: w _ G2' = ...
+
=====================================
testsuite/tests/pmcheck/should_compile/all.T
=====================================
@@ -56,7 +56,7 @@ test('T17219', expect_broken(17219), compile, [overlapping_incomplete])
test('T17234', normal, compile, [overlapping_incomplete])
test('T17248', normal, compile, [overlapping_incomplete])
test('T17340', normal, compile, ['-Wredundant-bang-patterns'])
-test('T17357', expect_broken(17357), compile, [overlapping_incomplete])
+test('T17357', normal, compile, [overlapping_incomplete])
test('T17376', normal, compile, [overlapping_incomplete])
test('T17378', normal, compile, [overlapping_incomplete])
test('T17465', normal, compile, [overlapping_incomplete])
@@ -195,3 +195,5 @@ test('T27323b', normal, compile, ['-Wredundant-bang-patterns'])
test('T27360', normal, compile, [overlapping_incomplete + '-g3'])
test('T27892a', normal, compile, [overlapping_incomplete])
test('T28095', normal, compile, [overlapping_incomplete])
+test('T28014', normal, compile, [overlapping_incomplete + '-Wredundant-bang-patterns'])
+test('T28014b', normal, compile, [overlapping_incomplete])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/edd13012e8326a0bad6c421f5478279…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/edd13012e8326a0bad6c421f5478279…
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
1
0
[Git][ghc/ghc][wip/T28014] Pmc: Make pattern synonym matches lazy
by Sebastian Graf (@sgraf812) 22 Nov '26
by Sebastian Graf (@sgraf812) 22 Nov '26
22 Nov '26
Sebastian Graf pushed to branch wip/T28014 at Glasgow Haskell Compiler / GHC
Commits:
53f8ee02 by Sebastian Graf at 2026-11-22T18:31:42+01:00
Pmc: Make pattern synonym matches lazy
A match on a pattern synonym no longer implies that the scrutinee is not
bottom. The scrutinee is not bottom only when it failed to match a member of
an applicable COMPLETE pragma and no member of that pragma can match it.
Fixes #28014 and #17357.
- - - - -
10 changed files:
- + changelog.d/28014
- compiler/GHC/HsToCore/Pmc/Check.hs
- compiler/GHC/HsToCore/Pmc/Solver.hs
- compiler/GHC/HsToCore/Pmc/Solver/Types.hs
- testsuite/tests/pmcheck/should_compile/T17357.stderr
- + testsuite/tests/pmcheck/should_compile/T28014.hs
- + testsuite/tests/pmcheck/should_compile/T28014.stderr
- + testsuite/tests/pmcheck/should_compile/T28014b.hs
- + testsuite/tests/pmcheck/should_compile/T28014b.stderr
- testsuite/tests/pmcheck/should_compile/all.T
Changes:
=====================================
changelog.d/28014
=====================================
@@ -0,0 +1,14 @@
+section: compiler
+synopsis: The pattern-match checker no longer assumes that pattern synonym matches force their argument
+description:
+ A match on a pattern synonym excludes ⊥ as a value of the scrutinee only
+ through a ``COMPLETE`` set: when every member that can match at the type of
+ the scrutinee failed to match, and that type has a value other than ⊥.
+ Hence ``-Wredundant-bang-patterns`` and ``-Woverlapping-patterns`` no longer
+ report bangs or clauses as redundant or inaccessible when deleting them
+ would change the semantics, and ``-Wincomplete-patterns`` reports matches
+ that fail on ⊥ fields that a pattern synonym does not force. Redundancy that
+ rests on the strictness of a pattern synonym outside of an exhausted
+ ``COMPLETE`` set is no longer reported.
+issues: #28014 #17357
+mrs: !17033
=====================================
compiler/GHC/HsToCore/Pmc/Check.hs
=====================================
@@ -144,7 +144,7 @@ checkGrd grd = CA $ \inc -> case grd of
, cr_approx = Precise }
-- Con: Fall through on x ≁ K and refine with x ~ K ys and type info
PmCon x con tvs dicts args -> do
- !div <- if isPmAltConMatchStrict con
+ !div <- if pmAltConMatchMayDiverge con
then addPhiCtNablas inc (PhiBotCt x)
else pure mempty
!matched <- addPhiCtNablas inc (PhiConCt x con tvs (map evVarPred dicts) args)
=====================================
compiler/GHC/HsToCore/Pmc/Solver.hs
=====================================
@@ -547,6 +547,116 @@ clause as redundant, which clearly is unsound. The solution:
3. Immediately reject when we find @x ≁ T2@.
Handling of Newtypes is also described in the Appendix of the Lower Your Guards paper,
where you can find the solution in a perhaps more digestible format.
+
+Note [Strictness of pattern synonym matches]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+TODO(sgraf): formulate. Points:
+
+* A match on a data constructor K forces x, so both x ~ K and x ≁ K imply
+ x ≁ ⊥. A match on a pattern synonym P need not force x (#28014, #17357):
+
+ pattern F :: a
+ pattern F <- (const False -> True)
+
+ withBang :: Bool -> Int
+ withBang F = 1
+ withBang !_ = 2 -- Bang not redundant: withBang undefined is ⊥,
+ -- but 2 without the bang
+
+ So neither x ~ P nor x ≁ P implies x ≁ ⊥ ('isPmAltConMatchStrict').
+
+* A match on P may still diverge on ⊥, so the divergent set gets x ~ ⊥
+ ('pmAltConMatchMayDiverge'). Example from #17357:
+
+ strictConst :: a -> b -> a
+ strictConst a b = seq b a
+ pattern SF <- (strictConst False -> True)
+
+ f2 :: Bool -> Bool -> ()
+ f2 _ True = ()
+ f2 SF True = () -- Inaccessible RHS, not redundant
+ f2 !_ True = ()
+ f2 _ _ = ()
+
+* Rule. Let C be a COMPLETE set from a pragma that applies at the type τ
+ of x. If x failed to match a member of C, and no member of C can match x,
+ then x ≁ ⊥. A member P cannot match x when x failed to match P, or when the
+ provided constraints of P contradict τ. The pragma asserts that matching
+ any value of τ, ⊥ included, against the members of C succeeds or diverges.
+ x ≁ ⊥ is a fact, so redundancy and coverage both use it.
+
+* Type constraints alone leave ⊥. Here no member of C = {G1, G2} (below)
+ can match at G Char, and x failed to match only F:
+
+ data U = MkU (G Char)
+ hc :: U -> Int
+ hc (MkU F) = 1 -- Not matched: MkU _
+
+* Matcher lemma, for the pragma assertion at a τ with a non-⊥ value.
+ $mP :: forall r. τ -> (args -> r) -> (Void# -> r) -> r.
+ By parametricity, $mP v k e ∈ {⊥, k args, e (##)}. By monotonicity in v,
+ if P fails on ⊥ without diverging, P fails on every value.
+ A non-⊥ value v of τ matches some member P of C. If P failed on ⊥
+ without diverging, P fails on v. Contradiction.
+
+* The vanilla COMPLETE set of a data type needs no rule. A failed match on a
+ data constructor gives x ≁ ⊥ already. If no data constructor failed but
+ the set has no inhabitant, τ has no data constructor, and ⊥ stays:
+
+ data T = MkT Void
+ h :: T -> Int
+ h (MkT F) = 1 -- Not matched: MkT _. Indeed h (MkT undefined) fails.
+
+* Implementation in the inhabitation test ('instantiate'). A residual
+ COMPLETE set from a pragma that lost a member witnesses a failed match on
+ that member ('matchedPragmaSets'). This covers synonyms with a required
+ theta, which are not in 'vi_neg'
+ (Note [Completeness checking with required Thetas]).
+ - Without such a set, offer ⊥ first, as before.
+ - Otherwise, search the residual COMPLETE sets for a non-⊥ inhabitant
+ ('instCompleteSets'). If there is none, offer ⊥ when each of these sets
+ has an inhabitant ('allInhabited').
+ The order is only a matter of performance
+ (Note [Shortcutting the inhabitation test]).
+ 'generateInhabitingPatterns' decides on a wildcard the same way.
+ Wrinkle: 'instCompleteSet' also removes a member that cannot match at the
+ type of x at the time of the test. A later type refinement that rules out
+ the remaining members then rules out ⊥ as well.
+
+* Example: every member failed.
+
+ pattern Nil :: [a]
+ pattern Nil <- (null -> True)
+ pattern Cons :: a -> [a] -> [a]
+ pattern Cons x xs <- (uncons -> Just (x, xs))
+ {-# COMPLETE Nil, Cons #-}
+
+ g :: [a] -> Int
+ g Nil = 0
+ g (Cons _ _) = 1 -- Exhaustive
+ g _ = 2 -- Redundant
+
+* Example: members that cannot match at τ.
+
+ data G a where { G1' :: G Int; G2' :: G Bool }
+ pattern G1 :: () => (a ~ Int) => G a
+ pattern G1 = G1'
+ pattern G2 :: () => (a ~ Bool) => G a
+ pattern G2 = G2'
+ {-# COMPLETE G1, G2 #-}
+
+ fb :: G Int -> Int
+ fb G1 = 1 -- Exhaustive: G2 cannot match at G Int
+
+* Precision loss: redundancy that rests on the strictness of P outside an
+ exhausted COMPLETE set is not reported.
+
+ pattern J :: a -> Maybe a
+ pattern J x = Just x
+
+ k :: Maybe Int -> Int
+ k (J _) = 1
+ k !_ = 2 -- Bang is dead, but not reported
-}
-------------------------
@@ -729,7 +839,7 @@ addNotConCt nabla x nalt = do
-- otherwise return updated entry and `Just x'` if `x` should be marked dirty,
-- where `x'` is the representative of `x`.
go :: VarInfo -> MaybeT DsM (Maybe Id, VarInfo)
- go vi@(VI x' pos neg _ rcm) = do
+ go vi@(VI x' pos neg bot rcm) = do
-- 1. Bail out quickly when nalt contradicts a solution
let contradicts nalt sol = eqPmAltCon (paca_con sol) nalt == Equal
guard (not (any (contradicts nalt) pos))
@@ -741,8 +851,10 @@ addNotConCt nabla x nalt = do
-- See Note [Completeness checking with required Thetas]
| hasRequiredTheta nalt = neg
| otherwise = extendPmAltConSet neg nalt
- massert (isPmAltConMatchStrict nalt)
- let vi' = vi{ vi_neg = neg', vi_bot = IsNotBot }
+ -- See Note [Strictness of pattern synonym matches]
+ let bot' | isPmAltConMatchStrict nalt = IsNotBot
+ | otherwise = bot
+ let vi' = vi{ vi_neg = neg', vi_bot = bot' }
-- 3. Make sure there's at least one other possible constructor
mb_rcm' <- lift (markMatched nalt rcm)
pure $ case mb_rcm' of
@@ -796,8 +908,9 @@ addConCt nabla@MkNabla{ nabla_tm_st = ts@TmSt{ ts_facts=env } } x alt tvs args =
MaybeBot -> pure (nabla_with MaybeBot)
IsBot -> addBotCt (nabla_with MaybeBot) y
IsNotBot -> addNotBotCt (nabla_with MaybeBot) y
- _ -> assert (isPmAltConMatchStrict alt )
- pure (nabla_with IsNotBot) -- strict match ==> not ⊥
+ _ | isPmAltConMatchStrict alt -> pure (nabla_with IsNotBot) -- strict match ==> not ⊥
+ -- See Note [Strictness of pattern synonym matches]
+ | otherwise -> pure (nabla_with bot)
equateTys :: [Type] -> [Type] -> [PhiCt]
equateTys ts us =
@@ -1372,8 +1485,31 @@ varNeedsTesting old_ty_st MkNabla{nabla_ty_st=new_ty_st} vi = do
-- remain that do not satisfy it. This lazy approach just
-- avoids doing unnecessary work.
instantiate :: Int -> Nabla -> VarInfo -> MaybeT DsM VarInfo
-instantiate fuel nabla vi = {-# SCC "instantiate" #-}
- (instBot fuel nabla vi <|> instCompleteSets fuel nabla vi)
+instantiate fuel nabla vi = {-# SCC "instantiate" #-} do
+ -- See Note [Strictness of pattern synonym matches]
+ matched <- lift (matchedPragmaSets vi)
+ if null matched
+ then instBot fuel nabla vi <|> instCompleteSets fuel nabla vi
+ else instCompleteSets fuel nabla vi <|> do
+ guard =<< lift (allInhabited fuel nabla (vi_id vi) matched)
+ instBot fuel nabla vi
+
+-- | The residual COMPLETE sets from pragmas that lost a member, for a variable
+-- that might be ⊥. When one of them has no inhabitant, the variable is not ⊥.
+-- See Note [Strictness of pattern synonym matches].
+matchedPragmaSets :: VarInfo -> DsM DsCompleteMatches
+matchedPragmaSets VI{ vi_bot = IsNotBot } = pure []
+matchedPragmaSets VI{ vi_rcm = rcm } = case rcm_pragmas rcm of
+ Nothing -> pure []
+ Just residuals -> do
+ originals <- dsGetCompleteMatches
+ let lost_member orig res = sizeUniqDSet (cmConLikes res) < sizeUniqDSet (cmConLikes orig)
+ pure [ res | (orig, res) <- zip originals residuals, lost_member orig res ]
+
+-- | Whether each of the COMPLETE sets has an inhabitant at the variable.
+allInhabited :: Int -> Nabla -> Id -> DsCompleteMatches -> DsM Bool
+allInhabited fuel nabla x cms =
+ isJust <$> runMaybeT (foldM (\nabla cm -> instCompleteSet fuel nabla x cm) nabla cms)
-- | The \(⊢_{Bot}\) rule from the paper
instBot :: Int -> Nabla -> VarInfo -> MaybeT DsM VarInfo
@@ -1986,7 +2122,11 @@ generateInhabitingPatterns mode (x:xs) n nabla = do
Just clss -> do
-- Try each COMPLETE set.
nablass' <- forM clss (instantiate_cons y rep_ty xs n newty_nabla)
- if any null nablass' && vi_bot vi /= IsNotBot
+ -- See Note [Strictness of pattern synonym matches]
+ bot_possible <- if any null nablass' && vi_bot vi /= IsNotBot
+ then matchedPragmaSets vi >>= allInhabited initFuel newty_nabla y
+ else pure False
+ if bot_possible
then generateInhabitingPatterns mode xs n newty_nabla -- bot is still possible. Display a wildcard!
else do
-- Pick the residual COMPLETE set with the smallest cost (see 'completeSetCost').
=====================================
compiler/GHC/HsToCore/Pmc/Solver/Types.hs
=====================================
@@ -22,7 +22,7 @@ module GHC.HsToCore.Pmc.Solver.Types (
-- ** Representations for Literals and AltCons
PmLit(..), PmLitValue(..), PmAltCon(..), pmLitType, pmAltConType,
- isPmAltConMatchStrict, pmAltConImplBangs,
+ isPmAltConMatchStrict, pmAltConMatchMayDiverge, pmAltConImplBangs,
-- *** PmAltConSet
PmAltConSet, emptyPmAltConSet, isEmptyPmAltConSet, elemPmAltConSet,
@@ -586,14 +586,23 @@ pmAltConType (PmAltLit lit) _arg_tys = assert (null _arg_tys ) $ pmLitType l
pmAltConType (PmAltConLike con) arg_tys = conLikeResTy con arg_tys
-- | Is a match on this constructor forcing the match variable?
--- True of data constructors, literals and pattern synonyms (#17357), but not of
--- newtypes.
--- See Note [Coverage checking Newtype matches] in GHC.HsToCore.Pmc.Solver.
+-- True of data constructors and literals, but not of newtypes and pattern
+-- synonyms.
+-- See Note [Coverage checking Newtype matches] and
+-- Note [Strictness of pattern synonym matches] in GHC.HsToCore.Pmc.Solver.
isPmAltConMatchStrict :: PmAltCon -> Bool
isPmAltConMatchStrict PmAltLit{} = True
-isPmAltConMatchStrict (PmAltConLike PatSynCon{}) = True -- #17357
+isPmAltConMatchStrict (PmAltConLike PatSynCon{}) = False
isPmAltConMatchStrict (PmAltConLike (RealDataCon dc)) = not (isNewDataCon dc)
+-- | Can a match on this constructor diverge when the match variable is ⊥?
+-- True of everything but newtypes.
+-- See Note [Coverage checking Newtype matches] and
+-- Note [Strictness of pattern synonym matches] in GHC.HsToCore.Pmc.Solver.
+pmAltConMatchMayDiverge :: PmAltCon -> Bool
+pmAltConMatchMayDiverge (PmAltConLike (RealDataCon dc)) = not (isNewDataCon dc)
+pmAltConMatchMayDiverge _ = True
+
pmAltConImplBangs :: PmAltCon -> [HsImplBang]
pmAltConImplBangs PmAltLit{} = []
pmAltConImplBangs (PmAltConLike con) = conLikeImplBangs con
=====================================
testsuite/tests/pmcheck/should_compile/T17357.stderr
=====================================
@@ -1,20 +1,20 @@
-
-T17357.hs:22:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:22:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
Pattern match has inaccessible right hand side
In an equation for ‘f’: f F True = ...
-T17357.hs:23:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:23:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
Pattern match has inaccessible right hand side
In an equation for ‘f’: f !_ True = ...
-T17357.hs:30:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:30:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
Pattern match has inaccessible right hand side
In an equation for ‘f2’: f2 SF True = ...
-T17357.hs:31:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:31:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
Pattern match has inaccessible right hand side
In an equation for ‘f2’: f2 !_ True = ...
-T17357.hs:42:1: warning: [-Woverlapping-patterns (in -Wdefault)]
+T17357.hs:42:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
Pattern match is redundant
In an equation for ‘f3’: f3 !_ = ...
+
=====================================
testsuite/tests/pmcheck/should_compile/T28014.hs
=====================================
@@ -0,0 +1,82 @@
+{-# LANGUAGE BangPatterns, GADTs, PatternSynonyms, ViewPatterns #-}
+module T28014 where
+
+import Data.List (uncons)
+import Data.Void
+
+-- | Never matches, and does not force its argument.
+pattern F :: a
+pattern F <- (const False -> True)
+
+-- | The bang is not redundant: withBang undefined is ⊥, but would be 2
+-- without the bang.
+withBang :: Bool -> Int
+withBang F = 1
+withBang !_ = 2
+
+data T = MkT Void
+
+-- | Not exhaustive: h (MkT undefined) fails to match.
+h :: T -> Int
+h (MkT F) = 1
+
+pattern Nil :: [a]
+pattern Nil <- (null -> True)
+pattern Cons :: a -> [a] -> [a]
+pattern Cons x xs <- (uncons -> Just (x, xs))
+{-# COMPLETE Nil, Cons #-}
+
+-- | Exhaustive, and the last clause is redundant.
+g :: [a] -> Int
+g Nil = 0
+g (Cons _ _) = 1
+g _ = 2
+
+-- | The last clause is redundant.
+gBang :: [a] -> Int
+gBang Nil = 0
+gBang (Cons _ _) = 1
+gBang !_ = 2
+
+data G a where
+ G1' :: G Int
+ G2' :: G Bool
+
+pattern G1 :: () => (a ~ Int) => G a
+pattern G1 = G1'
+pattern G2 :: () => (a ~ Bool) => G a
+pattern G2 = G2'
+{-# COMPLETE G1, G2 #-}
+
+-- | Exhaustive: G2 cannot match at G Int.
+fb :: G Int -> Int
+fb G1 = 1
+
+data U = MkU (G Char)
+
+-- | Exhaustive, by the COMPLETE pragma.
+hu :: U -> Int
+hu (MkU G1) = 1
+
+-- | Not exhaustive: no member of the COMPLETE set for G can match at G Char,
+-- and hc (MkU F) fails on MkU undefined.
+hc :: U -> Int
+hc (MkU F) = 1
+
+-- | E Int has no constructor.
+data E a where
+ E1 :: E Bool
+
+-- | No clause is inaccessible: w undefined G1' is 2.
+w :: E a -> G a -> Int
+w F _ = 1
+w _ G1' = 2
+w _ G2' = 3
+
+pattern J :: a -> Maybe a
+pattern J x = Just x
+
+-- | The bang is dead, but the checker can't see that J forces its argument.
+k :: Maybe Int -> Int
+k (J _) = 1
+k !_ = 2
=====================================
testsuite/tests/pmcheck/should_compile/T28014.stderr
=====================================
@@ -0,0 +1,32 @@
+T28014.hs:21:1: warning: [GHC-62161] [-Wincomplete-patterns (in -Wextra)]
+ Pattern match(es) are non-exhaustive
+ In an equation for ‘h’:
+ Patterns of type ‘T’ not matched: MkT p where p is not one of {F}
+
+T28014.hs:33:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match is redundant
+ In an equation for ‘g’: g _ = ...
+
+T28014.hs:39:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match is redundant
+ In an equation for ‘gBang’: gBang !_ = ...
+
+T28014.hs:59:1: warning: [GHC-94210] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match has inaccessible right hand side
+ In an equation for ‘hu’: hu (MkU G1) = ...
+
+T28014.hs:59:9: warning: [GHC-40564] [-Winaccessible-code (in -Wdefault)]
+ • Inaccessible code in
+ a pattern with pattern synonym:
+ G1 :: forall a. () => (a ~ Int) => G a,
+ in an equation for ‘hu’
+ Couldn't match type ‘Char’ with ‘Int’
+ • In the pattern: G1
+ In the pattern: MkU G1
+ In an equation for ‘hu’: hu (MkU G1) = 1
+
+T28014.hs:64:1: warning: [GHC-62161] [-Wincomplete-patterns (in -Wextra)]
+ Pattern match(es) are non-exhaustive
+ In an equation for ‘hc’:
+ Patterns of type ‘U’ not matched: MkU p where p is not one of {F}
+
=====================================
testsuite/tests/pmcheck/should_compile/T28014b.hs
=====================================
@@ -0,0 +1,19 @@
+{-# LANGUAGE GADTs, PatternSynonyms, ViewPatterns #-}
+module T28014b where
+
+pattern F :: a
+pattern F <- (const False -> True)
+{-# COMPLETE F #-}
+
+data G a where
+ G1' :: G Int
+ G2' :: G Bool
+
+data E a where
+ E1 :: E Bool
+
+-- | By the COMPLETE pragma, the first clause covers everything.
+w :: E a -> G a -> Int
+w F _ = 1
+w _ G1' = 2
+w _ G2' = 3
=====================================
testsuite/tests/pmcheck/should_compile/T28014b.stderr
=====================================
@@ -0,0 +1,8 @@
+T28014b.hs:18:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match is redundant
+ In an equation for ‘w’: w _ G1' = ...
+
+T28014b.hs:19:1: warning: [GHC-53633] [-Woverlapping-patterns (in -Wdefault)]
+ Pattern match is redundant
+ In an equation for ‘w’: w _ G2' = ...
+
=====================================
testsuite/tests/pmcheck/should_compile/all.T
=====================================
@@ -56,7 +56,7 @@ test('T17219', expect_broken(17219), compile, [overlapping_incomplete])
test('T17234', normal, compile, [overlapping_incomplete])
test('T17248', normal, compile, [overlapping_incomplete])
test('T17340', normal, compile, ['-Wredundant-bang-patterns'])
-test('T17357', expect_broken(17357), compile, [overlapping_incomplete])
+test('T17357', normal, compile, [overlapping_incomplete])
test('T17376', normal, compile, [overlapping_incomplete])
test('T17378', normal, compile, [overlapping_incomplete])
test('T17465', normal, compile, [overlapping_incomplete])
@@ -195,3 +195,5 @@ test('T27323b', normal, compile, ['-Wredundant-bang-patterns'])
test('T27360', normal, compile, [overlapping_incomplete + '-g3'])
test('T27892a', normal, compile, [overlapping_incomplete])
test('T28095', normal, compile, [overlapping_incomplete])
+test('T28014', normal, compile, [overlapping_incomplete + '-Wredundant-bang-patterns'])
+test('T28014b', normal, compile, [overlapping_incomplete])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/53f8ee02e55a316faf95d711e0e60b1…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/53f8ee02e55a316faf95d711e0e60b1…
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
1
0
Sebastian Graf pushed new branch wip/T28014 at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/T28014
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
1
0
[Git][ghc/ghc] Pushed new branch wip/sjakobi/T28172-anchor-release-branch-regex
by Simon Jakobi (@sjakobi) 22 Nov '26
by Simon Jakobi (@sjakobi) 22 Nov '26
22 Nov '26
Simon Jakobi pushed new branch wip/sjakobi/T28172-anchor-release-branch-regex at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/sjakobi/T28172-anchor-release…
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
1
0
[Git][ghc/ghc][wip/az/exactprint-annotation-rationalisation] 90 commits: document what ->>> stands for in heap profile
by Alan Zimmerman (@alanz) 22 Nov '26
by Alan Zimmerman (@alanz) 22 Nov '26
22 Nov '26
Alan Zimmerman pushed to branch wip/az/exactprint-annotation-rationalisation at Glasgow Haskell Compiler / GHC
Commits:
212c292f by Rajkumar Natarajan at 2026-11-11T13:54:08-05:00
document what ->>> stands for in heap profile
updates the profiling section of the user's guide to explain how types
are approximated when using -hy. Also adds haddocks to getTyDescription
with the same information.
Fixes #26754
- - - - -
c64fc319 by Jonathan at 2026-11-11T13:54:55-05:00
Fix AArch64 veneer target for relocations with an addend
Fixes #27807
The RTS linker would construct invalid relocation veneers on AArch64 if
the addend was non-zero, which typically caused SIGILL crashes. This
could be triggered by evaluating Template Haskell in a package with a
large number of dependencies using a static build of GHC.
- - - - -
cd4dce19 by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
testsuite: add a test for registerFd_ trusting the callback table (#27821)
registerFd001 shows a 'threadWaitRead' that never finishes after an fd is
closed with 'closeFd' rather than 'closeFdWith'. Darwin is the only platform
this reaches -- one-shot registrations are implemented but not used there
(#7651) -- so the test is expect_broken on Darwin only.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5ab442ee by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
registerFd_: always tell the polling backend (#27821)
Where the backend has no one-shot registrations, 'registerFd_' now tells it
about every registration, rather than only when the events differ from the
ones the callback table records: the table alone cannot say whether the
backend still knows the fd. The 'modify' it returns is unchanged. See Note
[Do not trust the callback table].
This fixes registerFd001 and clears its expect_broken.
Changelog wording from Duncan Coutts in review.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
ab8b5b06 by Vladislav Zavialov at 2026-11-11T13:56:27-05:00
Curried contexts in prefix GADT constructors (#27424)
Prefix GADT constructor declarations now accept multiple consecutive
contexts, equivalent to a single conjoined context:
data G a where
MkCurried :: C a => (D a, E a) => G a
MkConjoined :: (C a, D a, E a) => G a
This is a step towards GHC Proposal #402 "Stable GADT constructor syntax".
To represent multiple contexts, the `con_mb_cxt` field of `ConDeclGADT` has
been replaced by `con_cxts`, which stores a list instead of a Maybe:
- con_mb_cxt :: Maybe (LHsContext pass)
+ con_cxts :: [LHsContext pass]
The rest of this patch follows from this change.
Note that in ConDeclH98, the optional context is still stored as a Maybe.
To accommodate this difference, a few helper functions were generalised over
a Foldable container `t`:
hsConDeclTheta :: Foldable t => t (LHsContext ...) -> [LHsType ...]
pprLHsContext :: (Foldable t, ...) => t (LHsContext ...) -> SDoc
repContexts :: Foldable t => t (LHsContext GhcRn) -> MetaM (Core (M TH.Cxt))
tcHsContext :: Foldable t => t (LHsContext GhcRn) -> TcM [PredType]
In practice, the instantiations of `t` are either `Maybe` or `[]`.
Record-style GADT constructors continue to accept at most one context.
`splitLHsGadtTy` accounts for this by splitting off only the first context
if it detects record syntax, leaving the offending part of the type in the
body for the renamer to reject later on.
Test cases: T12087a T27424a T27424b T27424c T27424d GadtConSigs_th_dump1
- - - - -
d2f135ff by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: cache register usage in liveness annotations
regUsageOfInstr allocates fresh register lists on every call, and on the
linear allocator path it was called three times per instruction: in the
backward liveness pass, in the forward liveness pass and in the allocator
itself. Store the usage computed by the backward pass in the Liveness
annotation and reuse it in the other passes (and in the graph allocator's
spill passes). patchRegsLiveInstr recomputes it for the patched
instruction.
See Note [Cached register usage in liveness annotations].
Part of #28008.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
ff0a5d32 by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: describe register usage with a small DSL
This new register usage DSL (see Note [Register usage DSL] in
GHC.CmmToAsm.RegUsage) reduces allocation compared to the previous
list-based approach.
Fixes #28008.
Metric Decrease:
ManyAlternatives
T12707
T13035
T13379
T13960
T18698b
T19695
T21839c
T3064
T3294
T4801
T5321FD
T5321Fun
T783
T9198
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
51f38f3a by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock-library: fix the build of the spec and fixtures test suites
The documentation pipeline moved from String to Text (commit 202ed264141)
but the two test suites of haddock-library were left behind and no
longer compiled. They are not run by GHC's CI (see #16206), so this went
unnoticed.
The fixtures suite still has four pre-existing failures (list-blocks1,
table1, table4, table5) that are not addressed here.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
394d9d6d by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: parse backtick spans as monospaced text
A backtick span whose content is not a valid Haskell identifier, such as
`foo bar`, was rendered as plain text with literal backticks. It is now
parsed as monospaced text, like @foo bar@. A closed backtick span whose
whole content is one identifier keeps its meaning as a hyperlinked
identifier. A span such as `foldl' f z xs` is code: it is no longer read
as the identifier foldl between a backtick and a single quote. The
TeX-style form `foo' stays an identifier when no backtick closes the
span on the same line.
Code spans follow the CommonMark rules: a span opened by a run of N
backticks ends at the next run of exactly N backticks on the same line,
so ``x `plus` y`` is code "x `plus` y". One space is removed at each end
when both are present, and an unclosed opening run is plain text. The
content is literal: no markup is parsed and backslashes are kept, so
`\x -> x` renders as written.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Fixes #28090
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
7ae41c37 by Sylvain Henry at 2026-11-11T13:58:14-05:00
Use 'T' instead of `T' in Haddock comments next to backtick spans
With backtick code spans, a TeX-style quote `T' followed by a backtick on
the same line opens a code span up to that backtick. Use the 'T' form in
the Haddock comments where this happens.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
ce96f0b6 by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: do not parse backtick spans inside @...@
Text between @...@ is already code, so backtick code spans are no longer
parsed there. Thus in
@x <- f -- of type `M Bool`@
the backticks stay as text. Inline markup inside @...@, such as /.../,
passes this context down.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
744b3036 by Sylvain Henry at 2026-11-11T13:58:15-05:00
haddock: keep the backticks of infix identifiers inside @...@
A backticked identifier inside @...@ was always rendered without its
backticks, so @f `elem` xs@ rendered as "f elem xs". Now an identifier
in an infix application or an operator section, such as @f `elem` xs@
or @(`elem` xs)@, is parsed in infix form, as if written ``elem``, and
renders with its backticks and with elem linked. Elsewhere, as in
@`foldlM` :: ...@, the backticks still only mark the link.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
0d8e1f8d by Sylvain Henry at 2026-11-11T13:59:05-05:00
PPC NCG: print non-standard NaN literals in target byte order
The PowerPC NCG printed a non-standard NaN literal byte by byte with
floatToBytes/doubleToBytes, which use the byte order of the host. This
is wrong when the host and the target have a different endianness (e.g.
from x86_64 to big-endian PowerPC). Print the bits with `.long`/`.quad`
instead, so that the assembler uses the target byte order.
Also make `ppr_item` print its argument: some clauses printed the
literal of `pprDataItem` instead.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
5a9db1ed by Sylvain Henry at 2026-11-11T13:59:05-05:00
Print all NaN literals as integer bits (#28101)
The x86 and PowerPC NCGs printed the quiet NaNs 0x7fc00000 and
0x7ff8000000000000 as `.float NaN`/`.double NaN`. GNU as and clang
encode these with all mantissa bits set, so constant-folded bit casts
of these values gave 0x7fffffff/0x7fffffffffffffff. The C backend
printed every NaN as `NAN`, losing its sign and payload.
Now the NCGs print all NaNs with `.long`/`.quad` and the C backend with
hs_bitcastword2float/hs_bitcastword642double.
See Note [Printing NaN literals].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b4ceb6a9 by mangoiv at 2026-11-11T13:59:47-05:00
ci: fix ghcup nightly script misbehaviour
- download all jobs instead of just the first 100
- stop using a canary job to detect whether it's a nightly or release
pipeline
- - - - -
aefa0c1b by Alan Zimmerman at 2026-11-11T14:00:28-05:00
EPA: Use AnnList in HsMultiIf
It introduces layout, capture it
- - - - -
d72505e4 by Simon Jakobi at 2026-11-12T15:26:14-05:00
testsuite: Fix T17088 flakiness and restore bug coverage
T17088 reads and prints a byte from an uninitialized array. Debug RTS
ways fill allocated memory with 0xaa, so the test can fail due to an
output mismatch unrelated to the pointer-tagging bug it covers.
Initialize the byte to zero to make the output deterministic.
The original bug requires the compacting collector and particular
compiler and RTS settings. Run the test only in the compacting_gc way
with -O1 and -A128k. Also disable STG lambda lifting because it removes
the closure shape needed to reproduce the pointer-tagging failure.
This makes the test reliable while ensuring it remains an effective
reproducer for #17088.
Closes #27534.
Assisted-by: gpt-5.6-sol via Codex CLI
- - - - -
5a7591b3 by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: Fix python type errors
These errors appear when using the VSCode python extension which uses
Pylance under the hood.
- - - - -
52f129f8 by David Eichmann at 2026-11-12T15:26:56-05:00
Add test modifier to test over all IO Managers
- - - - -
22e8b92a by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: include custom IO Manager in test name
- - - - -
82c34ccd by Simon Jakobi at 2026-11-12T15:27:40-05:00
Make T2464 actually test #ifdef'd pragmas
The test guarded a LANGUAGE EmptyDataDecls pragma behind #if, but
EmptyDataDecls is on by default since Haskell2010, so the module
compiled even when the guarded pragma was ignored. Guard MagicHash
instead, which is unlikely to be included in a future default language.
The test also checks that warnings from file-header pragmas are emitted
only once, even though the pragmas are parsed both before and after
CPP, using the -fffi deprecation warning as the canary. Use an
unrecognised warning flag instead, so the test no longer depends on a
deprecated flag that is about to be removed.
Context: #27939
Assisted-by: Claude Fable 5.1
- - - - -
419f2a12 by Simon Jakobi at 2026-11-12T15:27:40-05:00
Remove command-line flags deprecated in GHC 8.2 or earlier
Also remove the INCLUDE file-header pragma, which only expanded to
the now-removed -#include.
Closes #27939.
Assisted-by: Claude Fable 5.1
- - - - -
adc294d0 by Erik de Castro Lopo at 2026-11-12T15:28:21-05:00
TimerManager: publish only evaluated timeout queues (#9809)
The issue in #9809 was triggered by many threads registering timeouts
at the same time and those timeouts being stored as unevaluated thunks
in the shared list. When say 100,000 timeouts are registered at the
same time, the program can be slowed down considerably and the memory
usage grow unacceptably large.
The commit that caused the problem was 2d5eccdf1c, a 2013 change that
fixed #7653.
The fix is to add a modifyTimeouts function which applies an edit to a
copy of the list and fully evaluates the result before replacing the
shared list with a CAS operation.
Performance has improved for the threaded case and not regressed for
the single thread case:
Forked registrations of 100k timeouts (median of 5 runs):
-N4: 0.577 s, 428 MB -> 0.078 s, 39 MB
-N12: 1.227 s, 479 MB -> 0.127 s, 80 MB
Forked registrations of 1M timeouts on -N1 (median of 3 and 10 runs):
5.21 s (range 0.67-9.47 s), 1613 MB -> 0.67 s, 250 MB
Single-thread registrations are unchanged or slightly faster, and timer
latency during registration storms improves (p99 lateness of a 1 ms
threadDelay during 100k forked registrations on -N4: 302-394 ms ->
3.5-4.1 ms).
The registration code still runs in constant stack, so #7653 stays fixed;
T7653 and the concurrent, base and ghc-internal testsuites pass.
modifyTimeouts is OPAQUE so that the optimiser cannot expose the edit
function's inspection of the old queue next to the compare-and-swap and
replace the expected pointer with the evaluated queue, which would make the
compare-and-swap keep failing when the MutVar# holds a thunk or indirection.
Regression test T9809.hs included.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b294b82f by Moritz Angermann at 2026-11-12T15:28:21-05:00
testsuite: give pause_resume_via_safe_ffi_concurrent 60s on Darwin CI
The 10s System.Timeout watchdog was a false deadlock: five serialized
1s pauses plus rts_pause waiting on threadDelay/timer-manager traffic
overruns that budget on loaded Mac runners. Keep a watchdog so a real
hang still fails.
- - - - -
1543f834 by Simon Jakobi at 2026-11-12T15:29:03-05:00
testsuite/README: Don't append new tests at the end of all.T
Patches that each add a test at the end of the same all.T conflict
with each other. Tests added elsewhere in the file usually merge cleanly.
Context: #26285
Assisted-by: Claude Opus 5.5
- - - - -
9ad25cb2 by Sven Tennie at 2026-11-14T06:20:13-05:00
hadrian: Add Stage3 cross-compiled target bindist (#26924)
Add a `binary-dist-stage3` Hadrian target that packages target
executables (produced by the stage2 compiler) into a separate
'_build/bindist-stage3/' folder, distinct from the stage2 regular or
cross-compiler bindist in '_build/bindist/'.
This allows a single CI pipeline job to produce both a cross-compiler
bindist (e.g. x86_64 -> RISC-V) and a target-architecture bindist (e.g.
RISC-V -> RISC-V) that can be installed and run natively on the target.
To avoid issues with stale files or race-conditions on them, generate
the `configure` script per stage in `_build/<stage>/distrib`
directories.
- - - - -
ca91017d by Sven Tennie at 2026-11-14T06:20:13-05:00
ci: Build Stage3 and Stage2 bindists for cross targets in one job (#26924)
Building the stage3 target bindist already produces most of the stage2
cross-compiler bindist as a byproduct, so building them in separate jobs
duplicates the build efforts for no benefit. Instead of a separate
CROSS_STAGE=3 job, the stage3 job now also builds and publishes the
stage2 bindist.
The stage3 tarball is named and versioned as if it were built natively
on the target (target triple prefix, non-cross opsys), so its artifact
name stays what downstream consumers already expect and no changes are
needed on their side.
For now, this is only enabled for the RISC-V job. Others can easily
follow.
- - - - -
71b41e09 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: model cross targets as structured TargetPlatform triples (#26924)
Storing the cross target as a raw triple forced ad-hoc parsing at every
use, and broke the single responsibility rule. Modelling it as a
structured `TargetPlatform`` instead, avoids parsing and provides a
clear separation of concerns.
- - - - -
8067c2f9 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: extract the cross smoke tests into a separate smoke_test command (#26924)
This reduces if-nesting and complexity of the main `test_hadrian`
command. The decision how to test is now made by the caller. This is a
fair choice, because most test cases can run under emulation - they are
just very slow then.
The Stage3 smoke test also checks that the target compiler does not report
itself as cross-compiling and, when supported, runs a small GHCi expression.
- - - - -
7ece99a7 by fendor at 2026-11-14T06:20:57-05:00
Add `-dep-json` flag to `ghc -M`
Add an optional flag to `ghc -M` that allows to write the dependency
information in JSON Lines format.
The JSON Lines format enables us to stream the output of the dependency
generation to a consumer.
The output of `-dep-json` is streamed to a temporary file and then
copied to the final destination to avoid partial writes.
Each line contains one of two possible json objects:
1. A Home Unit Dependency
* Contains the name of the home module, its unit, where it is
located, whether a preprocessor is used, and all of its imports.
Importantly, the imports include `-XExplicitLevelImports`
information.
* If requested via `-include-pkg-deps`, includes imports of external
units, e.g. modules from `base`.
* If requested via `-include-cpp-deps`, files included via CPP.
2. External Unit Dependency
* Only if `-include-pkg-deps` is given
* Contains unit-id, its package name and package id.
---
This PR refactors the Makefile generation to use phases appropriately.
We introduce an intermediate data structure that is generated based on
the module graph nodes, and only then generate the Makefile rules.
This allows the dep-json and dep-makefile generation to use the same
dependency processing.
- - - - -
0f6e0146 by fendor at 2026-11-14T06:20:57-05:00
Add multiple home unit support to `ghc -M`
Allows to process the module graph of multiple home units at once using
the same syntax as `--make` and `--interactive`:
ghc -M -unit @unitA -unit @unitB
The semantics are identical to `--make` and `--interactive`.
Each home unit can declare individually to use `-include-cpp-deps` and
`-include-pkg-deps`.
However, there can only be one output file, and `-dep-json` and
`-dep-makefile` can only be provided at the top of the cli invocation.
We introduce a new GHC API `doMkDepend` that allows to use multiple home
units conveniently.
The output of `-dep-json` and `-dep-makefile` does not change, since we
were careful to choose a format that supports multiple home units from
the start.
Single home units are still accepted like before with no changes.
- - - - -
5598e6a0 by fendor at 2026-11-14T06:20:57-05:00
Deprecate `doMkDependHS` in favour of `doMkDepend`
- - - - -
39f2943e by David Eichmann at 2026-11-14T06:21:41-05:00
rts: Expose getRtsSymbols() and store redirect labels and external symbols tag
- - - - -
aa159605 by David Eichmann at 2026-11-14T06:21:41-05:00
hadrian: when running tests, properly set have_gdb and have_readelf
- - - - -
ff826da4 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: add have_ldd() test modifier
- - - - -
b9f0b7e2 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite driver: on windows, ensure PATH correctly contains mingw and ghc-pkg libraries
- - - - -
543c108e by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: driver now sets WAY_FLAGS variable for makefile tests
- - - - -
13408a2b by David Eichmann at 2026-11-14T06:21:41-05:00
Add golden test for rts/RtsSymbols.c
This test compares declared symbols against symbols observed
in the rts DSO (.so file).
- - - - -
38d421fb by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: look up a non-recursive let with the key order of the store
xtE stored a `Let (NonRec b r) e` with the body e as the first key and
the right-hand side r as the second key. lkE used the opposite order.
When a trie level holds one entry, GenMap compares the full keys with
(==), and the difference has no effect. When a trie level holds two
entries, a lookup of an expression with a non-recursive let fails. A
later insert of an equal expression then overwrites the first entry.
Now xtE stores the key in the order that lkE uses.
Effects of the bug: CSE did not share identical bindings when a module
had two different bindings that hold a non-recursive let or join point
(#27892). The pattern-match checker gave different representatives to
equal guard or view expressions, and thus reported spurious
non-exhaustive matches.
Fixes #27892.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
fa5bc4c0 by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: ignore the multiplicities of binders
BndrMap keyed a binder on its type and on its multiplicity, and
eqDeBruijnExpr compared the multiplicities of lambda binders. But the
multiplicity of a let binder has no meaning (Note [Multiplicity of let
binders] in GHC.Types.Var), and Core-to-core passes do not keep the
multiplicities of lambda binders correct (Note [Linting linearity] in
GHC.Core.Lint). Thus the trie separated terms that are equal.
The key-order bug fixed in the previous commit hid this bug. With that
fix, the pattern-match checker gave different representatives to two
equal view expressions when one let came from the source and the other
let came from the beta-reduction of a linear lambda.
Now BndrMap is TypeMapG again, as before the linear types commit, and
eqDeBruijnExpr ignores the multiplicities of lambda binders. The
haddocks of CoreMap and eqCoreExpr state this contract.
Fixes #28095.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
fa6b8c9e by Simon Peyton Jones at 2026-11-16T16:03:04-05:00
Swap visibilities in mkSymCo
As #28123 showed, `mkSymCo` was failing to swap visibility flags
in `ForAllCo`.
Fixing that in turn showed that the change to `mkEtaForAllMCo` that
allegedly fixed #27557 was utterly wrong, and should simply be un-done.
I have added some comments to document the invariants.
- - - - -
cbe0a6bf by fendor at 2026-11-17T09:25:55-05:00
Add support for streaming `ghc -M` to stdout
Adds the flags `-dep-json-stdout` and `-dep-makefile-stdout` which
streams dependency information line-by-line to stdout.
Each dependency generation can be redirected to separate outputs.
Providing any extra `-dep-{json,makefile}[-stdout]` disables the default
generation of the `Makefile` file.
Allows consumers to start processing the dependency information as it
comes in and not waiting for the dependency generation to finish.
`DepStream` abstracts over the possible output handles, which is either
a file or the stdout handle.
Writing to a file requires temporary file paths, thus `DepStream` must
provide a way to perform clean up when dependency processing finished or
when an error is thrown for any reason.
We further decouple the rendering and writing of the result from the
dependency generation, localising side effects and making the code
slightly more readable.
The testsuite now also handles `ghc -M` writing to stdout.
We add a test for each combination of writing to stdout and file,
except for writing both makefile and json.
While it probably works, is really undefined behaviour.
Closes #27937
- - - - -
fbd49db2 by Sylvain Henry at 2026-11-17T09:27:09-05:00
Link the on-demand iserv without --gc-sections
GHC links an iserv program each time a session needs the external
interpreter. The link is static, against the ghci library and the boot
libraries. Like all executable links, it passed -Wl,--gc-sections to a
GNU linker. On libraries built with -split-sections (the release
bindists), the section garbage collection of ld.bfd is the largest part
of that link: with binutils 2.45, the link takes 3 times longer with
--gc-sections than without. The program is temporary and its size is
not important. Thus the iserv link does not use --gc-sections. Other
executable links do not change.
In CI, each ext-interp or ghci-ext test takes 12 to 18 times longer in
the x86_64-linux-fedora43-release test job (split sections) than in the
x86_64-linux-deb13-validate test job (no split sections) on the same
runner, while a normal-way test takes the same time in both. This link
is most of that difference.
See Note [No --gc-sections for the on-demand iserv] in
GHC.Runtime.Interpreter.C.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
09c965e2 by mangoiv at 2026-11-17T09:27:51-05:00
ci: make tests-primops run on marge CI
test primops dispatch was disabled on the *full-ci
group label to avoid dispatching for some of its configs
but wasn't reenabled for marge ci runs which it ought to
run
Fixes #27765
- - - - -
83038fbe by David Eichmann at 2026-11-17T09:28:32-05:00
test driver refactor: replace `.format(**locals())` with f-string
- - - - -
bdf1860b by Alan Zimmerman at 2026-11-17T21:44:55+00:00
EPA: Use AnnList in DecBrl
Via updating the TTG extension point payload
- - - - -
559a62fb by Alan Zimmerman at 2026-11-17T21:44:55+00:00
P:EPA: Replace AnnListLayout / AnnListBrackets with EpLayout
- - - - -
2153d6be by Alan Zimmerman at 2026-11-17T21:44:55+00:00
P:WIP: setLayoutBoth inside markAnnListA
Current problem is it is a global one-shot, and MG has one too
Check: is it needed?
if so, honouring EpLayout may be needed
- - - - -
0ff78d53 by Alan Zimmerman at 2026-11-17T21:44:55+00:00
P:EPA some tests for layout. WIP
- - - - -
7c04e615 by Alan Zimmerman at 2026-11-17T21:44:55+00:00
MOVE EPA: Plan for Fixing AnnList Layout Properly
Also Exactprint layout scope plan
- - - - -
155248a5 by Alan Zimmerman at 2026-11-17T21:44:55+00:00
P:EPA: tidy up a bit. Combine somewhere else
- - - - -
23ab4b92 by Alan Zimmerman at 2026-11-17T21:44:55+00:00
P:EPA: Introduce LayoutFrame stacks in ExactPrint state
- - - - -
7ebe18b5 by Alan Zimmerman at 2026-11-21T13:21:55+00:00
P:EPA: Make EpVirtualBraces noSpanAnchor if no contents
Otherwise the vocurly is emitted at the start of the next
item parsed
Check: is this needed, or just a check for empty contents?
- - - - -
dd794cf7 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
P:Align with ghc-exactprint
- - - - -
e87b89ac by Alan Zimmerman at 2026-11-22T12:28:59+00:00
P:EPA: Fix AnnList leading semis when layout
When there is layout, anything printed triggers it, including leading
semis.
Add some test case examples too
- - - - -
4065ab0f by Alan Zimmerman at 2026-11-22T12:28:59+00:00
P:Exactprint: tidy up layout capturing
- - - - -
622da443 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
F:MD:EPA: add makeDelta test for Test20297
The original #20297 related to comment placement for exact printing
after running ExactPrint.makeDelta on ParsedSource. Add an additional
test that explicitly tests this.
- - - - -
d327487c by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Make ValBinds LocatedA in HsLocalBindsLR
If we have items with an AnnList Annotation, as part of another, which
has different content, it must be LocatedA. This is a technical requirement
due to the way comment allocation happens during the makeDelta processing.
Comments are queued for printing, and as soon as any non-comment is to
be printed, the pending comments before that position are printed, and
in makeDelta processing these attached as preceding comments to the thing
just printed.
The means they end up captured inside the layout region of the AnnList item.
So for
foo = x
where -- comment
x = 3
the comment ends up as a preceding comment of `x = 3`, inside the
layout, and prints as
foo = x
where
-- comment
x = 3
- - - - -
e11e366e by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Make IPBinds LocatedA
- - - - -
01ddd997 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Make ClsInstDecl decls LocatedA
- - - - -
a41bfd2b by Alan Zimmerman at 2026-11-22T12:28:59+00:00
P:EPA: Make ClassDecls decls LocatedA
- - - - -
6b6484f6 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Make ClosedTypeFamily equations Located
For FamilyDecl/ClosedTypeFamily
- - - - -
3b84fbfb by Alan Zimmerman at 2026-11-22T12:28:59+00:00
Perf ok:EPA: Make dd_cons located
- - - - -
38c66645 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Make HsMultiIf options located
- - - - -
2b702456 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Make DecBrl contents LocatedA
- - - - -
137c0f2e by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Located do statements
- - - - -
772fda09 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Print RecStmt located
- - - - -
76fab901 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
P:EPA: HsCmdDo Located
- - - - -
792e7d02 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
Extend Test20297 for additional occurrences
- - - - -
553893a1 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Tweak PatSynBind location for comments
- - - - -
6e2317b3 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: WIP, add test for where ;; ValBinds
- - - - -
73965cc1 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Make EpVirtualBraces noSpanAnchor if no contents
Otherwise the vocurly is emitted at the start of the next
item parsed
Check: is this needed, or just a check for empty contents?
- - - - -
39f0e76f by Alan Zimmerman at 2026-11-22T12:28:59+00:00
Perf ok:EPA: Use EpNoLayout in AnnList with empty contents and no explicit braces
TODO: get rid of unused first arg to epVirtualBraces
- - - - -
c0c3b811 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
Perf ok:TODO: XClassDecl: remove additional EpLayout
- - - - -
f7098a2c by Alan Zimmerman at 2026-11-22T12:28:59+00:00
Perf ok:EPA: Remove CanUpdateAnchorOnly
- - - - -
0455fa76 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
Perf:decrese:EPA: Sync with ghc-exactprint after EPWriter -> CPS
- - - - -
9718d372 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Fix EpVirtualBraces for HsDo
The start of layout must include the leading semi, so we comb3 to
ensure it is included if the initial stmts are empty
- - - - -
7cc0eaab by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: ClsInstDecl where clause span
- - - - -
b58eab4e by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: GADT parens printing, fix
- - - - -
f367fbb2 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
Plan update DO NOT COMMIT
- - - - -
3859a4aa by Alan Zimmerman at 2026-11-22T12:28:59+00:00
F1:EPA: fix AnnList opening span for some cases
F1 as per ANNLIST-LAYOUT-FINDINGS.md
- - - - -
1fc478a5 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
F2:EPA fix vocurly start
F2
- - - - -
51e75e29 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
F3:EPA multi way if
- - - - -
21739dd8 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
F4:EPA: Parse leading semis for gadt_contrs
- - - - -
3e2a19f6 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: First pass implementation of HsList, for ClassDecls
Just as a straight list replacement to start with, no payload.
This shows the scope and invasiveness of the initial change
- - - - -
b2442349 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: HsList attempt WIP
- - - - -
b7c6e311 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
Enable ppr test for Haddock1. It currently fails
- - - - -
111b1a94 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
WIP on removing NoEpAnn. Likely abandon
- - - - -
0855c736 by Alan Zimmerman at 2026-11-22T12:28:59+00:00
EPA: Add an overview doc for exact printing
- - - - -
d3c831ed by Simon Peyton Jones at 2026-11-22T12:28:59+00:00
Added an intro section
- - - - -
322 changed files:
- .gitignore
- .gitlab-ci.yml
- .gitlab/ci.sh
- .gitlab/generate-ci/gen_ci.hs
- .gitlab/jobs.yaml
- .gitlab/rel_eng/mk-ghcup-metadata/mk_ghcup_metadata.py
- + ANNLIST-LAYOUT-FINDINGS.md
- + ANNLIST-LAYOUT-PLAN.md
- + ExactPrint.md
- + LAYOUT-SCOPE-PLAN.md
- + changelog.d/27821
- + changelog.d/27892
- + changelog.d/28101
- + changelog.d/T26754
- + changelog.d/T28123
- + changelog.d/T9809-timer-manager-contention
- changelog.d/allow-gadt-prefix-con-parens
- + changelog.d/fix-aarch64-veneer-target-16686
- + changelog.d/gadt-curried-contexts-27424
- + changelog.d/iserv-no-gc-sections.md
- + changelog.d/make-depends-deprecate-doMkDependHS
- + changelog.d/make-depends-json
- + changelog.d/make-depends-multiple-home-units
- + changelog.d/make-depends-streaming-output
- + changelog.d/ncg-reg-usage.md
- + changelog.d/remove-long-deprecated-flags.md
- + changelog.d/stage3-cross-bindists
- compiler/GHC/CmmToAsm/AArch64/Instr.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/Instr.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- compiler/GHC/CmmToAsm/PPC/Ppr.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- + compiler/GHC/CmmToAsm/RegUsage.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToC.hs
- compiler/GHC/Core/Map/Expr.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/CoreToStg.hs
- compiler/GHC/Driver/Backpack.hs
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Flags.hs
- compiler/GHC/Driver/Main/Interactive.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Driver/Session/Units.hs
- compiler/GHC/Hs.hs
- compiler/GHC/Hs/Binds.hs
- compiler/GHC/Hs/Decls.hs
- compiler/GHC/Hs/DocString.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/Hs/ImpExp.hs
- compiler/GHC/Hs/Instances.hs
- compiler/GHC/Hs/Stats.hs
- compiler/GHC/Hs/Type.hs
- compiler/GHC/Hs/Utils.hs
- compiler/GHC/HsToCore/Docs.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/Pmc/Desugar.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/HsToCore/Ticks.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Linker/Executable.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/Annotation.hs
- compiler/GHC/Parser/Errors/Ppr.hs
- compiler/GHC/Parser/Errors/Types.hs
- compiler/GHC/Parser/Header.hs
- compiler/GHC/Parser/Lexer.x
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Parser/PostProcess/Haddock.hs
- compiler/GHC/Rename/Bind.hs
- compiler/GHC/Rename/Expr.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Rename/Names.hs
- compiler/GHC/Rename/Splice.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Interpreter/C.hs
- compiler/GHC/Stg/Make.hs
- compiler/GHC/StgToCmm/Closure.hs
- compiler/GHC/Tc/Deriv.hs
- compiler/GHC/Tc/Gen/Bind.hs
- compiler/GHC/Tc/Gen/Expr.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/Instance.hs
- compiler/GHC/Tc/Types/Origin.hs
- compiler/GHC/Tc/Utils/Env.hs
- compiler/GHC/Tc/Zonk/Type.hs
- compiler/GHC/ThToHs.hs
- compiler/GHC/Types/Literal/Floating.hs
- compiler/GHC/Types/Tickish.hs
- compiler/GHC/Utils/Json.hs
- compiler/Language/Haskell/Syntax.hs
- compiler/Language/Haskell/Syntax/Basic.hs
- compiler/Language/Haskell/Syntax/Binds.hs
- compiler/Language/Haskell/Syntax/Decls.hs
- compiler/Language/Haskell/Syntax/Decls/Foreign.hs
- compiler/Language/Haskell/Syntax/Expr.hs
- compiler/Language/Haskell/Syntax/Type.hs
- compiler/ghc.cabal.in
- + distrib/configure.ac
- docs/users_guide/codegens.rst
- docs/users_guide/expected-undocumented-flags.txt
- docs/users_guide/exts/control.rst
- docs/users_guide/exts/ffi.rst
- docs/users_guide/exts/gadt_syntax.rst
- docs/users_guide/exts/pragmas.rst
- docs/users_guide/ghc.rst
- + docs/users_guide/make-depends-json-schema-1_0.json
- docs/users_guide/profiling.rst
- docs/users_guide/separate_compilation.rst
- − docs/users_guide/what_glasgow_exts_does.rst
- ghc/GHCi/UI.hs
- ghc/Main.hs
- hadrian/src/BindistConfig.hs
- hadrian/src/Oracles/Setting.hs
- hadrian/src/Rules/BinaryDist.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Settings/Builders/RunTest.hs
- hadrian/src/Settings/Packages.hs
- libraries/base/src/Data/Foldable.hs
- libraries/base/tests/.gitignore
- + libraries/base/tests/T9809.hs
- libraries/base/tests/all.T
- libraries/ghc-internal/src/GHC/Internal/Event/Manager.hs
- libraries/ghc-internal/src/GHC/Internal/Event/TimerManager.hs
- rts/Linker.c
- rts/LinkerInternals.h
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/RtsUtils.c
- rts/include/Rts.h
- + rts/include/rts/RtsSymbols.h
- rts/linker/PEi386.c
- rts/linker/elf_reloc_aarch64.c
- rts/rts.cabal
- testsuite/README.md
- testsuite/config/ghc
- testsuite/driver/junit.py
- testsuite/driver/my_typing.py
- testsuite/driver/runtests.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/driver/testutil.py
- testsuite/mk/test.mk
- + testsuite/tests/cmm/should_run/T28101.hs
- + testsuite/tests/cmm/should_run/T28101.stdout
- + testsuite/tests/cmm/should_run/T28101_cmm.cmm
- testsuite/tests/cmm/should_run/all.T
- testsuite/tests/concurrent/should_run/all.T
- + testsuite/tests/concurrent/should_run/registerFd001.hs
- + testsuite/tests/concurrent/should_run/registerFd001.stdout
- testsuite/tests/driver/Makefile
- testsuite/tests/driver/T2464.hs
- testsuite/tests/driver/T2464.stderr
- + testsuite/tests/driver/mkdepend/Makefile
- + testsuite/tests/driver/mkdepend/README.md
- + testsuite/tests/driver/mkdepend/T24384/A.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/D.hs
- + testsuite/tests/driver/mkdepend/T24384/E.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/DepInternal.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/dep-internal.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep-public/DepPublic.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-public/dep-public.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep/Dep.hs
- + testsuite/tests/driver/mkdepend/T24384/dep/dep.pkg
- + testsuite/tests/driver/mkdepend/T24384/foo.h
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/preproc.sh
- + testsuite/tests/driver/mkdepend/T24384a.stdout
- + testsuite/tests/driver/mkdepend/T24384b.stdout
- + testsuite/tests/driver/mkdepend/T24384c.stdout
- + testsuite/tests/driver/mkdepend/all.T
- + testsuite/tests/driver/mkdepend/format_json.sh
- + testsuite/tests/driver/mkdepend/format_makefile.sh
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs-boot
- + testsuite/tests/driver/mkdepend/mhu01/a/A/TH.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Normal.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Splice.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/c/C.hs
- + testsuite/tests/driver/mkdepend/mhu01/unitA
- + testsuite/tests/driver/mkdepend/mhu01/unitB
- + testsuite/tests/driver/mkdepend/mhu01/unitC
- + testsuite/tests/driver/mkdepend/mhu02/A.hs
- + testsuite/tests/driver/mkdepend/mhu02/B.hs
- + testsuite/tests/driver/mkdepend/mhu02/pp.sh
- + testsuite/tests/driver/mkdepend/mhu02/unitA
- + testsuite/tests/driver/mkdepend/mhu02/unitB
- + testsuite/tests/driver/mkdepend/mhu03/pkg/A.hs
- + testsuite/tests/driver/mkdepend/mhu03/pkg/pp.sh
- + testsuite/tests/driver/mkdepend/mhu03/unitA
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend01/A.hs
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01b.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01c.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu03.dep-json
- testsuite/tests/ffi/should_run/T2594.hs
- testsuite/tests/ffi/should_run/ffi015.hs
- testsuite/tests/ffi/should_run/fptr01.hs
- testsuite/tests/ffi/should_run/fptrfail01.hs
- − testsuite/tests/gadt/T12087.stderr
- + testsuite/tests/gadt/T12087a.hs
- testsuite/tests/gadt/T12087.hs → testsuite/tests/gadt/T12087b.hs
- + testsuite/tests/gadt/T12087b.stderr
- + testsuite/tests/gadt/T27424a.hs
- + testsuite/tests/gadt/T27424b.hs
- + testsuite/tests/gadt/T27424b.stderr
- testsuite/tests/gadt/all.T
- testsuite/tests/ghc-api/exactprint/T22919.stderr
- testsuite/tests/ghc-api/exactprint/Test20239.stderr
- testsuite/tests/ghc-api/exactprint/ZeroWidthSemi.stderr
- testsuite/tests/ghci/linking/T25155_iserv_main.c
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T17544_kw.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T24221.stderr
- testsuite/tests/indexed-types/should_compile/all.T
- testsuite/tests/indexed-types/should_fail/SkolemOccursLoop.hs
- testsuite/tests/module/mod185.stderr
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpParsedAstComments.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/DumpSemis.hs
- testsuite/tests/parser/should_compile/DumpSemis.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- testsuite/tests/parser/should_compile/T14189.stderr
- testsuite/tests/parser/should_compile/T15279.stderr
- testsuite/tests/parser/should_compile/T15323.stderr
- testsuite/tests/parser/should_compile/T20452.stderr
- testsuite/tests/parser/should_compile/T20718.stderr
- testsuite/tests/parser/should_compile/T20846.stderr
- testsuite/tests/perf/compiler/hard_hole_fits.stderr
- testsuite/tests/perf/compiler/large-project/all.T
- + testsuite/tests/perf/compiler/large-project/large-project-mhu.sh
- + testsuite/tests/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- testsuite/tests/primops/should_run/all.T
- + testsuite/tests/printer/Layout.hs
- testsuite/tests/printer/Makefile
- testsuite/tests/printer/Ppr003.hs
- testsuite/tests/printer/T18791.stderr
- + testsuite/tests/printer/T27424c.hs
- + testsuite/tests/printer/Test20297.expected.hs
- testsuite/tests/printer/Test20297.hs
- testsuite/tests/printer/Test20297.stdout
- + testsuite/tests/printer/Test20297MD.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/printer/all.T
- testsuite/tests/rts/T17088.hs
- testsuite/tests/rts/all.T
- testsuite/tests/rts/linker/Makefile
- + testsuite/tests/rts/linker/T27807.s
- + testsuite/tests/rts/linker/T27807.stdout
- testsuite/tests/rts/linker/all.T
- testsuite/tests/rts/pause-resume/all.T
- testsuite/tests/rts/pause-resume/pause_resume_via_safe_ffi_concurrent.hs
- + testsuite/tests/rts/symbols/Main.hs
- + testsuite/tests/rts/symbols/Makefile
- + testsuite/tests/rts/symbols/all.T
- + testsuite/tests/rts/symbols/dumpDeclaredSymbols.c
- + testsuite/tests/rts/symbols/rts-check-symbols.sh
- + testsuite/tests/rts/symbols/rts-check-symbols.stdout
- + testsuite/tests/simplCore/should_compile/T27892.hs
- + testsuite/tests/simplCore/should_compile/T27892.stderr
- + testsuite/tests/simplCore/should_compile/T28095a.hs
- + testsuite/tests/simplCore/should_compile/T28095a.stderr
- testsuite/tests/simplCore/should_compile/all.T
- testsuite/tests/th/GadtConSigs_th_dump1.hs
- testsuite/tests/th/GadtConSigs_th_dump1.stderr
- + testsuite/tests/th/T27424d.hs
- + testsuite/tests/th/T27424d.stderr
- testsuite/tests/th/all.T
- + testsuite/tests/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
- utils/check-exact/Parsers.hs
- utils/check-exact/Transform.hs
- utils/check-exact/Utils.hs
- utils/haddock/CHANGES.md
- utils/haddock/doc/markup.rst
- utils/haddock/haddock-api/haddock-api.cabal
- utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Parser.hs
- utils/haddock/haddock-api/src/Haddock/Backends/LaTeX.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
- utils/haddock/haddock-api/src/Haddock/Convert.hs
- utils/haddock/haddock-api/src/Haddock/GhcUtils.hs
- utils/haddock/haddock-api/src/Haddock/Interface/Create.hs
- utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
- utils/haddock/haddock-api/src/Haddock/Types.hs
- utils/haddock/haddock-library/CHANGES.md
- utils/haddock/haddock-library/fixtures/Fixtures.hs
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.parsed
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.parsed
- utils/haddock/haddock-library/haddock-library.cabal
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser.hs
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser/Identifier.hs
- utils/haddock/haddock-library/test/Documentation/Haddock/ParserSpec.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/750087f8e4b3725d468fdabf388967…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/750087f8e4b3725d468fdabf388967…
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
1
0
[Git][ghc/ghc][wip/T27212] Document and refactor eta-reduction documentation
by Simon Peyton Jones (@simonpj) 22 Nov '26
by Simon Peyton Jones (@simonpj) 22 Nov '26
22 Nov '26
Simon Peyton Jones pushed to branch wip/T27212 at Glasgow Haskell Compiler / GHC
Commits:
cd190880 by Simon Peyton Jones at 2026-11-22T09:42:41+00:00
Document and refactor eta-reduction documentation
Triggered by #27212, this patch does several related things.
* #27212 suggested that `findRhsArity` should ask for eta-expansion
whenever the RHS's `manifestArity` is less than the arity it finds.
That is a misconception: it deliberately compares with `exprArity`,
which counts PAPs, so that we do not eta-expand PAPs (#9020).
Switching to `manifestArity` makes compile time worse in T13960
and T13056.
So this patch changes no code here; we continue to expand only to
increase `exprArity` not `manifestArity`. Instead it documents the
design in `findRhsArity`, `tryEtaExpandRhs`, `wantEtaExpansion` and
Note [Do not eta-expand PAPs] (which now records the #27212
experiment).
* Refactor GHC.Core.Opt.Arity.tryEtaReduce, which was hard to
understand:
- Accumulate an MCoercion rather than a Coercion, so the common
no-cast case builds no coercions at all.
- Separate equations of `go` for type and value arguments. For
value arguments, the new `getTrivialHead_maybe` looks through any
nesting of casts and floatable ticks, and `mkEtaReduceFunCo` builds
the coercion.
- Make the FunCo with `mkFunCo2` and compute its right-hand
FunTyFlag from the coercion kinds. The cast can turn a Type-kinded
argument into a Constraint-kinded one. New test T27212 covers this.
- `mkEtaReduceForAllMCo` builds the ForAllCo for type arguments. It
is tiresomely similar to `mkEtaForAllMCo`, but with the visibilities
the other way round (#24014). It will go away again once !17006
lands.
- New helper `mCoToCo` in GHC.Core.TyCo.Make.
* Drop the checks on multiplicity in `tryEtaReduce`, which sometimes
disabled eta-reduction. For example, (\x. K x) has type Int -> T,
but the data constructor has type K :: Int %1 -> T, so we used to
refuse to eta-reduce it to K.
But Note [Linting linearity] in GHC.Core.Lint (EXAMPLE 4) already
says that we do not preserve linearity under eta-reduction, so this
change just puts that claim into practice. See (EtaMult) in
Note [Eta reduction soundness].
Consequences in the testsuite:
- T18052a: the pattern-synonym builder (\x y. (x,y)) is now just (,).
- T21888a: the NOINLINE function (f x = Just x) becomes (f = Just),
so f loses its CPR signature. The test is about demands, not CPR.
* Tidy up the documentation of eta-reduction:
- Relabel the criteria in Note [Eta reduction soundness] as (EtaA),
(EtaS), (EtaR), (EtaE), (EtaT), (EtaJ), (EtaB) and (EtaW), and
update all references to them. Also fix references to point (2) of
Note [Eta reduction makes sense], which no longer exists.
- Replace the confused "never reduce arity" bullet with an example in
(EtaA), cross-referenced from Note [Arity robustness].
- Add historical notes (EtaMult) and (EtaBot).
- Label the equations in Note [Eta reduction with casted arguments]
(ECA1-4), and point to the code that implements them.
LLM disclosure: I interacted with Claude a lot for this MR, but I
wrote all the code and docs myself.
- - - - -
13 changed files:
- compiler/GHC/Core/Coercion.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/OccurAnal.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Utils.hs
- testsuite/tests/dmdanal/sigs/T21888a.stderr
- testsuite/tests/printer/T18052a.stderr
- + testsuite/tests/simplCore/should_compile/T27212.hs
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Coercion.hs
=====================================
@@ -74,7 +74,7 @@ module GHC.Core.Coercion (
isReflCoVar_maybe, assertGoodForAllCo,
- coToMCo, kindCoToMKindCo,
+ coToMCo, kindCoToMKindCo, mCoToCo,
mkTransMCo, mkTransMCoL, mkTransMCoR, mkCastTyMCo, mkSymMCo,
mkFunResMCo, mkPiMCos,
isReflMCo, checkReflexiveMCo,
=====================================
compiler/GHC/Core/Opt/Arity.hs
=====================================
@@ -886,8 +886,14 @@ findRhsArity :: ArityOpts -> RecFlag -> Id -> CoreExpr
-- This implements the fixpoint loop for arity analysis
-- See Note [Arity analysis]
--
--- The Bool is True if the returned arity is greater than (exprArity rhs)
--- so the caller should do eta-expansion
+-- The Bool is True if
+-- the returned arity is greater than (exprArity rhs)
+-- so the caller should do eta-expansion
+-- NB: `exprArity`, not `manifestArity`:
+-- a PAP such as (\x. f x), where f has arity 3, has exprArity 3,
+-- so we do not eta-expand it to (\x y z. f x y z)
+-- See Note [Do not eta-expand PAPs] in GHC.Core.Opt.Simplify.Utils
+--
-- That Bool is never True for join points, which are never eta-expanded
--
-- Returns an SafeArityType that is guaranteed trimmed to typeArity of 'bndr'
@@ -903,10 +909,11 @@ findRhsArity opts is_rec bndr rhs
| otherwise
= (arity_increased, non_join_arity_type)
- -- arity_increased: eta-expand if we'll get more lambdas
- -- to the top of the RHS
+ -- arity_increased: eta-expand if the analysis finds a greater arity
+ -- than exprArity, which already takes account of PAPs
where
- old_arity = exprArity rhs
+ old_arity = exprArity rhs -- See Note [Do not eta-expand PAPs]
+ -- in GHC.Core.Opt.Simplify.Utils
init_env :: ArityEnv
init_env = findRhsArityEnv opts (isJoinId bndr)
@@ -2388,6 +2395,7 @@ mkEtaForAllMCo (Bndr tcv vis) ty mco
-- and is SymCo'd in `etaInfoAbs`. Hence the orientation of the visibility
-- flags. A bit of a brain-strain (#27557).
+
{-
************************************************************************
* *
@@ -2452,16 +2460,20 @@ perform eta reduction on an expression with n leading lambdas `\xs. e xs`
(checked in 'is_eta_reduction_sound' in 'tryEtaReduce', which focuses on the
case where `e` is trivial):
-(A) It is sound to eta-reduce n arguments as long as n does not exceed the
- `exprArity` of `e`. (Needs Arity analysis.)
- This criterion exploits information about how `e` is *defined*.
+(EtaA) It is sound to eta-reduce n arguments as long as n does not exceed the
+ `exprArity` of `e`. (Needs Arity analysis.) This criterion exploits information
+ about how `e` is *defined*. For example:
+ f = \xy. g x y ===> f = g
+ This eta-reduction is good only if `g` has arity at least 2, otherwise
+ f's arity will decrease from 2 to 1.
+ c.f. Note [Arity robustness] in GHC.Core.Opt.Simplify.Env.
- Example: If `e = \x. bot` then we know it won't diverge until it is called
- with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`.
+ Another example: If `e = \x. bot` then we know it won't diverge until it
+ is called with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`.
By contrast, it would be *unsound* to eta-reduce 2 args, `\x y. e x y` to `e`:
`e 42` diverges when `(\x y. e x y) 42` does not.
-(S) It is sound to eta-reduce n arguments in an evaluation context in which all
+(EtaS) It is sound to eta-reduce n arguments in an evaluation context in which all
calls happen with at least n arguments. (Needs Strictness analysis.)
NB: This treats evaluations like a call with 0 args.
NB: This criterion exploits information about how `e` is *used*.
@@ -2483,35 +2495,31 @@ case where `e` is trivial):
But it is unsound to eta-reduce the arg in `g2 (\x y. e x y)` to `g2 e`
when `e = \x. if x then bot else id`, because the latter will diverge when
the former would not. Fortunately, the strictness analyser will report
- "Not always called with two arguments" for `g2` and we won't eta-expand.
+ "Not always called with two arguments" for `g2` and we won't eta-reduce.
See Note [Eta reduction based on evaluation context] for the implementation
details. This criterion is tested extensively in T21261.
-(R) Note [Eta reduction in recursive RHSs] tells us that we should not
+(EtaR) Note [Eta reduction in recursive RHSs] tells us that we should not
eta-reduce `f` in its own RHS and describes our fix.
There we have `f = \x. f x` and we should not eta-reduce to `f=f`. Which
might change a terminating program (think @f `seq` e@) to a non-terminating
one.
-(E) (See fun_arity in tryEtaReduce.) As a perhaps special case on the
- boundary of (A) and (S), when we know that a fun binder `f` is in
- WHNF, we simply assume it has arity 1 and apply (A). Example:
+(EtaE) (See fun_arity in tryEtaReduce.) As a perhaps special case on the
+ boundary of (EtaA) and (EtaS), when we know that a fun binder `f` is in
+ WHNF, we simply assume it has arity 1 and apply (EtaA). Example:
g f = f `seq` \x. f x
Here it's sound eta-reduce `\x. f x` to `f`, because `f` can't be bottom
after the `seq`. This turned up in #7542.
- T. If the binders are all type arguments, it's always safe to eta-reduce,
- regardless of the arity of f.
- /\a b. f @a @b --> f
-
-2. Type and dictionary abstraction. Regardless of whether 'f' is a value, it
+(EtaT) Type and dictionary abstraction. Regardless of whether 'f' is a value, it
is always sound to reduce /type lambdas/, thus:
- (/\a -> f a) --> f
+ (/\a -> f @a) --> f
Moreover, we always want to, because it makes RULEs apply more often:
- This RULE: `forall g. foldr (build (/\a -> g a))`
+ This RULE: `forall g. foldr (build (/\a -> g @a))`
should match `foldr (build (/\b -> ...something complex...))`
- and the simplest way to do so is eta-reduce `/\a -> g a` in the RULE to `g`.
+ and the simplest way to do so is eta-reduce `/\a -> g @a` in the RULE to `g`.
More debatably, we extend this to dictionary arguments too, because the type
checker can insert these eta-expanded versions, with both type and dictionary
@@ -2523,18 +2531,25 @@ case where `e` is trivial):
And here are a few more technical criteria for when it is *not* sound to
eta-reduce that are specific to Core and GHC:
-(J) We may not undersaturate join points.
+(EtaJ) We may not undersaturate join points.
See Note [Invariants on join points] in GHC.Core, and #20599.
-(B) We may not undersaturate functions with no binding.
+(EtaB) We may not undersaturate functions with no binding.
See Note [Eta expanding primops].
-(W) We may not undersaturate StrictWorkerIds.
+(EtaW) We may not undersaturate StrictWorkerIds.
See Note [CBV Function Ids: overview] in GHC.Types.Id.Info.
-Here is a list of historic accidents surrounding unsound eta-reduction:
-* Consider
+Here is a list of historic notes surrounding unsound eta-reduction:
+
+(EtaMult) We used to disable eta-reduction if performing it would change multiplicity.
+ For example:
+ (\x. K x) :: Int -> T but K :: Int %1 -> T
+ But that (a) inhibits beneficial eta-reduction (b) costs extra work to check, and
+ now we don't even try. See Note [Linting linearity] in GHC.Core.Lint, esp EXAMPLE 4
+
+(EtaBot) Consider
f = \x.f x
h y = case (case y of { True -> f `seq` True; False -> False }) of
True -> ...; False -> ...
@@ -2548,16 +2563,6 @@ Here is a list of historic accidents surrounding unsound eta-reduction:
Result: seg-fault because the boolean case actually gets a function value.
See #1947.
-* Never *reduce* arity. For example
- f = \xy. g x y
- Then if h has arity 1 we don't want to eta-reduce because then
- f's arity would decrease, and that is bad
- [SG in 2022: I don't understand this point. There is no `h`, perhaps that
- should have been `g`. Even then, this proposed eta-reduction is invalid by
- criterion (A), which might actually be the point this anecdote is trying to
- make. Perhaps the "no arity decrease" idea is also related to
- Note [Arity robustness]?]
-
Note [Do not eta reduce PAPs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I considered eta-reducing if the result is a PAP:
@@ -2598,11 +2603,14 @@ This should be eta-reduced to
So we need to accumulate a coercion, pushing it inward (past
variable arguments only) thus:
- f (x |> co_arg) |> co --> (f |> (sym co_arg -> co)) x
- f (x:t) |> co --> (f |> (t -> co)) x
- f @ a |> co --> (f |> (forall a.co)) @ a
- f @ (g:t1~t2) |> co --> (f |> (t1~t2 => co)) @ (g:t1~t2)
-These are the equations for ok_arg.
+(ECA1) \x. f (x |> co_arg) |> co --> (f |> (sym co_arg -> co))
+(ECA2) \x. f (x:t) |> co --> (f |> (t -> co))
+(ECA3) \x. f (x:t1~#t2) |> co --> (f |> (t1~#t2 => co))
+(ECA4) \x. f @ a |> co --> (f |> (forall a.co))
+
+(ECA1,2,4) are implemented by the `go` equations in `tryEtaReduce`.
+However (ECA3) is not implemented -- it could be, perhaps by spotting
+an argument that is (Coercion (CoVar x)), but it seems like a rare case.
Note [Eta reduction with casted function]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -2620,7 +2628,7 @@ eta-expansion may be turned off (by sm_eta_expand).
Note [Eta reduction based on evaluation context]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Note [Eta reduction soundness], criterion (S) allows us to eta-reduce
+Note [Eta reduction soundness], criterion (EtaS) allows us to eta-reduce
`g (\x y. e x y)` to `g e` when we know that `g` always calls its parameter with
at least 2 arguments. So how do we read that off `g`'s demand signature?
@@ -2713,13 +2721,13 @@ tryEtaReduce :: UnVarSet -> [Var] -> CoreExpr -> SubDemand -> Maybe CoreExpr
-- and Note [Eta reduction makes sense] when that is the case.
-- and Note [Eta reduction based on evaluation context] for the `eval_sd` arg
tryEtaReduce rec_ids bndrs body eval_sd
- = go (reverse bndrs) body (mkRepReflCo (exprType body))
+ = go (reverse bndrs) body MRefl
where
- incoming_arity = count isId bndrs -- See Note [Eta reduction makes sense], point (2)
+ incoming_arity = count isId bndrs -- See (EtaA) in Note [Eta reduction soundness]
go :: [Var] -- Binders, innermost first, types [a3,a2,a1]
-> CoreExpr -- Of type tr
- -> Coercion -- Of type tr ~ ts
+ -> MCoercion -- Of type tr ~ ts
-> Maybe CoreExpr -- Of type a1 -> a2 -> a3 -> ts
-- See Note [Eta reduction with casted arguments]
-- for why we have an accumulating coercion
@@ -2729,19 +2737,37 @@ tryEtaReduce rec_ids bndrs body eval_sd
-- See Note [Eta reduction with casted function]
go bs (Cast e co1) co2
- = go bs e (co1 `mkTransCo` co2)
+ = go bs e (co1 `mkTransMCoR` co2)
go bs (Tick t e) co
| tickishFloatable t
= fmap (Tick t) $ go bs e co
-- Float app ticks: \x -> Tick t (e x) ==> Tick t e
- go (b : bs) (App fun arg) co
- | Just (co', ticks) <- ok_arg b arg co (exprType fun)
- = fmap (flip (foldr mkTick) ticks) $ go bs fun co'
- -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e
+ -- Implements (ECA4)
+ go all_bs@(b : bs) all_e@(App fun (Type arg_ty)) mco
+ | Just tv <- getTyVar_maybe arg_ty
+ , b == tv
+ , Just (bndr, body_ty) <- splitForAllForAllTyBinder_maybe (exprType fun)
+ = go bs fun (mkEtaReduceForAllMCo bndr body_ty tv mco)
- go remaining_bndrs fun co
+ | otherwise
+ = go_finish all_bs all_e mco
+ -- Want to go to the finish case; see the call
+ -- to (all isTyVar remaining_bndrs) there
+
+ -- Implements (ECA1,2)
+ go (b : bs) (App fun val_arg) mco
+ | Just (v, arg_mco, arg_ticks) <- getTrivialHead_maybe val_arg
+ , b == v
+ , Just co' <- mkEtaReduceFunCo (exprType fun) arg_mco mco
+ = fmap (flip (foldr mkTick) arg_ticks) $
+ go bs fun co'
+ -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e
+
+ go bs fun co = go_finish bs fun co
+
+ go_finish remaining_bndrs fun co
| all isTyVar remaining_bndrs
-- If all the remaining_bnrs are tyvars, then the etad_exp
-- will be trivial, which is what we want.
@@ -2752,7 +2778,7 @@ tryEtaReduce rec_ids bndrs body eval_sd
, remaining_bndrs `ltLength` bndrs
-- Only reply Just if /something/ has happened
, ok_fun fun
- , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfCo co
+ , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfMCo co
reduced_bndrs = mkVarSet (dropList remaining_bndrs bndrs)
-- reduced_bndrs are the ones we are eta-reducing away
, used_vars `disjointVarSet` reduced_bndrs
@@ -2761,10 +2787,10 @@ tryEtaReduce rec_ids bndrs body eval_sd
-- See Note [Eta reduction makes sense], intro and point (1)
-- NB: don't compute used_vars from exprFreeVars (mkCast fun co)
-- because the latter may be ill formed if the guard fails (#21801)
- = Just (mkLams (reverse remaining_bndrs) (mkCast fun co))
+ = Just (mkLams (reverse remaining_bndrs) (mkCastMCo fun co))
- go _remaining_bndrs _fun _ = -- pprTrace "tER fail" (ppr _fun $$ ppr _remaining_bndrs) $
- Nothing
+ | otherwise
+ = Nothing
---------------
-- See Note [Eta reduction makes sense], point (1)
@@ -2777,18 +2803,18 @@ tryEtaReduce rec_ids bndrs body eval_sd
---------------
-- See Note [Eta reduction soundness], this is THE place to check soundness!
is_eta_reduction_sound fun
- | fun `elemUnVarSet` rec_ids -- Criterion (R)
+ | fun `elemUnVarSet` rec_ids -- Criterion (EtaR)
= False -- Don't eta-reduce in fun in its own recursive RHSs
- | cantEtaReduceFun fun -- Criteria (J), (W), (B)
+ | cantEtaReduceFun fun -- Criteria (EtaJ), (EtaW), (EtaB)
= False -- Function can't be eta reduced to arity 0
-- without violating invariants of Core and GHC
| otherwise
= -- Check that eta-reduction won't make the program stricter...
- fun_arity fun >= incoming_arity -- Criterion (A) and (E)
- || all_calls_with_arity incoming_arity -- Criterion (S)
- || all ok_lam bndrs -- Criterion (T)
+ fun_arity fun >= incoming_arity -- Criterion (EtaA) and (EtaE)
+ || all_calls_with_arity incoming_arity -- Criterion (EtaS)
+ || all ok_lam bndrs -- Criterion (EtaT)
all_calls_with_arity n = isStrict (fst $ peelManyCalls n eval_sd)
-- See Note [Eta reduction based on evaluation context]
@@ -2797,57 +2823,76 @@ tryEtaReduce rec_ids bndrs body eval_sd
fun_arity fun
| arity > 0 = arity
| isEvaldUnfolding (idUnfolding fun) = 1
- -- See Note [Eta reduction soundness], criterion (E)
+ -- See Note [Eta reduction soundness], criterion (EtaE)
| otherwise = 0
where
arity = idArity fun
---------------
ok_lam v = isTyVar v || isEvId v
- -- See Note [Eta reduction makes sense], point (2)
-
- ---------------
- ok_arg :: Var -- Of type bndr_t
- -> CoreExpr -- Of type arg_t
- -> Coercion -- Of kind (t1~t2)
- -> Type -- Type (arg_t -> t1) of the function
- -- to which the argument is supplied
- -> Maybe (Coercion -- Of type (arg_t -> t1 ~ bndr_t -> t2)
- -- (and similarly for tyvars, coercion args)
- , [CoreTickish])
- -- See Note [Eta reduction with casted arguments]
- ok_arg bndr (Type arg_ty) co fun_ty
- | Just tv <- getTyVar_maybe arg_ty
- , bndr == tv = case splitForAllForAllTyBinder_maybe fun_ty of
- Just (Bndr _ vis, _) -> Just (fco, [])
- where !fco = mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co
- -- The lambda we are eta-reducing always has visibility
- -- 'coreTyLamForAllTyFlag' which may or may not match
- -- the visibility on the inner function (#24014)
- Nothing -> pprPanic "tryEtaReduce: type arg to non-forall type"
- (text "fun:" <+> ppr bndr
- $$ text "arg:" <+> ppr arg_ty
- $$ text "fun_ty:" <+> ppr fun_ty)
- ok_arg bndr (Var v) co fun_ty
- | bndr == v
- , let mult = idMult bndr
- , Just (_af, fun_mult, _, _) <- splitFunTy_maybe fun_ty
- , mult `eqType` fun_mult -- There is no change in multiplicity, otherwise we must abort
- = Just (mkFunResCo Representational bndr co, [])
- ok_arg bndr (Cast e co_arg) co fun_ty
- | (ticks, Var v) <- stripTicksTop tickishFloatable e
- , Just (_, fun_mult, _, _) <- splitFunTy_maybe fun_ty
- , bndr == v
- , fun_mult `eqType` idMult bndr
- = Just (mkFunCoNoFTF Representational (multToCo fun_mult) (mkSymCo co_arg) co, ticks)
- -- The simplifier combines multiple casts into one,
- -- so we can have a simple-minded pattern match here
- ok_arg bndr (Tick t arg) co fun_ty
- | tickishFloatable t, Just (co', ticks) <- ok_arg bndr arg co fun_ty
- = Just (co', t:ticks)
-
- ok_arg _ _ _ _ = Nothing
+ -- See Note [Eta reduction soundness], point (EtaT)
+
+
+-----------------
+getTrivialHead_maybe :: CoreExpr -> Maybe (Id, MCoercion, [CoreTickish])
+-- (getTrivialHead_maybe e) returns (Just (fn, co,ts))
+-- if `e` looks like (Tick ts (fn |> co)) and ts are floatable
+-- So co :: fn_ty ~ arg_ty
+
+getTrivialHead_maybe (Var v)
+ = Just (v, MRefl, [])
+
+getTrivialHead_maybe (Cast e co_outer)
+ = do { (v, mco_inner, ticks) <- getTrivialHead_maybe e
+ ; return (v, mco_inner `mkTransMCoL` co_outer, ticks) }
+
+getTrivialHead_maybe (Tick t arg)
+ | tickishFloatable t
+ = do { (v, co, ticks) <- getTrivialHead_maybe arg
+ ; return (v, co, t:ticks) }
+
+getTrivialHead_maybe _ = Nothing
+
+-----------------
+mkEtaReduceFunCo :: Type -> MCoercion -> MCoercion -> Maybe MCoercion
+mkEtaReduceFunCo _ MRefl MRefl
+ = Just MRefl -- Very common case
+mkEtaReduceFunCo fun_ty arg_mco res_mco
+ | Just (ftf, mult, arg_ty, res_ty) <- splitFunTy_maybe fun_ty
+ -- fun_ty = arg_ty -> res_ty
+ -- sym arg_mco : arg_ty ~ inner_arg_ty
+ -- res_mco : res_ty ~ outer_res_ty
+ , let arg_co = mCoToCo Representational arg_ty arg_mco
+ res_co = mCoToCo Representational res_ty res_mco
+ mult_co = multToCo mult
+ ftf' = chooseFunTyFlag (coercionLKind arg_co) (coercionRKind res_co)
+ = Just (MCo (mkFunCo2 Representational ftf ftf' mult_co (mkSymCo arg_co) res_co))
+ -- (arg_ty -> res_ty) ~ (inner_arg_ty -> outer_res_ty)
+ | otherwise
+ = Nothing
+-----------------
+mkEtaReduceForAllMCo :: ForAllTyBinder -> Type -> TyVar -> MCoercion -> MCoercion
+-- Very similar to mkEtaForAllMCo, but with
+-- the visibilities the other way around. Tiresome.
+-- mkEtaReduceForAllMCo (forall a[vis]. body_ty) b (co :: ty1 ~ ty2)
+-- (where `b` may be free in `ty1` and `ty2`)
+-- = ForAllCo b[vis]~[spec]. (co :: ty1 ~ ty2)
+-- where `coreTyLamForAllTyFlag` is [spec]
+mkEtaReduceForAllMCo (Bndr fun_tv vis) body_ty tv mco
+ = case mco of
+ MRefl | isCoreTyLamForAllTyFlag vis
+ -- The lambda we are eta-reducing always has visibility
+ -- 'coreTyLamForAllTyFlag' which may or may not match the
+ -- visibility on the inner function (#24014)
+ -> MRefl
+ | otherwise
+ -> MCo $ mkForAllCo fun_tv vis coreTyLamForAllTyFlag MRefl refl_co
+ MCo co -> MCo $ mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co
+ -- Tricky: `fun_tv` scopes over `body_ty` and hence over `refl_co`
+ -- but: `tv` scopes over `mco` and hence over `co`
+ where
+ refl_co = mkRepReflCo body_ty
{- *********************************************************************
* *
=====================================
compiler/GHC/Core/Opt/OccurAnal.hs
=====================================
@@ -42,7 +42,6 @@ import GHC.Core.Utils ( exprIsTrivial, isDefaultAlt, isExpandableApp,
import GHC.Core.Opt.Arity ( joinRhsArity, isOneShotBndr )
import GHC.Core.Coercion
import GHC.Core.Type
-import GHC.Core.TyCo.FVs ( tyCoVarsOfMCo )
import GHC.Data.Maybe( orElse )
import GHC.Data.Graph.Directed ( SCC(..), Node(..)
=====================================
compiler/GHC/Core/Opt/Simplify/Env.hs
=====================================
@@ -1240,6 +1240,8 @@ out_id so that its arity is visible in its RHS. Examples:
Example: `f = \x. f x`. See Note [Eta reduction in recursive RHSs] for how
we prevent that.
+c.f. (EtaA) in Note [Eta reduction soundness] in GHC.Core.Opt.Arity.
+
Note [Robust OccInfo]
~~~~~~~~~~~~~~~~~~~~~
It's important that we *do* retain the loop-breaker OccInfo, because
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -3143,7 +3143,7 @@ There have been various earlier versions of this patch:
case_bndr_evald_next _ = False
This patch was part of fixing #7542. See also
- Note [Eta reduction soundness], criterion (E) in GHC.Core.Utils.)
+ Note [Eta reduction soundness], criterion (EtaE) in GHC.Core.Opt.Arity.)
Further notes about case elimination
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -2110,8 +2110,9 @@ tryEtaExpandRhs :: SimplEnv -> BindContext -> OutId -> OutExpr
tryEtaExpandRhs env bind_cxt bndr rhs
| seEtaExpand env -- If Eta-expansion is on
, wantEtaExpansion rhs -- and we'd like to eta-expand e
- , do_eta_expand -- and e's manifest arity is lower than
- -- what it could be
+ , do_eta_expand -- and arity analysis finds a greater arity
+ -- than (exprArity e); NB: not manifestArity
+ -- See Note [Do not eta-expand PAPs]
-- (never true for join points)
= -- Do eta-expansion.
assertPpr( not (isJoinBC bind_cxt) ) (ppr bndr) $
@@ -2130,7 +2131,8 @@ tryEtaExpandRhs env bind_cxt bndr rhs
(do_eta_expand, arity_type) = findRhsArity arity_opts is_rec bndr rhs
wantEtaExpansion :: CoreExpr -> Bool
--- Mostly True; but False of PAPs which will immediately eta-reduce again
+-- Mostly True; but False of trivial RHSs, and of PAPs at the top of the RHS
+-- (PAPs under value lambdas are dealt with by findRhsArity)
-- See Note [Which RHSs do we eta-expand?]
wantEtaExpansion (Cast e _) = wantEtaExpansion e
wantEtaExpansion (Tick _ e) = wantEtaExpansion e
@@ -2168,7 +2170,22 @@ seems like a Good idea.
Note [Do not eta-expand PAPs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We used to have old_arity = manifestArity rhs, which meant that we
+We do not eta-expand a RHS that is a partial application (PAP). This
+is achieved in two places:
+
+(DEP1) A PAP at the top of the RHS, such as
+ f = g d -- g has arity 2
+ is rejected by `wantEtaExpansion`.
+
+(DEP2) A PAP under value lambdas, such as
+ f = \x. g x -- g has arity 3
+ is not eta-expanded because `findRhsArity` asks for eta-expansion
+ only if the arity it finds is greater than (exprArity rhs), and
+ `exprArity` takes account of PAPs: here (exprArity rhs) = 3.
+ Using `manifestArity` (which is 1 here) instead would eta-expand
+ to f = \x y z. g x y z.
+
+Up to 2014 we used old_arity = manifestArity rhs, which meant that we
would eta-expand even PAPs. But this gives no particular advantage,
and can lead to a massive blow-up in code size, exhibited by #9020.
Suppose we have a PAP
@@ -2184,6 +2201,17 @@ coercions and whatnot that eventually disappear again. For T9020, GHC
allocated 6.6G before, and 0.8G afterwards; and residency dropped from
1.8G to 45M.
+#27212 tried switching (DEP2) back to manifestArity, with these results:
+
+* T13960: bytestring's
+ cstring1 = \(a::Addr#) @r. cstring2 @r a -- cstring2 has arity 4
+ was eta-expanded to (\a @r k br s. cstring2 @r a k br s). That bigger
+ unfolding is inlined at every string literal, adding 6 terms per
+ literal; compile-time allocation went up by 9%.
+
+* T13056: a derived-instance method (\ @a d. lvl @a), where `lvl` is
+ bottoming, was eta-expanded, and then needlessly worker/wrappered.
+
Moreover, if we eta expand
f = g d ==> f = \x. g d x
that might in turn make g inline (if it has an inline pragma), which
=====================================
compiler/GHC/Core/TyCo/Make.hs
=====================================
@@ -58,7 +58,7 @@ module GHC.Core.TyCo.Make (
, mkAxInstCo
, mkTransCo, mkTransMCo, mkTransMCoL, mkTransMCoR
, mkProofIrrelCo
- , coToMCo, kindCoToMKindCo
+ , coToMCo, kindCoToMKindCo, mCoToCo
, mkCoherenceLeftCo, mkCoherenceRightCo, mkCoherenceRightMCo
, toPhantomCo, mkPhantomCo
, isReflCo, isReflMCo, isReflKindCo, isReflKindMCo, isReflCo_maybe
@@ -860,7 +860,7 @@ mkHomoForAllCos vs orig_co
= foldr go orig_co vs
where
go :: ForAllTyBinder -> Coercion -> Coercion
- go (Bndr var vis) co = mk_forall_co var vis vis MRefl co
+ go (Bndr var vis) co = mkForAllCoNonRefl var vis vis MRefl co
mkHomoForAllCo :: TyVar -> Coercion -> Coercion
-- Specialised for a single TyVar,
@@ -869,7 +869,7 @@ mkHomoForAllCo tv orig_co
| Just (ty, r) <- isReflCo_maybe orig_co
= mkReflCo r (mkForAllTy (Bndr tv vis) ty)
| otherwise
- = mk_forall_co tv vis vis MRefl orig_co
+ = mkForAllCoNonRefl tv vis vis MRefl orig_co
where
vis = coreTyLamForAllTyFlag
@@ -892,15 +892,15 @@ mkForAllCo v visL visR kind_co co
| Just refl_co <- isReflForAllCo v visL visR kind_co co
= refl_co
| otherwise
- = mk_forall_co v visL visR kind_co co
+ = mkForAllCoNonRefl v visL visR kind_co co
--- | `mk_forall_co` just builds a ForAllCo.
+-- | `mkForAllCoNonRefl` just builds a ForAllCo.
-- With debug on, it checks invariants (e.g. he kind of the tycovar should
-- be the left-hand kind of the kind coercion).
-- Callers should have done any isReflCo short-cutting.
-mk_forall_co :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag
- -> KindMCoercion -> Coercion -> Coercion
-mk_forall_co tcv visL visR kind_co co
+mkForAllCoNonRefl :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag
+ -> KindMCoercion -> Coercion -> Coercion
+mkForAllCoNonRefl tcv visL visR kind_co co
= assertGoodForAllCo tcv visL visR kind_co co $
assertPpr (not (isReflCo co && isReflMCo kind_co && visL `eqForAllVis` visR)) (ppr co) $
ForAllCo { fco_tcv = tcv, fco_visL = visL, fco_visR = visR
@@ -1289,6 +1289,10 @@ coToMCo :: Coercion -> MCoercion
coToMCo co | isReflCo co = MRefl
| otherwise = MCo co
+mCoToCo :: Role -> Type -> MCoercion -> Coercion
+mCoToCo role ty MRefl = mkReflCo role ty
+mCoToCo _ _ (MCo co) = co
+
kindCoToMKindCo :: KindCoercion -> KindMCoercion
-- Convert a KindCoercion to a KindMCoercion,
-- coToMCo doesn't eliminate GRefl, but kindCoToMCo can
=====================================
compiler/GHC/Core/Type.hs
=====================================
@@ -160,7 +160,7 @@ module GHC.Core.Type (
-- * Type free variables
tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeDSet,
- coVarsOfType, coVarsOfTypes,
+ tyCoVarsOfMCo, coVarsOfType, coVarsOfTypes,
anyFreeVarsOfType, anyFreeVarsOfTypes,
noFreeVarsOfType,
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -2392,7 +2392,7 @@ canCollectArgsThroughTick id t
= tickishFloatable t || cantEtaReduceFun id
-- | Can we eta-reduce the given function?
--- See Note [Eta reduction soundness], criteria (B), (J), and (W).
+-- See Note [Eta reduction soundness], criteria (EtaB), (EtaJ), and (EtaW).
cantEtaReduceFun :: Id -> Bool
cantEtaReduceFun fun
= hasNoBinding fun -- (B)
=====================================
testsuite/tests/dmdanal/sigs/T21888a.stderr
=====================================
@@ -7,7 +7,7 @@ T21888a.wombat: <S!P(S)>b
==================== Cpr signatures ====================
-T21888a.f: 2
+T21888a.f:
T21888a.g: 1
T21888a.wombat: b
=====================================
testsuite/tests/printer/T18052a.stderr
=====================================
@@ -10,11 +10,11 @@ Dependent packages: [(normal, base-4.23.0.0)]
==================== Tidy Core ====================
Result size of Tidy Core
- = {terms: 24, types: 52, coercions: 0, joins: 0/0}
+ = {terms: 18, types: 46, coercions: 0, joins: 0/0}
--- RHS size: {terms: 7, types: 6, coercions: 0, joins: 0/0}
+-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
T18052a.$b:||: :: forall {a} {b}. a -> b -> (a, b)
-T18052a.$b:||: = \ (@a) (@b) (x :: a) (y :: b) -> (x, y)
+T18052a.$b:||: = GHC.Internal.Tuple.(,)
-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
(+++) :: forall {a}. [a] -> [a] -> [a]
=====================================
testsuite/tests/simplCore/should_compile/T27212.hs
=====================================
@@ -0,0 +1,18 @@
+{-# OPTIONS_GHC -Wno-inaccessible-code -Wno-overlapping-patterns #-}
+module T27212 where
+
+import Unsafe.Coerce
+
+class Given a where given :: a
+newtype Gift a r = Gift (Given a => r)
+
+useIt :: Given Int => Int
+useIt = given + 1
+{-# NOINLINE useIt #-}
+
+foo :: [Int] -> [Int]
+foo xs = case unsafeEqualityProof @(Gift Int Int) @(Int -> Int) of
+ UnsafeRefl -> map (\y -> (Gift useIt :: Gift Int Int) y) xs
+ -- That (\y. glah y) can eta-reduce to `glah`
+ -- but doing so makes a FunCo coercion that crosses from
+ -- Type to constraint. Tricky.
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -631,3 +631,4 @@ test('T27936', normal, compile, [''])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+test('T27212', normal, compile, ['-O'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/cd190880ae1cfe2d45687c14328576b…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/cd190880ae1cfe2d45687c14328576b…
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
1
0