...
 
Commits (8)
  • Adam Sandberg Eriksson's avatar
    docs: fix formatting and add some links · d830bbc9
    Adam Sandberg Eriksson authored
    [skip ci]
    d830bbc9
  • Andrew Martin's avatar
    Implement cstringLength# and FinalPtr · 49301ad6
    Andrew Martin authored
    This function and its accompanying rule resolve issue #5218.
    A future PR to the bytestring library will make the internal
    Data.ByteString.Internal.unsafePackAddress compute string length
    with cstringLength#. This will improve the status quo because it is
    eligible for constant folding.
    
    Additionally, introduce a new data constructor to ForeignPtrContents
    named FinalPtr. This additional data constructor, when used in the
    IsString instance for ByteString, leads to more Core-to-Core
    optimization opportunities, fewer runtime allocations, and smaller
    binaries.
    
    Also, this commit re-exports all the functions from GHC.CString
    (including cstringLength#) in GHC.Exts. It also adds a new test
    driver. This test driver is used to perform substring matches on Core
    that is dumped after all the simplifier passes. In this commit, it is
    used to check that constant folding of cstringLength# works.
    49301ad6
  • Ben Gamari's avatar
    simplCore: Ignore ticks in rule templates · dcd6bdcc
    Ben Gamari authored
    This fixes #17619, where a tick snuck in to the template of a rule,
    resulting in a panic during rule matching. The tick in question was
    introduced via post-inlining, as discussed in `Note [Simplifying
    rules]`. The solution we decided upon was to simply ignore ticks in the
    rule template, as discussed in `Note [Tick annotations in RULE
    matching]`.
    
    Fixes #18162.
    Fixes #17619.
    dcd6bdcc
  • John Ericson's avatar
    Fix #18145 and also avoid needless work with implicit vars · 82cb8913
    John Ericson authored
     - `forAllOrNothing` now is monadic, so we can trace whether we bind
       an explicit `forall` or not.
    
     - #18145 arose because the free vars calculation was needlessly
       complex. It is now greatly simplified.
    
     - Replaced some other implicit var code with `filterFreeVarsToBind`.
    Co-authored-by: Ryan Scott's avatarRyan Scott <ryan.gl.scott@gmail.com>
    82cb8913
  • Ben Gamari's avatar
    Bump process submodule · a60dc835
    Ben Gamari authored
    Fixes #17926.
    a60dc835
  • Ben Gamari's avatar
    users-guide: Clarify meaning of -haddock flag · 856adf54
    Ben Gamari authored
    Fixes #18206.
    856adf54
  • Ben Gamari's avatar
    git: Add ignored commits file · 7ae57afd
    Ben Gamari authored
    This can be used to tell git to ignore bulk renaming commits like the
    recently-finished module hierarchy refactoring. Configured with,
    
        git config blame.ignoreRevsFile .git-ignore-revs
    7ae57afd
  • Ryan Scott's avatar
    Make GADT constructors adhere to the forall-or-nothing rule properly · 0d541790
    Ryan Scott authored
    Issue #18191 revealed that the types of GADT constructors don't quite
    adhere to the `forall`-or-nothing rule. This patch serves to clean up
    this sad state of affairs somewhat. The main change is not in the
    code itself, but in the documentation, as this patch introduces two
    sections to the GHC User's Guide:
    
    * A "Formal syntax for GADTs" section that presents a BNF-style
      grammar for what is and isn't allowed in GADT constructor types.
      This mostly exists to codify GHC's existing behavior, but it also
      imposes a new restriction that addresses #18191: the outermost
      `forall` and/or context in a GADT constructor is not allowed to be
      surrounded by parentheses. Doing so would make these
      `forall`s/contexts nested, and GADTs do not support nested
      `forall`s/contexts at present.
    
    * A "`forall`-or-nothing rule" section that describes exactly what
      the `forall`-or-nothing rule is all about. Surprisingly, there was
      no mention of this anywhere in the User's Guide up until now!
    
    To adhere the new specification in the "Formal syntax for GADTs"
    section of the User's Guide, the following code changes were made:
    
    * `GHC.Parser.PostProcess.mkGadtDecl` no longer strips away
      parentheses from the outermost `forall` and context. Instead, these
      parentheses are preserved so that the renamer can check for nested
      `forall`s/contexts later. See
      `Note [No nested foralls or contexts in GADT constructors]` in
      `GHC.Parser.PostProcess` for more details.
    
      One nice side effect of this change is that we can get rid of the
      explicit `AddAnn` tracking in `mkGadtDecl`, as we no longer need to
      remember the `AddAnn`s for stripped-away parentheses.
    
    * `GHC.Renamer.Module.rnConDecl` now checks for nested
      `forall`s/contexts, rather than checking for this in the typechcker
      (in `GHC.Tc.TyCl.badDataConTyCon`). For the most part, this code
      was ported directly from `badDataConTyCon`, but designed to work
      over `HsType`s instead of `Type`s.
    
      One nice side effect of this change is that we are able to give a
      more accurate error message for GADT constructors that use visible
      dependent quantification (e.g., `MkFoo :: forall a -> a -> Foo a`),
      which improves the stderr in the `T16326_Fail6` test case.
    
    Fixes #18191.
    0d541790
# Configure git to ignore commits listed in this file with:
#
# git config blame.ignoreRevsFile .git-ignore-revs
# Module Hierarchy Renamings
af332442123878c1b61d236dce46418efcbe8750
255418da5d264fb2758bc70925adb2094f34adc3
1941ef4f050c0dfcb68229641fcbbde3a10f1072
528df8ecb4e2f9c78b1ae4ab7ff8230644e9b643
18a346a4b5a02b8c62e8eedb91b35c2d8e754b96
817f93eac4d13f680e8e3e7a25eb403b1864f82e
1b1067d14b656bbbfa7c47f156ec2700c9751549
240f5bf6f53515535be5bf3ef7632aa69ae21e3e
1500f0898e85316c7c97a2f759d83278a072ab0e
3ca52151881451ce5b3a7740d003e811b586140d
cf739945b8b28ff463dc44925348f20b3c1f22cb
da7f74797e8c322006eba385c9cbdce346dd1d43
6e2d9ee25bce06ae51d2f1cf8df4f7422106a383
d491a6795d507eabe35d8aec63c534d29f2d305b
99a9f51bf8207c79241fc0b685fadeb222a61292
eb6082358cdb5f271a8e4c74044a12f97352c52f
5119296440e6846c553c72b8a93afc5ecfa576f0
447864a94a1679b5b079e08bb7208a0005381cef
......@@ -349,6 +349,7 @@ basicKnownKeyNames
-- Strings and lists
unpackCStringName,
unpackCStringFoldrName, unpackCStringUtf8Name,
cstringLengthName,
-- Overloaded lists
isListClassName,
......@@ -1014,10 +1015,11 @@ modIntName = varQual gHC_CLASSES (fsLit "modInt#") modIntIdKey
-- Base strings Strings
unpackCStringName, unpackCStringFoldrName,
unpackCStringUtf8Name, eqStringName :: Name
unpackCStringUtf8Name, eqStringName, cstringLengthName :: Name
unpackCStringName = varQual gHC_CSTRING (fsLit "unpackCString#") unpackCStringIdKey
unpackCStringFoldrName = varQual gHC_CSTRING (fsLit "unpackFoldrCString#") unpackCStringFoldrIdKey
unpackCStringUtf8Name = varQual gHC_CSTRING (fsLit "unpackCStringUtf8#") unpackCStringUtf8IdKey
cstringLengthName = varQual gHC_CSTRING (fsLit "cstringLength#") cstringLengthIdKey
eqStringName = varQual gHC_BASE (fsLit "eqString") eqStringIdKey
-- The 'inline' function
......@@ -2097,7 +2099,7 @@ wildCardKey, absentErrorIdKey, augmentIdKey, appendIdKey,
unpackCStringUtf8IdKey, unpackCStringAppendIdKey,
unpackCStringFoldrIdKey, unpackCStringIdKey,
typeErrorIdKey, divIntIdKey, modIntIdKey,
absentSumFieldErrorIdKey :: Unique
absentSumFieldErrorIdKey, cstringLengthIdKey :: Unique
wildCardKey = mkPreludeMiscIdUnique 0 -- See Note [WildCard binders]
absentErrorIdKey = mkPreludeMiscIdUnique 1
......@@ -2124,6 +2126,7 @@ voidPrimIdKey = mkPreludeMiscIdUnique 21
typeErrorIdKey = mkPreludeMiscIdUnique 22
divIntIdKey = mkPreludeMiscIdUnique 23
modIntIdKey = mkPreludeMiscIdUnique 24
cstringLengthIdKey = mkPreludeMiscIdUnique 25
concatIdKey, filterIdKey, zipIdKey,
bindIOIdKey, returnIOIdKey, newStablePtrIdKey,
......
......@@ -66,6 +66,7 @@ import qualified Data.ByteString as BS
import Data.Int
import Data.Ratio
import Data.Word
import Data.Maybe (fromMaybe)
{-
Note [Constant folding]
......@@ -1257,6 +1258,8 @@ builtinRules
ru_nargs = 4, ru_try = match_append_lit },
BuiltinRule { ru_name = fsLit "EqString", ru_fn = eqStringName,
ru_nargs = 2, ru_try = match_eq_string },
BuiltinRule { ru_name = fsLit "CStringLength", ru_fn = cstringLengthName,
ru_nargs = 1, ru_try = match_cstring_length },
BuiltinRule { ru_name = fsLit "Inline", ru_fn = inlineIdName,
ru_nargs = 2, ru_try = \_ _ _ -> match_inline },
BuiltinRule { ru_name = fsLit "MagicDict", ru_fn = idName magicDictId,
......@@ -1477,6 +1480,30 @@ match_eq_string _ id_unf _
match_eq_string _ _ _ _ = Nothing
-----------------------------------------------------------------------
-- Illustration of this rule:
--
-- cstringLength# "foobar"# --> 6
-- cstringLength# "fizz\NULzz"# --> 4
--
-- Nota bene: Addr# literals are suffixed by a NUL byte when they are
-- compiled to read-only data sections. That's why cstringLength# is
-- well defined on Addr# literals that do not explicitly have an embedded
-- NUL byte.
--
-- See GHC issue #5218, MR 2165, and bytestring PR 191. This is particularly
-- helpful when using OverloadedStrings to create a ByteString since the
-- function computing the length of such ByteStrings can often be constant
-- folded.
match_cstring_length :: RuleFun
match_cstring_length env id_unf _ [lit1]
| Just (LitString str) <- exprIsLiteral_maybe id_unf lit1
-- If elemIndex returns Just, it has the index of the first embedded NUL
-- in the string. If no NUL bytes are present (the common case) then use
-- full length of the byte string.
= let len = fromMaybe (BS.length str) (BS.elemIndex 0 str)
in Just (Lit (mkLitInt (roPlatform env) (fromIntegral len)))
match_cstring_length _ _ _ _ = Nothing
---------------------------------------------------
-- The rule is this:
......
......@@ -830,6 +830,21 @@ Ticks into the LHS, which makes matching trickier. #10665, #10745.
Doing this to either side confounds tools like HERMIT, which seek to reason
about and apply the RULES as originally written. See #10829.
There is, however, one case where we are pretty much /forced/ to transform the
LHS of a rule: postInlineUnconditionally. For instance, in the case of
let f = g @Int in f
We very much want to inline f into the body of the let. However, to do so (and
be able to safely drop f's binding) we must inline into all occurrences of f,
including those in the LHS of rules.
This can cause somewhat surprising results; for instance, in #18162 we found
that a rule template contained ticks in its arguments, because
postInlineUnconditionally substituted in a trivial expression that contains
ticks. See Note [Tick annotations in RULE matching] in GHC.Core.Rules for
details.
Note [No eta expansion in stable unfoldings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have a stable unfolding
......@@ -1251,6 +1266,10 @@ it's best to inline it anyway. We often get a=E; b=a from desugaring,
with both a and b marked NOINLINE. But that seems incompatible with
our new view that inlining is like a RULE, so I'm sticking to the 'active'
story for now.
NB: unconditional inlining of this sort can introduce ticks in places that
may seem surprising; for instance, the LHS of rules. See Note [Simplfying
rules] for details.
-}
postInlineUnconditionally
......
......@@ -714,11 +714,15 @@ match :: RuleMatchEnv
-> CoreExpr -- Target
-> Maybe RuleSubst
-- We look through certain ticks. See note [Tick annotations in RULE matching]
-- We look through certain ticks. See Note [Tick annotations in RULE matching]
match renv subst e1 (Tick t e2)
| tickishFloatable t
= match renv subst' e1 e2
where subst' = subst { rs_binds = rs_binds subst . mkTick t }
match renv subst (Tick t e1) e2
-- Ignore ticks in rule template.
| tickishFloatable t
= match renv subst e1 e2
match _ _ e@Tick{} _
= pprPanic "Tick in rule" (ppr e)
......@@ -1016,7 +1020,7 @@ Hence, (a) the guard (not (isLocallyBoundR v2))
Note [Tick annotations in RULE matching]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We used to unconditionally look through Notes in both template and
We used to unconditionally look through ticks in both template and
expression being matched. This is actually illegal for counting or
cost-centre-scoped ticks, because we have no place to put them without
changing entry counts and/or costs. So now we just fail the match in
......@@ -1025,6 +1029,11 @@ these cases.
On the other hand, where we are allowed to insert new cost into the
tick scope, we can float them upwards to the rule application site.
Moreover, we may encounter ticks in the template of a rule. There are a few
ways in which these may be introduced (e.g. #18162, #17619). Such ticks are
ignored by the matcher. See Note [Simplifying rules] in
GHC.Core.Opt.Simplify.Utils for details.
cf Note [Notes in call patterns] in GHC.Core.Opt.SpecConstr
Note [Matching lets]
......
......@@ -128,8 +128,9 @@ import Foreign
import GHC.Conc.Sync (sharedCAF)
#endif
import GHC.Base ( unpackCString#, unpackNBytes# )
#if __GLASGOW_HASKELL__ < 811
import GHC.Base (unpackCString#,unpackNBytes#)
#endif
-- | Gives the UTF-8 encoded bytes corresponding to a 'FastString'
bytesFS :: FastString -> ByteString
......
......@@ -53,7 +53,7 @@ data HsLit x
-- ^ Unboxed character
| HsString (XHsString x) {- SourceText -} FastString
-- ^ String
| HsStringPrim (XHsStringPrim x) {- SourceText -} ByteString
| HsStringPrim (XHsStringPrim x) {- SourceText -} !ByteString
-- ^ Packed bytes
| HsInt (XHsInt x) IntegralLit
-- ^ Genuinely an Int; arises from
......
......@@ -58,8 +58,9 @@ module GHC.Hs.Types (
hsLTyVarName, hsLTyVarNames, hsLTyVarLocName, hsExplicitLTyVarNames,
splitLHsInstDeclTy, getLHsInstDeclHead, getLHsInstDeclClass_maybe,
splitLHsPatSynTy,
splitLHsForAllTyInvis, splitLHsQualTy, splitLHsSigmaTyInvis,
splitHsFunType, hsTyGetAppHead_maybe,
splitLHsForAllTyInvis, splitLHsQualTy,
splitLHsSigmaTyInvis, splitNestedLHsSigmaTysInvis,
splitLHsFunTys, hsTyGetAppHead_maybe,
mkHsOpTy, mkHsAppTy, mkHsAppTys, mkHsAppKindTy,
ignoreParens, hsSigType, hsSigWcType, hsPatSigType,
hsTyKindSig,
......@@ -1242,18 +1243,44 @@ mkHsAppKindTy ext ty k
-}
---------------------------------
-- splitHsFunType decomposes a type (t1 -> t2 ... -> tn)
-- Breaks up any parens in the result type:
-- splitHsFunType (a -> (b -> c)) = ([a,b], c)
splitHsFunType :: LHsType GhcRn -> ([LHsType GhcRn], LHsType GhcRn)
splitHsFunType (L _ (HsParTy _ ty))
= splitHsFunType ty
splitHsFunType (L _ (HsFunTy _ x y))
| (args, res) <- splitHsFunType y
-- | 'splitLHsFunTys' decomposes a type @t1 -> t2 ... -> tn@ into the argument
-- and result types. For example:
--
-- @
-- 'splitLHsFunTys' (a -> b -> c) = ([a,b], c)
-- @
--
-- Note that this function looks through parentheses, so it will work on types
-- such as @(a -> (b -> c))@. The downside to this is that it is not
-- generally possible to take the returned types and reconstruct the original
-- type (parentheses and all) from them.
splitLHsFunTys :: LHsType GhcRn -> ([LHsType GhcRn], LHsType GhcRn)
splitLHsFunTys (L _ (HsParTy _ ty))
= splitLHsFunTys ty
splitLHsFunTys (L _ (HsFunTy _ x y))
| (args, res) <- splitLHsFunTys y
= (x:args, res)
splitHsFunType other = ([], other)
splitLHsFunTys other = ([], other)
-- | Returns 'Just (arg_ty, res_ty)@ if the supplied type is an 'HsFunTy',
-- where @arg_ty@ and @res_ty@ are the decomposed argument and result types,
-- respectively. Returns 'Nothing' otherwise. For example:
--
-- @
-- 'splitLHsFunTy_maybe' (a -> b) = 'Just' (a, b)
-- 'splitLHsFunTy_maybe' [a] = 'Nothing'
-- @
--
-- Note that this function looks through parentheses, so it will work on types
-- such as @((a -> b))@. The downside to this is that it is not
-- generally possible to take the returned types and reconstruct the original
-- type (parentheses and all) from them.
splitLHsFunTy_maybe :: LHsType pass -> Maybe (LHsType pass, LHsType pass)
splitLHsFunTy_maybe (L _ (HsParTy _ ty)) = splitLHsFunTy_maybe ty
splitLHsFunTy_maybe (L _ (HsFunTy _ x y)) = Just (x, y)
splitLHsFunTy_maybe _ = Nothing
-- retrieve the name of the "head" of a nested type application
-- somewhat like splitHsAppTys, but a little more thorough
......@@ -1347,6 +1374,69 @@ splitLHsSigmaTyInvis ty
, (ctxt, ty2) <- splitLHsQualTy ty1
= (tvs, ctxt, ty2)
-- | Decompose a type's @forall@s and contexts from its body, possibly looking
-- underneath 'HsFunTy's in the process. For example:
--
-- @
-- 'splitNestedLHsSigmaTysInvis' (forall a. a -> Show a => forall b. b -> a)
-- = ([a, b], [Show a], [a -> b -> a])
-- @
--
-- Note that this function looks through parentheses, so it will work on types
-- such as @(forall a. <...>)@. The downside to this is that it is not
-- generally possible to take the returned types and reconstruct the original
-- type (parentheses and all) from them.
splitNestedLHsSigmaTysInvis ::
LHsType (GhcPass p)
-> ( [LHsTyVarBndr Specificity (GhcPass p)]
, LHsContext (GhcPass p), LHsType (GhcPass p) )
splitNestedLHsSigmaTysInvis ty
-- If there's a forall, split it apart and try splitting the rho type
-- underneath it.
| Just (arg_tys, tvs1, theta1, rho1) <- deepSplitLHsSigmaTyInvis_maybe ty
= let (tvs2, theta2, rho2) = splitNestedLHsSigmaTysInvis rho1
in ( tvs1 ++ tvs2
, append_lhs_contexts theta1 theta2
, foldr mk_lhs_fun_ty rho2 arg_tys )
-- If there's no forall, we're done.
| otherwise = ([], noLHsContext, ty)
where
append_lhs_contexts :: LHsContext (GhcPass p) -> LHsContext (GhcPass p)
-> LHsContext (GhcPass p)
append_lhs_contexts (L _ ctxt1) (L _ ctxt2) = noLoc $ ctxt1 ++ ctxt2
mk_lhs_fun_ty :: LHsType (GhcPass p) -> LHsType (GhcPass p)
-> LHsType (GhcPass p)
mk_lhs_fun_ty arg_ty res_ty = noLoc $ HsFunTy noExtField arg_ty res_ty
-- | Helper function for 'deepSplitLHsSigmaTyInvis_maybe' that decomposes a
-- function type's arguments, followed by any @forall@s and contexts that
-- appear after the last function arrow. For example:
--
-- @
-- 'deepSplitLHsSigmaTyInvis_maybe' (Int -> Char -> forall a. Show a => a -> b)
-- = ([Int, Char], [a], [Show a], [a -> b])
-- @
--
-- Note that this function looks through parentheses, so it will work on types
-- such as @(forall a. <...>)@. The downside to this is that it is not
-- generally possible to take the returned types and reconstruct the original
-- type (parentheses and all) from them.
deepSplitLHsSigmaTyInvis_maybe ::
LHsType pass
-> Maybe ( [LHsType pass], [LHsTyVarBndr Specificity pass]
, LHsContext pass, LHsType pass )
deepSplitLHsSigmaTyInvis_maybe ty
| Just (arg_ty, res_ty) <- splitLHsFunTy_maybe ty
, Just (arg_tys, tvs, theta, rho) <- deepSplitLHsSigmaTyInvis_maybe res_ty
= Just (arg_ty:arg_tys, tvs, theta, rho)
| (tvs, theta, rho) <- splitLHsSigmaTyInvis ty
, not (null tvs && null (unLoc theta))
= Just ([], tvs, theta, rho)
| otherwise = Nothing
-- | Decompose a type of the form @forall <tvs>. body@ into its constituent
-- parts. Only splits type variable binders that
-- were quantified invisibly (e.g., @forall a.@, with a dot).
......
......@@ -2248,9 +2248,8 @@ gadt_constr :: { LConDecl GhcPs }
-- see Note [Difference in parsing GADT and data constructors]
-- Returns a list because of: C,D :: ty
: con_list '::' sigtypedoc
{% let (gadt,anns) = mkGadtDecl (unLoc $1) $3
in ams (sLL $1 $> gadt)
(mu AnnDcolon $2:anns) }
{% ams (sLL $1 $> (mkGadtDecl (unLoc $1) $3))
[mu AnnDcolon $2] }
{- Note [Difference in parsing GADT and data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
......
......@@ -685,30 +685,41 @@ mkConDeclH98 name mb_forall mb_cxt args
, con_args = args
, con_doc = Nothing }
-- Construct a GADT-style data constructor from the constructor names and their
-- type. Does not perform any validity checking, as that it done later in
-- GHC.Rename.Module.rnConDecl.
mkGadtDecl :: [Located RdrName]
-> LHsType GhcPs -- Always a HsForAllTy
-> (ConDecl GhcPs, [AddAnn])
-> ConDecl GhcPs
mkGadtDecl names ty
= (ConDeclGADT { con_g_ext = noExtField
, con_names = names
, con_forall = L l $ isLHsForAllTy ty'
, con_qvars = tvs
, con_mb_cxt = mcxt
, con_args = args
, con_res_ty = res_ty
, con_doc = Nothing }
, anns1 ++ anns2)
= ConDeclGADT { con_g_ext = noExtField
, con_names = names
, con_forall = L (getLoc ty) $ isJust mtvs
, con_qvars = fromMaybe [] mtvs
, con_mb_cxt = mcxt
, con_args = args
, con_res_ty = res_ty
, con_doc = Nothing }
where
(ty'@(L l _),anns1) = peel_parens ty []
(tvs, rho) = splitLHsForAllTyInvis ty'
(mcxt, tau, anns2) = split_rho rho []
split_rho (L _ (HsQualTy { hst_ctxt = cxt, hst_body = tau })) ann
= (Just cxt, tau, ann)
split_rho (L l (HsParTy _ ty)) ann
= split_rho ty (ann++mkParensApiAnn l)
split_rho tau ann
= (Nothing, tau, ann)
(mtvs, rho) = split_sigma ty
(mcxt, tau) = split_rho rho
-- NB: We do not use splitLHsForAllTyInvis below, since that looks through
-- parentheses...
split_sigma (L _ (HsForAllTy { hst_fvf = ForallInvis, hst_bndrs = bndrs
, hst_body = rho }))
= (Just bndrs, rho)
split_sigma sigma
= (Nothing, sigma)
-- ...similarly, we do not use splitLHsQualTy below, since that also looks
-- through parentheses.
-- See Note [No nested foralls or contexts in GADT constructors] for why
-- this is important.
split_rho (L _ (HsQualTy { hst_ctxt = cxt, hst_body = tau }))
= (Just cxt, tau)
split_rho tau
= (Nothing, tau)
(args, res_ty) = split_tau tau
......@@ -718,10 +729,43 @@ mkGadtDecl names ty
split_tau tau
= (PrefixCon [], tau)
peel_parens (L l (HsParTy _ ty)) ann = peel_parens ty
(ann++mkParensApiAnn l)
peel_parens ty ann = (ty, ann)
{-
Note [No nested foralls or contexts in GADT constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GADT constructors provide some freedom to change the order of foralls in their
types (see Note [DataCon user type variable binders] in GHC.Core.DataCon), but
this freedom is still limited. GADTs still require that all quantification
occurs prenex. That is, any explicitly quantified type variables must occur at
the front of the GADT type, followed by any contexts, followed by the body of
the GADT type, in precisely that order. For instance:
data T where
MkT1 :: forall a b. (Eq a, Eq b) => a -> b -> T
-- OK
MkT2 :: forall a. Eq a => forall b. a -> b -> T
-- Rejected, `forall b` is nested
MkT3 :: forall a b. Eq a => Eq b => a -> b -> T
-- Rejected, `Eq b` is nested
MkT4 :: Int -> forall a. a -> T
-- Rejected, `forall a` is nested
MkT5 :: forall a. Int -> Eq a => a -> T
-- Rejected, `Eq a` is nested
MkT6 :: (forall a. a -> T)
-- Rejected, `forall a` is nested due to the surrounding parentheses
MkT7 :: (Eq a => a -> t)
-- Rejected, `Eq a` is nested due to the surrounding parentheses
For the full details, see the "Formal syntax for GADTs" section of the GHC
User's Guide.
Because the presence of outermost parentheses can affect whether
`forall`s/contexts are nested, the parser is careful not to remove parentheses
when post-processing GADT constructors (in mkGadtDecl). Later, the renamer will
check for nested `forall`s/contexts (in GHC.Rename.Module.rnConDecl) after
it has determined what all of the argument types are.
(See Note [GADT abstract syntax] in GHC.Hs.Decls for why this check must wait
until the renamer.)
-}
setRdrNameSpace :: RdrName -> NameSpace -> RdrName
-- ^ This rather gruesome function is used mainly by the parser.
......
This diff is collapsed.
This diff is collapsed.
......@@ -4720,50 +4720,12 @@ noClassTyVarErr clas fam_tc
badDataConTyCon :: DataCon -> Type -> SDoc
badDataConTyCon data_con res_ty_tmpl
| ASSERT( all isTyVar tvs )
tcIsForAllTy actual_res_ty
= nested_foralls_contexts_suggestion
| isJust (tcSplitPredFunTy_maybe actual_res_ty)
= nested_foralls_contexts_suggestion
| otherwise
= hang (text "Data constructor" <+> quotes (ppr data_con) <+>
text "returns type" <+> quotes (ppr actual_res_ty))
2 (text "instead of an instance of its parent type" <+> quotes (ppr res_ty_tmpl))
where
actual_res_ty = dataConOrigResTy data_con
-- This suggestion is useful for suggesting how to correct code like what
-- was reported in #12087:
--
-- data F a where
-- MkF :: Ord a => Eq a => a -> F a
--
-- Although nested foralls or contexts are allowed in function type
-- signatures, it is much more difficult to engineer GADT constructor type
-- signatures to allow something similar, so we error in the latter case.
-- Nevertheless, we can at least suggest how a user might reshuffle their
-- exotic GADT constructor type signature so that GHC will accept.
nested_foralls_contexts_suggestion =
text "GADT constructor type signature cannot contain nested"
<+> quotes forAllLit <> text "s or contexts"
$+$ hang (text "Suggestion: instead use this type signature:")
2 (ppr (dataConName data_con) <+> dcolon <+> ppr suggested_ty)
-- To construct a type that GHC would accept (suggested_ty), we:
--
-- 1) Find the existentially quantified type variables and the class
-- predicates from the datacon. (NB: We don't need the universally
-- quantified type variables, since rejigConRes won't substitute them in
-- the result type if it fails, as in this scenario.)
-- 2) Split apart the return type (which is headed by a forall or a
-- context) using tcSplitNestedSigmaTys, collecting the type variables
-- and class predicates we find, as well as the rho type lurking
-- underneath the nested foralls and contexts.
-- 3) Smash together the type variables and class predicates from 1) and
-- 2), and prepend them to the rho type from 2).
(tvs, theta, rho) = tcSplitNestedSigmaTys (dataConUserType data_con)
suggested_ty = mkSpecSigmaTy tvs theta rho
badGadtDecl :: Name -> SDoc
badGadtDecl tc_name
= vcat [ text "Illegal generalised algebraic data declaration for" <+> quotes (ppr tc_name)
......
......@@ -6,6 +6,7 @@
This module converts Template Haskell syntax into Hs syntax
-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
......@@ -618,7 +619,7 @@ cvtConstr (GadtC c strtys ty)
; args <- mapM cvt_arg strtys
; L _ ty' <- cvtType ty
; c_ty <- mk_arr_apps args ty'
; returnL $ fst $ mkGadtDecl c' c_ty}
; returnL $ mkGadtDecl c' c_ty}
cvtConstr (RecGadtC [] _varstrtys _ty)
= failWith (text "RecGadtC must have at least one constructor name")
......@@ -629,7 +630,7 @@ cvtConstr (RecGadtC c varstrtys ty)
; rec_flds <- mapM cvt_id_arg varstrtys
; let rec_ty = noLoc (HsFunTy noExtField
(noLoc $ HsRecTy noExtField rec_flds) ty')
; returnL $ fst $ mkGadtDecl c' rec_ty }
; returnL $ mkGadtDecl c' rec_ty }
cvtSrcUnpackedness :: TH.SourceUnpackedness -> SrcUnpackedness
cvtSrcUnpackedness NoSourceUnpackedness = NoSrcUnpack
......@@ -1232,8 +1233,7 @@ cvtLit (CharPrimL c) = do { force c; return $ HsCharPrim NoSourceText c }
cvtLit (StringL s) = do { let { s' = mkFastString s }
; force s'
; return $ HsString (quotedSourceText s) s' }
cvtLit (StringPrimL s) = do { let { s' = BS.pack s }
; force s'
cvtLit (StringPrimL s) = do { let { !s' = BS.pack s }
; return $ HsStringPrim NoSourceText s' }
cvtLit (BytesPrimL (Bytes fptr off sz)) = do
let bs = unsafePerformIO $ withForeignPtr fptr $ \ptr ->
......
......@@ -114,7 +114,7 @@ data Literal
-- See Note [Types of LitNumbers] below for the
-- Type field.
| LitString ByteString -- ^ A string-literal: stored and emitted
| LitString !ByteString -- ^ A string-literal: stored and emitted
-- UTF-8 encoded, we'll arrange to decode it
-- at runtime. Also emitted with a @\'\\0\'@
-- terminator. Create with 'mkLitString'
......
......@@ -79,12 +79,15 @@ Language
* GHC now consistently does eager instantiation during type inference.
As a consequence, visible type application (VTA) now only works when
the head of the application is:
* A variable
* An expression with a type signature
For example `(let x = blah in id) @Bool True` no longer typechecks.
You should write `let x = blah in id @Bool True` instead.
This change prepares the way for Quick Look impredicativity.
For example ``(let x = blah in id) @Bool True`` no longer typechecks.
You should write ``let x = blah in id @Bool True`` instead.
This change prepares the way for `Quick Look impredicativity
<https://gitlab.haskell.org/ghc/ghc/issues/18126>`_.
* GHC now allows users to manually define the specificity of type variable
binders. By marking a variable with braces ``{tyvar}`` or ``{tyvar :: kind}``,
......@@ -92,7 +95,28 @@ Language
effectively allows users to choose which variables can or can't be
instantiated through visible type application. More information can be found
here: :ref:`Manually-defining-inferred-variables`.
* GADT constructor types now properly adhere to :ref:`forall-or-nothing`. As
a result, GHC will now reject some GADT constructors that previous versions
of GHC would accept, such as the following: ::
data T where
MkT1 :: (forall a. a -> b -> T)
MkT2 :: (forall a. a -> T)
``MkT1`` and ``MkT2`` are rejected because the lack of an outermost
``forall`` triggers implicit quantification, making the explicit ``forall``s
nested. Furthermore, GADT constructors do not permit the use of nested
``forall``s, as explained in :ref:`formal-gadt-syntax`.
In addition to rejecting nested ``forall``s, GHC is now more stringent about
rejecting uses of nested *contexts* in GADT constructors. For example, the
following example, which previous versions of GHC would accept, is now
rejected:
data U a where
MkU :: (Show a => U a)
Compiler
~~~~~~~~
......@@ -110,60 +134,65 @@ Runtime system
Template Haskell
~~~~~~~~~~~~~~~~
- Implement the Overloaded Quotations proposal (#246). The type of all quotation
forms have now been generalised in terms of a minimal interface necessary for the
implementation rather than the overapproximation of the ``Q`` monad.
- Implement the `Overloaded Quotations proposal (#246) <https://github.com/ghc-proposals/ghc-proposals/blob/master/proposals/0246-overloaded-bracket.rst>`_.
The type of all quotation forms have now been generalised in terms of a
minimal interface necessary (the ``Quote`` type class) for the
implementation rather than the overapproximation of the ``Q`` monad.
- Template Haskell quotes now handle fixity declarations in ``let`` and
``where`` bindings properly. Previously, such fixity declarations would
be dropped when quoted due to a Template Haskell bug.
- Template Haskell quotes now handle fixity declarations in ``let`` and
``where`` bindings properly. Previously, such fixity declarations would
be dropped when quoted due to a Template Haskell bug.
- The ``-XTemplateHaskellQuotes`` extension now allows nested splices as nested
splices do not lead directly to compile-time evaluation. (!2288)
- The ``-XTemplateHaskellQuotes`` extension now allows nested splices as nested
splices do not lead directly to compile-time evaluation. (Merge request
`!2288 <https://gitlab.haskell.org/ghc/ghc/-/merge_requests/2288>`_)
Arrow notation
~~~~~~~~~~~~~~
- When combined with :extension:`Arrows`, the :extension:`LambdaCase` extension
now additionally allows ``\case`` syntax to be used as a command in ``proc``
notation.
- When combined with :extension:`Arrows`, the :extension:`LambdaCase` extension
now additionally allows ``\case`` syntax to be used as a command in ``proc``
notation.
- When combined with :extension:`Arrows`, the effects of the
:extension:`BlockArguments` extension now also apply to applications of
arrow control operators in ``(|`` banana brackets ``|)``: ::
- When combined with :extension:`Arrows`, the effects of the
:extension:`BlockArguments` extension now also apply to applications of
arrow control operators in ``(|`` banana brackets ``|)``: ::
(| untilA (increment -< x + y) do
within 0.5 -< x
... |)
(| untilA (increment -< x + y) do
within 0.5 -< x
... |)
``ghc-prim`` library
~~~~~~~~~~~~~~~~~~~~
- Add a known-key ``cstringLength#`` to ``GHC.CString`` that is eligible
for constant folding by a built-in rule.
``ghc`` library
~~~~~~~~~~~~~~~
- The type of the ``getAnnotations`` function has changed to better reflect
the fact that it returns two different kinds of annotations, those on
names and those on modules: ::
- The type of the ``getAnnotations`` function has changed to better reflect
the fact that it returns two different kinds of annotations, those on
names and those on modules: ::
getAnnotations :: Typeable a
=> ([Word8] -> a) -> ModGuts
-> CoreM (ModuleEnv [a], NameEnv [a])
getAnnotations :: Typeable a
=> ([Word8] -> a) -> ModGuts
-> CoreM (ModuleEnv [a], NameEnv [a])
- The meaning of the ``hs_fixds`` field of ``HsGroup`` has changed slightly.
It now only contains fixity signatures defined for top-level declarations
and class methods defined *outside* of the class itself. Previously,
``hs_fixds`` would also contain fixity signatures for class methods defined
*inside* the class, such as the fixity signature for ``m`` in the following
example: ::
- The meaning of the ``hs_fixds`` field of ``HsGroup`` has changed slightly.
It now only contains fixity signatures defined for top-level declarations
and class methods defined *outside* of the class itself. Previously,
``hs_fixds`` would also contain fixity signatures for class methods defined
*inside* the class, such as the fixity signature for ``m`` in the following
example: ::
class C a where
infixl 4 `m`
m :: a -> a -> a
class C a where
infixl 4 `m`
m :: a -> a -> a
If you wish to attain the previous behavior of ``hs_fixds``, use the new
``hsGroupTopLevelFixitySigs`` function, which collects all top-level fixity
signatures, including those for class methods defined inside classes.
If you wish to attain the previous behavior of ``hs_fixds``, use the new
``hsGroupTopLevelFixitySigs`` function, which collects all top-level fixity
signatures, including those for class methods defined inside classes.
- The ``Exception`` module was boiled down acknowledging the existence of
the ``exceptions`` dependency. In particular, the ``ExceptionMonad``
......@@ -176,6 +205,15 @@ Arrow notation
``base`` library
~~~~~~~~~~~~~~~~
- ``ForeignPtrContents`` has a new nullary data constructor ``FinalPtr``.
``FinalPtr`` is intended for turning a primitive string literal into a
``ForeignPtr``. Unlike ``PlainForeignPtr``, ``FinalPtr`` does not have
a finalizer. Replacing ``PlainForeignPtr`` that has ``NoFinalizers`` with
``FinalPtr`` reduces allocations, reduces the size of compiled binaries,
and unlocks important Core-to-Core optimizations. ``FinalPtr`` will be used
in an upcoming ``bytestring`` release to improve the performance of
``ByteString`` literals created with ``OverloadedStrings``.
Build system
~~~~~~~~~~~~
......@@ -196,7 +234,7 @@ for further change information.
libraries/containers/containers/containers.cabal: Dependency of ``ghc`` library
libraries/deepseq/deepseq.cabal: Dependency of ``ghc`` library
libraries/directory/directory.cabal: Dependency of ``ghc`` library
libraries/exceptions/exceptions.cabal: Dependency of ``haskeline`` library
libraries/exceptions/exceptions.cabal: Dependency of ``ghc`` and ``haskeline`` library
libraries/filepath/filepath.cabal: Dependency of ``ghc`` library
compiler/ghc.cabal: The compiler itself
libraries/ghci/ghci.cabal: The REPL interface
......
......@@ -45,4 +45,81 @@ Notes:
would warn about the unused type variable `a`.
.. _forall-or-nothing:
The ``forall``-or-nothing rule
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In certain forms of types, type variables obey what is known as the
"``forall``-or-nothing" rule: if a type has an outermost, explicit
``forall``, then all of the type variables in the type must be explicitly
quantified. These two examples illustrate how the rule works: ::
f :: forall a b. a -> b -> b -- OK, `a` and `b` are explicitly bound
g :: forall a. a -> forall b. b -> b -- OK, `a` and `b` are explicitly bound
h :: forall a. a -> b -> b -- Rejected, `b` is not in scope
The type signatures for ``f``, ``g``, and ``h`` all begin with an outermost
``forall``, so every type variable in these signatures must be explicitly
bound by a ``forall``. Both ``f`` and ``g`` obey the ``forall``-or-nothing
rule, since they explicitly quantify ``a`` and ``b``. On the other hand,
``h`` does not explicitly quantify ``b``, so GHC will reject its type
signature for being improperly scoped.
In places where the ``forall``-or-nothing rule takes effect, if a type does
*not* have an outermost ``forall``, then any type variables that are not
explicitly bound by a ``forall`` become implicitly quantified. For example: ::
i :: a -> b -> b -- `a` and `b` are implicitly quantified
j :: a -> forall b. b -> b -- `a` is implicitly quantified
k :: (forall a. a -> b -> b) -- `b` is implicitly quantified
GHC will accept ``i``, ``j``, and ``k``'s type signatures. Note that:
- ``j``'s signature is accepted despite its mixture of implicit and explicit
quantification. As long as a ``forall`` is not an outermost one, it is fine
to use it among implicitly bound type variables.
- ``k``'s signature is accepted because the outermost parentheses imply that
the ``forall`` is not an outermost ``forall``. The ``forall``-or-nothing
rule is one of the few places in GHC where the presence or absence of
parentheses can be semantically significant!
The ``forall``-or-nothing rule takes effect in the following places:
- Type signature declarations for functions, values, and class methods
- Expression type annotations
- Instance declarations
- :ref:`class-default-signatures`
- Type signatures in a :ref:`specialize-pragma` or
:ref:`specialize-instance-pragma`
- :ref:`standalone-kind-signatures`
- Type signatures for :ref:`gadt` constructors
- Type signatures for :ref:`pattern-synonyms`
- :ref:`data-instance-declarations`, :ref:`type-instance-declarations`,
:ref:`closed-type-families`, and :ref:`assoc-inst`
- :ref:`rewrite-rules` in which the type variables are explicitly quantified
Notes:
- :ref:`pattern-type-sigs` are a notable example of a place where
types do *not* obey the ``forall``-or-nothing rule. For example, GHC will
accept the following: ::
f (g :: forall a. a -> b) x = g x :: b
Furthermore, :ref:`rewrite-rules` do not obey the ``forall``-or-nothing rule
when their type variables are not explicitly quantified: ::
{-# RULES "f" forall (g :: forall a. a -> b) x. f g x = g x :: b #-}
- GADT constructors are extra particular about their ``forall``s. In addition
to adhering to the ``forall``-or-nothing rule, GADT constructors also forbid
nested ``forall``s. For example, GHC would reject the following GADT: ::
data T where
MkT :: (forall a. a -> b -> T)
Because of the lack of an outermost ``forall`` in the type of ``MkT``, the
``b`` would be implicitly quantified. In effect, it would be as if one had
written ``MkT :: forall b. (forall a. a -> b -> T)``, which contains nested
``forall``s. See :ref:`formal-gadt-syntax`.
......@@ -103,6 +103,114 @@ implements this behaviour, odd though it is. But for GADT-style
declarations, GHC's behaviour is much more useful, as well as much more
intuitive.
.. _formal-gadt-syntax:
Formal syntax for GADTs
~~~~~~~~~~~~~~~~~~~~~~~
To make more precise what is and what is not permitted inside of a GADT-style
constructor, we provide a BNF-style grammar for GADT below. Note that this
grammar is subject to change in the future. ::
gadt_con ::= conids '::' opt_forall opt_ctxt gadt_body
conids ::= conid
| conid ',' conids
opt_forall ::= <empty>
| 'forall' tv_bndrs '.'
tv_bndrs ::= <empty>
| tv_bndr tv_bndrs
tv_bndr ::= tyvar
| '(' tyvar '::' ctype ')'
opt_ctxt ::= <empty>
| btype '=>'
| '(' ctxt ')' '=>'
ctxt ::= ctype
| ctype ',' ctxt
gadt_body ::= prefix_gadt_body
| record_gadt_body
prefix_gadt_body ::= '(' prefix_gadt_body ')'
| return_type
| opt_bang btype '->' prefix_gadt_body
record_gadt_body ::= '{' fieldtypes '}' '->' return_type
fieldtypes ::= <empty>
| fieldname '::' opt_bang ctype
| fieldname '::' opt_bang ctype ',' fieldtypes
opt_bang ::= <empty>
| '!'
| '~'
| {-# UNPACK #-}
| {-# NOUNPACK #-}
Where:
- ``btype`` is a type that is not allowed to have an outermost
``forall``/``=>`` unless it is surrounded by parentheses. For example,
``forall a. a`` and ``Eq a => a`` are not legal ``btype``s, but
``(forall a. a)`` and ``(Eq a => a)`` are legal.
- ``ctype`` is a ``btype`` that has no restrictions on an outermost
``forall``/``=>``, so ``forall a. a`` and ``Eq a => a`` are legal ``ctype``s.
- ``return_type`` is a type that is not allowed to have ``forall``s, ``=>``s,
or ``->``s.
This is a simplified grammar that does not fully delve into all of the
implementation details of GHC's parser (such as the placement of Haddock
comments), but it is sufficient to attain an understanding of what is
syntactically allowed. Some further various observations about this grammar:
- GADT constructor types are currently not permitted to have nested ``forall``s
or ``=>``s. (e.g., something like ``MkT :: Int -> forall a. a -> T`` would be
rejected.) As a result, ``gadt_sig`` puts all of its quantification and
constraints up front with ``opt_forall`` and ``opt_context``. Note that
higher-rank ``forall``s and ``=>``s are only permitted if they do not appear
directly to the right of a function arrow in a `prefix_gadt_body`. (e.g.,
something like ``MkS :: Int -> (forall a. a) -> S`` is allowed, since
parentheses separate the ``forall`` from the ``->``.)
- Furthermore, GADT constructors do not permit outermost parentheses that
surround the ``opt_forall`` or ``opt_ctxt``, if at least one of them are
used. For example, ``MkU :: (forall a. a -> U)`` would be rejected, since
it would treat the ``forall`` as being nested.
Note that it is acceptable to use parentheses in a ``prefix_gadt_body``.
For instance, ``MkV1 :: forall a. (a) -> (V1)`` is acceptable, as is
``MkV2 :: forall a. (a -> V2)``.
- The function arrows in a ``prefix_gadt_body``, as well as the function
arrow in a ``record_gadt_body``, are required to be used infix. For
example, ``MkA :: (->) Int A`` would be rejected.
- GHC uses the function arrows in a ``prefix_gadt_body`` and
``prefix_gadt_body`` to syntactically demarcate the function and result
types. Note that GHC does not attempt to be clever about looking through
type synonyms here. If you attempt to do this, for instance: ::
type C = Int -> B
data B where
MkB :: C
Then GHC will interpret the return type of ``MkB`` to be ``C``, and since
GHC requires that the return type must be headed by ``B``, this will be
rejected. On the other hand, it is acceptable to use type synonyms within
the argument and result types themselves, so the following is permitted: ::
type B1 = Int
type B2 = B
data B where
MkB :: B1 -> B2
GADT syntax odds and ends
~~~~~~~~~~~~~~~~~~~~~~~~~
The rest of this section gives further details about GADT-style data
type declarations.
......
......@@ -74,7 +74,7 @@ The :extension:`TemplateHaskellQuotes` extension is considered safe under
that declaration splices are not allowed anywhere except at top level
(outside any other declarations).
The ``Q`` monad is a monad defined in ``Language.Haskell.TH.Syntax`` which
The ``Q`` monad is a monad defined in :th-ref:`Language.Haskell.TH.Syntax.` which
supports several useful operations during code generation such as reporting
errors or looking up identifiers in the environment.
......@@ -92,9 +92,10 @@ The :extension:`TemplateHaskellQuotes` extension is considered safe under
- ``[p| ... |]``, where the "..." is a pattern; the quotation has
type ``Quote m => m Pat``.
The ``Quote`` type class is the minimal interface necessary to implement
the desugaring of quotations. The ``Q`` monad is an instance of ``Quote`` but
contains many more operations which are not needed for defining quotations.
The ``Quote`` type class (:th-ref:`Language.Haskell.TH.Syntax.Quote`) is
the minimal interface necessary to implement the desugaring of quotations.
The ``Q`` monad is an instance of ``Quote`` but contains many more
operations which are not needed for defining quotations.
See :ref:`pts-where` for using partial type signatures in quotations.
......@@ -402,7 +403,7 @@ Using Template Haskell
----------------------
- The data types and monadic constructor functions for Template Haskell
are in the library ``Language.Haskell.TH.Syntax``.
are in the library :th-ref:`Language.Haskell.TH.Syntax.`.
- You can only run a function at compile time if it is imported from
another module. That is, you can't define a function in a module, and
......@@ -645,7 +646,7 @@ Here are the salient features
(Only the first two are described in the paper.)
- A quoter is a value of type
``Language.Haskell.TH.Quote.QuasiQuoter``, which is defined thus: ::
:th-ref:`Language.Haskell.TH.Quote.QuasiQuoter`, which is defined thus: ::
data QuasiQuoter = QuasiQuoter { quoteExp :: String -> Q Exp,
quotePat :: String -> Q Pat,
......
......@@ -1136,10 +1136,11 @@ Haddock
single: haddock
.. ghc-flag:: -haddock
:shortdesc: Make the parser more strict about Haddock comments.
:shortdesc: With this flag GHC will parse Haddock comments and include them
in the interface file it produces.
:type: dynamic
:reverse: -no-haddock
:category: misc
:category: haddock
By default, GHC ignores Haddock comments (``-- | ...`` and ``-- ^ ...``)
and does not check that they're associated with a valid term, such as a
......
......@@ -54,6 +54,14 @@ module GHC.Exts
-- * Overloaded string literals
IsString(..),
-- * CString
unpackCString#,
unpackAppendCString#,
unpackFoldrCString#,
unpackCStringUtf8#,
unpackNBytes#,
cstringLength#,
-- * Debugging
breakpoint, breakpointCond,
......
This diff is collapsed.
{-# LANGUAGE MagicHash, NoImplicitPrelude, BangPatterns #-}
{-# LANGUAGE MagicHash, NoImplicitPrelude, BangPatterns, UnliftedFFITypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.CString
......@@ -18,7 +17,7 @@
module GHC.CString (
unpackCString#, unpackAppendCString#, unpackFoldrCString#,
unpackCStringUtf8#, unpackNBytes#
unpackCStringUtf8#, unpackNBytes#, cstringLength#
) where
import GHC.Types
......@@ -174,3 +173,17 @@ unpackNBytes# addr len# = unpack [] (len# -# 1#)
case indexCharOffAddr# addr i# of
ch -> unpack (C# ch : acc) (i# -# 1#)
-- The return type is not correct here. We really want CSize,
-- but that type is defined in base. However, CSize should always
-- match the size of a machine word (I hope), so this is probably
-- alright on all platforms that GHC supports.
foreign import ccall unsafe "strlen" c_strlen :: Addr# -> Int#
-- | Compute the length of a NUL-terminated string. This address
-- must refer to immutable memory. GHC includes a built-in rule for
-- constant folding when the argument is a statically-known literal.
-- That is, a core-to-core pass reduces the expression
-- @cstringLength# "hello"#@ to the constant @5#@.
cstringLength# :: Addr# -> Int#
{-# INLINE[0] cstringLength# #-}
cstringLength# = c_strlen
## 0.6.2 (edit as necessary)
- Shipped with GHC 8.12.1
- Add known-key `cstringLength#` to `GHC.CString`. This is just the
C function `strlen`, but a built-in rewrite rule allows GHC to
compute the result at compile time when the argument is known.
## 0.6.1 (edit as necessary)
- Shipped with GHC 8.10.1
......
Subproject commit 8fffea5ca319e85e1bc9e7cac39e5a2c8effefcc
Subproject commit 1afc36ecd38c069251a836e1c1c8b3a3043ddc01
......@@ -43,6 +43,7 @@ Thumbs.db
*.prof.sample.normalised
*.run.stdout
*.run.stderr
*.dump-simpl
*.hp
tests/**/*.ps
......
......@@ -1344,6 +1344,26 @@ def compile_grep_asm(name: TestName,
# no problems found, this test passed
return passed()
def compile_grep_core(name: TestName,
way: WayName,
extra_hc_opts: str
) -> PassFail:
print('Compile only, extra args = ', extra_hc_opts)
result = simple_build(name + '.hs', way, '-ddump-to-file -dsuppress-all -ddump-simpl -O ' + extra_hc_opts, False, None, False, False)
if badResult(result):
return result
expected_pat_file = find_expected_file(name, 'substr-simpl')
actual_core_file = add_suffix(name, 'dump-simpl')
if not grep_output(join_normalisers(normalise_errmsg),
expected_pat_file, actual_core_file):
return failBecause('simplified core mismatch')
# no problems found, this test passed
return passed()
# -----------------------------------------------------------------------------
# Compile-and-run tests
......
T16326_Fail6.hs:9:3: error:
• GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkFoo :: forall a. a -> Foo a
• In the definition of data constructor ‘MkFoo’
In the data type declaration for ‘Foo’
Illegal visible, dependent quantification in the type of a term:
forall a -> a -> Foo a
(GHC does not yet support this)
In the definition of data constructor ‘MkFoo’
T12087.hs:6:3: error:
• GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF1 :: forall a. (Ord a, Eq a) => a -> F1 a
• In the definition of data constructor ‘MkF1’
In the data type declaration for ‘F1’
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF1 :: (Ord a, Eq a) => a -> F1 a
In the definition of data constructor ‘MkF1’
T12087.hs:9:3: error:
• GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF2 :: forall a. (Ord a, Eq a) => a -> F2 a
• In the definition of data constructor ‘MkF2’
In the data type declaration for ‘F2’
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF2 :: (Ord a, Eq a) => a -> F2 a
In the definition of data constructor ‘MkF2’
T12087.hs:12:3: error:
• GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF3 :: forall a b. (Eq a, Eq b) => a -> b -> F3 a
• In the definition of data constructor ‘MkF3’
In the data type declaration for ‘F3’
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF3 :: forall a b. (Eq a, Eq b) => a -> b -> F3 a
In the definition of data constructor ‘MkF3’
T12087.hs:15:3: error:
• GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF4 :: forall a b. (Eq a, Eq b) => a -> b -> F4 a
• In the definition of data constructor ‘MkF4’
In the data type declaration for ‘F4’
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF4 :: forall a b. (Eq a, Eq b) => a -> b -> F4 a
In the definition of data constructor ‘MkF4’
T12087.hs:18:3: error:
• GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF5 :: forall a b. Int -> Int -> a -> Int -> Int -> b -> F5 a
• In the definition of data constructor ‘MkF5’
In the data type declaration for ‘F5’
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkF5 :: forall a b. Int -> Int -> a -> Int -> Int -> b -> F5 a
In the definition of data constructor ‘MkF5’
......@@ -10,8 +10,8 @@ data Exp :: Type where
newtype TypedExp :: Type -> Type where
TEGood :: forall a . (Exp -> (TypedExp a))
-- The only difference here is that the type is wrapped in parentheses,
-- but GHC 8.0.1 rejects this program
-- The presence of outer parentheses makes the `forall` nested, and
-- GADTs do not permit nested `forall`s.
--
newtype TypedExpToo :: Type -> Type where
TEBad :: (forall a . (Exp -> (TypedExpToo a)))
T14320.hs:17:3: error:
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
TEBad :: forall a. Exp -> (TypedExpToo a)
In the definition of data constructor ‘TEBad’
T16427.hs:5:14: error:
• GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
C :: forall b. Int -> b -> D
• In the definition of data constructor ‘C’
In the data type declaration for ‘D’
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
C :: forall b. Int -> b -> D
In the definition of data constructor ‘C’
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
module T18191 where
data T where
MkT :: (forall a. a -> b -> T)
data S a where
MkS :: (forall a. S a)
data U a where
MkU :: (Show a => U a)
T18191.hs:6:3: error:
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature:
MkT :: forall a. a -> b -> T
In the definition of data constructor ‘MkT’
T18191.hs:9:3: error:
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature: MkS :: forall a. S a
In the definition of data constructor ‘MkS’
T18191.hs:12:3: error:
GADT constructor type signature cannot contain nested ‘forall’s or contexts
Suggestion: instead use this type signature: MkU :: Show a => U a
In the definition of data constructor ‘MkU’
......@@ -113,10 +113,11 @@ test('T7558', normal, compile_fail, [''])
test('T9380', normal, compile_and_run, [''])
test('T12087', normal, compile_fail, [''])
test('T12468', normal, compile_fail, [''])
test('T14320', normal, compile, [''])
test('T14320', normal, compile_fail, [''])
test('T14719', normal, compile_fail, ['-fdiagnostics-show-caret'])
test('T14808', normal, compile, [''])
test('T15009', normal, compile, [''])
test('T15558', normal, compile, [''])
test('T16427', normal, compile_fail, [''])
test('T17423', expect_broken(17423), compile_and_run, [''])
test('T18191', normal, compile_fail, [''])
......@@ -34,9 +34,9 @@
((Test10399.hs:12:30,AnnComma), [Test10399.hs:12:30]),
((Test10399.hs:12:31-32,AnnCloseP), [Test10399.hs:12:32]),
((Test10399.hs:12:31-32,AnnOpenP), [Test10399.hs:12:31]),
((Test10399.hs:(14,1)-(18,55),AnnData), [Test10399.hs:14:1-4]),
((Test10399.hs:(14,1)-(18,55),AnnSemi), [Test10399.hs:20:1]),
((Test10399.hs:(14,1)-(18,55),AnnWhere), [Test10399.hs:14:21-25]),
((Test10399.hs:(14,1)-(18,53),AnnData), [Test10399.hs:14:1-4]),
((Test10399.hs:(14,1)-(18,53),AnnSemi), [Test10399.hs:20:1]),
((Test10399.hs:(14,1)-(18,53),AnnWhere), [Test10399.hs:14:21-25]),
((Test10399.hs:15:5-64,AnnDcolon), [Test10399.hs:15:11-12]),
((Test10399.hs:15:5-64,AnnSemi), [Test10399.hs:16:5]),
((Test10399.hs:15:14-64,AnnDot), [Test10399.hs:15:23]),
......@@ -48,37 +48,29 @@
((Test10399.hs:15:45-46,AnnBang), [Test10399.hs:15:45]),
((Test10399.hs:15:45-46,AnnRarrow), [Test10399.hs:15:48-49]),
((Test10399.hs:15:45-64,AnnRarrow), [Test10399.hs:15:48-49]),
((Test10399.hs:(16,5)-(17,69),AnnCloseP), [Test10399.hs:17:69]),
((Test10399.hs:(16,5)-(17,69),AnnDcolon), [Test10399.hs:16:12-13]),
((Test10399.hs:(16,5)-(17,69),AnnOpenP), [Test10399.hs:16:27]),
((Test10399.hs:(16,5)-(17,69),AnnSemi), [Test10399.hs:18:5]),
((Test10399.hs:(16,15)-(17,69),AnnDot), [Test10399.hs:16:25]),
((Test10399.hs:(16,15)-(17,69),AnnForall), [Test10399.hs:16:15-20]),
((Test10399.hs:(16,27)-(17,69),AnnCloseP), [Test10399.hs:17:69]),
((Test10399.hs:(16,27)-(17,69),AnnOpenP), [Test10399.hs:16:27]),
((Test10399.hs:16:28-43,AnnCloseP), [Test10399.hs:16:43, Test10399.hs:16:43]),
((Test10399.hs:16:28-43,AnnDarrow), [Test10399.hs:16:45-46]),
((Test10399.hs:16:28-43,AnnOpenP), [Test10399.hs:16:28, Test10399.hs:16:28]),
((Test10399.hs:16:30-33,AnnComma), [Test10399.hs:16:34]),
((Test10399.hs:16:48,AnnRarrow), [Test10399.hs:16:50-51]),
((Test10399.hs:(16,48)-(17,68),AnnRarrow), [Test10399.hs:16:50-51]),
((Test10399.hs:16:53-66,AnnRarrow), [Test10399.hs:17:45-46]),
((Test10399.hs:(16,53)-(17,68),AnnRarrow), [Test10399.hs:17:45-46]),
((Test10399.hs:17:48,AnnRarrow), [Test10399.hs:17:50-51]),
((Test10399.hs:17:48-68,AnnRarrow), [Test10399.hs:17:50-51]),
((Test10399.hs:17:66-68,AnnCloseS), [Test10399.hs:17:68]),
((Test10399.hs:17:66-68,AnnOpenS), [Test10399.hs:17:66]),
((Test10399.hs:18:5-55,AnnCloseP), [Test10399.hs:18:55]),
((Test10399.hs:18:5-55,AnnDcolon), [Test10399.hs:18:16-17]),
((Test10399.hs:18:5-55,AnnOpenP), [Test10399.hs:18:19]),
((Test10399.hs:18:19-55,AnnCloseP), [Test10399.hs:18:55]),
((Test10399.hs:18:19-55,AnnOpenP), [Test10399.hs:18:19]),
((Test10399.hs:18:20-54,AnnDot), [Test10399.hs:18:29]),
((Test10399.hs:18:20-54,AnnForall), [Test10399.hs:18:20-25]),
((Test10399.hs:18:31-36,AnnCloseP), [Test10399.hs:18:36]),
((Test10399.hs:18:31-36,AnnOpenP), [Test10399.hs:18:31]),
((Test10399.hs:18:31-36,AnnRarrow), [Test10399.hs:18:38-39]),
((Test10399.hs:18:31-54,AnnRarrow), [Test10399.hs:18:38-39]),
((Test10399.hs:(16,5)-(17,67),AnnDcolon), [Test10399.hs:16:12-13]),
((Test10399.hs:(16,5)-(17,67),AnnSemi), [Test10399.hs:18:5]),
((Test10399.hs:(16,15)-(17,67),AnnDot), [Test10399.hs:16:25]),
((Test10399.hs:(16,15)-(17,67),AnnForall), [Test10399.hs:16:15-20]),
((Test10399.hs:16:27-42,AnnCloseP), [Test10399.hs:16:42, Test10399.hs:16:42]),
((Test10399.hs:16:27-42,AnnDarrow), [Test10399.hs:16:44-45]),
((Test10399.hs:16:27-42,AnnOpenP), [Test10399.hs:16:27, Test10399.hs:16:27]),
((Test10399.hs:16:29-32,AnnComma), [Test10399.hs:16:33]),
((Test10399.hs:16:47,AnnRarrow), [Test10399.hs:16:49-50]),
((Test10399.hs:(16,47)-(17,67),AnnRarrow), [Test10399.hs:16:49-50]),
((Test10399.hs:16:52-65,AnnRarrow), [Test10399.hs:17:44-45]),
((Test10399.hs:(16,52)-(17,67),AnnRarrow), [Test10399.hs:17:44-45]),
((Test10399.hs:17:47,AnnRarrow), [Test10399.hs:17:49-50]),
((Test10399.hs:17:47-67,AnnRarrow), [Test10399.hs:17:49-50]),
((Test10399.hs:17:65-67,AnnCloseS), [Test10399.hs:17:67]),
((Test10399.hs:17:65-67,AnnOpenS), [Test10399.hs:17:65]),
((Test10399.hs:18:5-53,AnnDcolon), [Test10399.hs:18:16-17]),
((Test10399.hs:18:19-53,AnnDot), [Test10399.hs:18:28]),
((Test10399.hs:18:19-53,AnnForall), [Test10399.hs:18:19-24]),
((Test10399.hs:18:30-35,AnnCloseP), [Test10399.hs:18:35]),
((Test10399.hs:18:30-35,AnnOpenP), [Test10399.hs:18:30]),
((Test10399.hs:18:30-35,AnnRarrow), [Test10399.hs:18:37-38]),
((Test10399.hs:18:30-53,AnnRarrow), [Test10399.hs:18:37-38]),
((Test10399.hs:20:1-25,AnnCloseQ), [Test10399.hs:20:24-25]),
((Test10399.hs:20:1-25,AnnOpen), [Test10399.hs:20:1-3]),
((Test10399.hs:20:1-25,AnnSemi), [Test10399.hs:22:1]),
......
......@@ -13,9 +13,9 @@ mkPoli = mkBila . map ((,,(),,()) <$> P.base <*> P.pos <*> P.form)
data MaybeDefault v where
SetTo :: forall v . ( Eq v, Show v ) => !v -> MaybeDefault v
SetTo4 :: forall v a. (( Eq v, Show v ) => v -> MaybeDefault v
-> a -> MaybeDefault [a])
TestParens :: (forall v . (Eq v) -> MaybeDefault v)
SetTo4 :: forall v a. ( Eq v, Show v ) => v -> MaybeDefault v
-> a -> MaybeDefault [a]
TestParens :: forall v . (Eq v) -> MaybeDefault v
[t| Map.Map T.Text $tc |]
......
......@@ -3,4 +3,4 @@
module T15323 where
data MaybeDefault v where
TestParens :: (forall v . (Eq v) => MaybeDefault v)
TestParens :: forall v . (Eq v) => MaybeDefault v
......@@ -8,7 +8,7 @@
{ModuleName: T15323}))
(Nothing)
[]
[({ T15323.hs:(5,1)-(6,56) }
[({ T15323.hs:(5,1)-(6,54) }
(TyClD
(NoExtField)
(DataDecl
......@@ -33,60 +33,60 @@
[])
(Nothing)
(Nothing)
[({ T15323.hs:6:5-56 }
[({ T15323.hs:6:5-54 }
(ConDeclGADT
(NoExtField)
[({ T15323.hs:6:5-14 }
(Unqual
{OccName: TestParens}))]
({ T15323.hs:6:21-55 }
({ T15323.hs:6:20-54 }
(True))
[({ T15323.hs:6:28 }
[({ T15323.hs:6:27 }
(UserTyVar
(NoExtField)
(SpecifiedSpec)
({ T15323.hs:6:28 }
({ T15323.hs:6:27 }
(Unqual
{OccName: v}))))]
(Just
({ T15323.hs:6:32-37 }
[({ T15323.hs:6:32-37 }
({ T15323.hs:6:31-36 }
[({ T15323.hs:6:31-36 }
(HsParTy
(NoExtField)
({ T15323.hs:6:33-36 }
({ T15323.hs:6:32-35 }
(HsAppTy
(NoExtField)
({ T15323.hs:6:33-34 }
({ T15323.hs:6:32-33 }
(HsTyVar
(NoExtField)
(NotPromoted)
({ T15323.hs:6:33-34 }
({ T15323.hs:6:32-33 }
(Unqual
{OccName: Eq}))))
({ T15323.hs:6:36 }
({ T15323.hs:6:35 }
(HsTyVar
(NoExtField)
(NotPromoted)
({ T15323.hs:6:36 }
({ T15323.hs:6:35 }
(Unqual
{OccName: v}))))))))]))
(PrefixCon
[])
({ T15323.hs:6:42-55 }
({ T15323.hs:6:41-54 }
(HsAppTy
(NoExtField)
({ T15323.hs:6:42-53 }
({ T15323.hs:6:41-52 }
(HsTyVar
(NoExtField)
(NotPromoted)
({ T15323.hs:6:42-53 }
({ T15323.hs:6:41-52 }
(Unqual
{OccName: MaybeDefault}))))
({ T15323.hs:6:55 }
({ T15323.hs:6:54 }
(HsTyVar
(NoExtField)
(NotPromoted)
({ T15323.hs:6:55 }
({ T15323.hs:6:54 }
(Unqual
{OccName: v}))))))
(Nothing)))]
......
{-# language MagicHash #-}
module CStringLengthCore
( ozymandias
) where
import GHC.Exts
ozymandias :: Int
ozymandias =
I# (cstringLength# "I met a traveller from an antique land"#)
test('CStringLength_core', normal, compile_grep_core, [''])
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
import GHC.Exts
main :: IO ()
main = do
putStr "A: "
print $
I# (cstringLength# "hello_world"#)
==
naiveStrlen "hello_world"# 0
putStr "B: "
print $
I# (cstringLength# "aaaaaaaaaaaaa\x00b"#)
==
naiveStrlen "aaaaaaaaaaaaa\x00b"# 0
putStr "C: "
print $
I# (cstringLength# "cccccccccccccccccc\x00b"#)
==
naiveStrlen "cccccccccccccccccc\x00b"# 0
putStr "D: "
print $
I# (cstringLength# "araña\NULb"#)
==
naiveStrlen "araña\NULb"# 0
naiveStrlen :: Addr# -> Int -> Int
naiveStrlen addr !n = case indexWord8OffAddr# addr 0# of
0## -> n
_ -> naiveStrlen (plusAddr# addr 1#) (n + 1)
......@@ -29,3 +29,4 @@ test('CmpWord16', normal, compile_and_run, [''])
test('ShrinkSmallMutableArrayA', normal, compile_and_run, [''])
test('ShrinkSmallMutableArrayB', normal, compile_and_run, [''])
test('T14664', normal, compile_and_run, [''])
test('CStringLength', normal, compile_and_run, ['-O2'])
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
module T18145 where
type family A :: k
type instance forall. A = Nothing :: Maybe a -- 'a' should be out of scope
class Foo x where
type B x :: Maybe a
type forall x. B x = Nothing :: Maybe a -- 'a' should be out of scope
instance Foo [x] where
type forall. B [x] = Nothing :: Maybe a -- 'a' should be out of scope
T18145.hs:10:44: error: Not in scope: type variable ‘a’
T18145.hs:14:41: error: Not in scope: type variable ‘a’
T18145.hs:17:41: error: Not in scope: type variable ‘a’
......@@ -153,3 +153,4 @@ test('T16504', normal, compile_fail, [''])
test('T14548', normal, compile_fail, [''])
test('T16610', normal, compile_fail, [''])
test('T17593', normal, compile_fail, [''])
test('T18145', normal, compile_fail, [''])