Skip to content
Snippets Groups Projects
  1. Feb 03, 2024
    • Apoorv Ingle's avatar
      Expand `do` blocks right before typechecking using the `HsExpansion` philosophy. · 5ff7cc26
      Apoorv Ingle authored
      - Fixes #18324 #20020 #23147 #22788 #15598 #22086 #21206
      
      - The change is detailed in
        - Note [Expanding HsDo with HsExpansion] in `GHC.Tc.Gen.Do`
        - Note [Doing HsExpansion in the Renamer vs Typechecker] in `GHC.Rename.Expr`
               expains the rational of doing expansions in type checker as opposed to in the renamer
      
      - Adds new datatypes:
        - `GHC.Hs.Expr.XXExprGhcRn`: new datatype makes this expansion work easier
          1. Expansion bits for Expressions, Statements and Patterns in (`ExpandedThingRn`)
          2. `PopErrCtxt` a special GhcRn Phase only artifcat to pop the previous error message in the error context stack
      
        - `GHC.Basic.Origin` now tracks the reason for expansion in case of Generated
          This is useful for type checking cf. `GHC.Tc.Gen.Expr.tcExpr` case for `HsLam`
      
        - Kills `HsExpansion` and `HsExpanded` as we have inlined them in `XXExprGhcRn` and `XXExprGhcTc`
      
      - Ensures warnings such as
        1. Pattern match checks
        2. Failable patterns
        3. non-() return in body statements are preserved
      
      - Kill `HsMatchCtxt` in favor of `TcMatchAltChecker`
      
      - Testcases:
        * T18324 T20020 T23147 T22788 T15598 T22086
        * T23147b (error message check),
        * DoubleMatch (match inside a match for pmc check)
        * pattern-fails (check pattern match with non-refutable pattern, eg. newtype)
        * Simple-rec (rec statements inside do statment)
        * T22788 (code snippet from #22788)
        * DoExpanion1 (Error messages for body statments)
        * DoExpansion2 (Error messages for bind statements)
        * DoExpansion3 (Error messages for let statements)
      
      Also repoint haddock to the right submodule so that the test (haddockHypsrcTest) pass
      
      Metric Increase 'compile_time/bytes allocated':
          T9020
      
      The testcase is a pathalogical example of a `do`-block with many statements that do nothing.
      Given that we are expanding the statements into function binds, we will have to bear
      a (small) 2% cost upfront in the compiler to unroll the statements.
      5ff7cc26
  2. Jan 20, 2024
  3. Jan 14, 2024
  4. Dec 06, 2023
  5. Jul 26, 2023
    • Bartłomiej Cieślar's avatar
      This MR is an implementation of the proposal #516. · 503fd647
      Bartłomiej Cieślar authored and Marge Bot's avatar Marge Bot committed
      It adds a warning -Wincomplete-record-selectors for usages of a record
      field access function (either a record selector or getField @"rec"),
      while trying to silence the warning whenever it can be sure that a constructor
      without the record field would not be invoked (which would otherwise cause
      the program to fail). For example:
      
          data T = T1 | T2 {x :: Bool}
      
          f a = x a -- this would throw an error
      
          g T1 = True
          g a = x a -- this would not throw an error
      
          h :: HasField "x" r Bool => r -> Bool
          h = getField @"x"
      
          j :: T -> Bool
          j = h -- this would throw an error because of the `HasField`
                -- constraint being solved
      
      See the tests DsIncompleteRecSel* and TcIncompleteRecSel for more examples of the warning.
      See Note [Detecting incomplete record selectors] in GHC.HsToCore.Expr for implementation details
      503fd647
  6. Jul 18, 2023
    • sheaf's avatar
      Skip PMC for boring patterns · bea0e323
      sheaf authored and Marge Bot's avatar Marge Bot committed
      Some patterns introduce no new information to the pattern-match
      checker (such as plain variable or wildcard patterns). We can thus
      skip doing any pattern-match checking on them when the sole purpose
      for doing so was introducing new long-distance information.
      
      See Note [Boring patterns] in GHC.Hs.Pat.
      
      Doing this avoids regressing in performance now that we do additional
      pattern-match checking inside do notation.
      bea0e323
    • sheaf's avatar
      Propagate long-distance information in do-notation · 1d05971e
      sheaf authored and Marge Bot's avatar Marge Bot committed
      The preceding commit re-enabled pattern-match checking inside record
      updates. This revealed that #21360 was in fact NOT fixed by e74fc066.
      
      This commit makes sure we correctly propagate long-distance information
      in do blocks, e.g. in
      
      ```haskell
      data T = A { fld :: Int } | B
      
      f :: T -> Maybe T
      f r = do
        a@A{} <- Just r
        Just $ case a of { A _ -> A 9 }
      ```
      
      we need to propagate the fact that "a" is headed by the constructor "A"
      to see that the case expression "case a of { A _ -> A 9 }" cannot fail.
      
      Fixes #21360
      1d05971e
    • sheaf's avatar
      Re-instate -Wincomplete-record-updates · df706de3
      sheaf authored and Marge Bot's avatar Marge Bot committed
      Commit e74fc066 refactored the handling of record updates to use
      the HsExpanded mechanism. This meant that the pattern matching inherent
      to a record update was considered to be "generated code", and thus we
      stopped emitting "incomplete record update" warnings entirely.
      
      This commit changes the "data Origin = Source | Generated" datatype,
      adding a field to the Generated constructor to indicate whether we
      still want to perform pattern-match checking. We also have to do a bit
      of plumbing with HsCase, to record that the HsCase arose from an
      HsExpansion of a RecUpd, so that the error message continues to mention
      record updates as opposed to a generic "incomplete pattern matches in case"
      error.
      
      Finally, this patch also changes the way we handle inaccessible code
      warnings. Commit e74fc066 was also a regression in this regard, as we
      were emitting "inaccessible code" warnings for case statements spuriously
      generated when desugaring a record update (remember: the desugaring mechanism
      happens before typechecking; it thus can't take into account e.g. GADT information
      in order to decide which constructors to include in the RHS of the desugaring
      of the record update).
      We fix this by changing the mechanism through which we disable inaccessible
      code warnings: we now check whether we are in generated code in
      GHC.Tc.Utils.TcMType.newImplication in order to determine whether to
      emit inaccessible code warnings.
      
      Fixes #23520
      Updates haddock submodule, to avoid incomplete record update warnings
      df706de3
  7. Jul 15, 2023
    • Matthew Craven's avatar
      Equality of forall-types is visibility aware · cf86f3ec
      Matthew Craven authored and Vladislav Zavialov's avatar Vladislav Zavialov committed
      This patch finally (I hope) nails the question of whether
         (forall a. ty) and (forall a -> ty)
      are `eqType`: they aren't!
      
      There is a long discussion in #22762, plus useful Notes:
      
      * Note [ForAllTy and type equality] in GHC.Core.TyCo.Compare
      * Note [Comparing visiblities] in GHC.Core.TyCo.Compare
      * Note [ForAllCo] in GHC.Core.TyCo.Rep
      
      It also establishes a helpful new invariant for ForAllCo,
      and ForAllTy, when the bound variable is a CoVar:in that
      case the visibility must be coreTyLamForAllTyFlag.
      
      All this is well documented in revised Notes.
      cf86f3ec
  8. Jul 05, 2023
    • Vladislav Zavialov's avatar
      testsuite: Do not require CUSKs · 679bbc97
      Vladislav Zavialov authored and Marge Bot's avatar Marge Bot committed
      Numerous tests make use of CUSKs (complete user-supplied kinds),
      a legacy feature scheduled for deprecation. In order to proceed
      with the said deprecation, the tests have been updated to use SAKS
      instead (standalone kind signatures).
      
      This also allows us to remove the Haskell2010 language pragmas that
      were added in 115cd3c8 to work around the lack of CUSKs in GHC2021.
      679bbc97
  9. May 25, 2023
    • sheaf's avatar
      Propagate long-distance info in generated code · fbc8e04e
      sheaf authored and Marge Bot's avatar Marge Bot committed
      When desugaring generated pattern matches, we skip pattern match checks.
      However, this ended up also discarding long-distance information, which
      might be needed for user-written sub-expressions.
      
      Example:
      
      ```haskell
      okay (GADT di) cd =
        let sr_field :: ()
            sr_field = case getFooBar di of { Foo -> () }
        in case cd of { SomeRec _ -> SomeRec sr_field }
      ```
      
      With sr_field a generated FunBind, we still want to propagate the outer
      long-distance information from the GADT pattern match into the checks
      for the user-written RHS of sr_field.
      
      Fixes #23445
      fbc8e04e
  10. May 23, 2023
    • Simon Peyton Jones's avatar
      Add the SolverStage monad · e1590ddc
      Simon Peyton Jones authored and Marge Bot's avatar Marge Bot committed
      This refactoring makes a substantial improvement in the
      structure of the type-checker's constraint solver: #23070.
      
      Specifically:
      
      * Introduced the SolverStage monad.   See GHC.Tc.Solver.Monad
        Note [The SolverStage monad]
      
      * Make each solver pipeline (equalities, dictionaries, irreds etc)
        deal with updating the inert set, as a separate SolverStage.  There
        is sometimes special stuff to do, and it means that each full
        pipeline can have type SolverStage Void, indicating that they never
        return anything.
      
      * Made GHC.Tc.Solver.Equality.zonkEqTypes into a SolverStage.  Much nicer.
      
      * Combined the remnants of GHC.Tc.Solver.Canonical and
        GHC.Tc.Solver.Interact into a new module GHC.Tc.Solver.Solve.
        (Interact and Canonical are removed.)
      
      * Gave the same treatment to dictionary and irred constraints
        as I have already done for equality constraints:
          * New types (akin to EqCt): IrredCt and DictCt
          * Ct is now just a simple sum type
                data Ct
                  = CDictCan      DictCt
                  | CIrredCan     IrredCt
                  | CEqCan        EqCt
                  | CQuantCan     QCInst
                  | CNonCanonical CtEvidence
          * inert_dicts can now have the better type DictMap DictCt, instead of
            DictMap Ct; and similarly inert_irreds.
      
      * Significantly simplified the treatment of implicit parameters.
        Previously we had a number of special cases
          * interactGivenIP, an entire function
          * special case in maybeKickOut
          * special case in findDict, when looking up dictionaries
        But actually it's simpler than that. When adding a new Given, implicit
        parameter constraint to the InertSet, we just need to kick out any
        existing inert constraints that mention that implicit parameter.
      
        The main work is done in GHC.Tc.Solver.InertSet.delIPDict, along with
        its auxiliary GHC.Core.Predicate.mentionsIP.
      
        See Note [Shadowing of implicit parameters] in GHC.Tc.Solver.Dict.
      
      * Add a new fast-path in GHC.Tc.Errors.Hole.tcCheckHoleFit.
        See Note [Fast path for tcCheckHoleFit].  This is a big win in some cases:
        test hard_hole_fits gets nearly 40% faster (at compile time).
      
      * Add a new fast-path for solving /boxed/ equality constraints
        (t1 ~ t2).  See Note [Solving equality classes] in GHC.Tc.Solver.Dict.
        This makes a big difference too: test T17836 compiles 40% faster.
      
      * Implement the PermissivePlan of #23413, which concerns what happens with
        insoluble Givens.   Our previous treatment was wildly inconsistent as that
        ticket pointed out.
      
        A part of this, I simplified GHC.Tc.Validity.checkAmbiguity: now we simply
        don't run the ambiguity check at all if -XAllowAmbiguousTypes is on.
      
      Smaller points:
      
      * In `GHC.Tc.Errors.misMatchOrCND` instead of having a special case for
        insoluble /occurs/ checks, broaden in to all insouluble constraints.
        Just generally better. See Note [Insoluble mis-match] in that module.
      
      As noted above, compile time perf gets better.  Here are the changes
      over 0.5% on Fedora.  (The figures are slightly larger on Windows for
      some reason.)
      
      Metrics: compile_time/bytes allocated
      -------------------------------------
                      LargeRecord(normal)   -0.9%
      MultiLayerModulesTH_OneShot(normal)   +0.5%
                           T11822(normal)   -0.6%
                           T12227(normal)   -1.8% GOOD
                           T12545(normal)   -0.5%
                           T13035(normal)   -0.6%
                           T15703(normal)   -1.4% GOOD
                           T16875(normal)   -0.5%
                           T17836(normal)  -40.7% GOOD
                          T17836b(normal)  -12.3% GOOD
                          T17977b(normal)   -0.5%
                            T5837(normal)   -1.1%
                            T8095(normal)   -2.7% GOOD
                            T9020(optasm)   -1.1%
                   hard_hole_fits(normal)  -37.0% GOOD
      
                                geo. mean   -1.3%
                                minimum    -40.7%
                                maximum     +0.5%
      
      Metric Decrease:
          T12227
          T15703
          T17836
          T17836b
          T8095
          hard_hole_fits
          LargeRecord
          T9198
          T13035
      e1590ddc
  11. Mar 30, 2023
  12. Feb 21, 2023
  13. Dec 14, 2022
  14. Nov 25, 2022
    • Vladislav Zavialov's avatar
      Print unticked promoted data constructors (#20531) · 13d627bb
      Vladislav Zavialov authored and Marge Bot's avatar Marge Bot committed
      
      Before this patch, GHC unconditionally printed ticks before promoted
      data constructors:
      
      	ghci> type T = True  -- unticked (user-written)
      	ghci> :kind! T
      	T :: Bool
      	= 'True              -- ticked (compiler output)
      
      After this patch, GHC prints ticks only when necessary:
      
      	ghci> type F = False    -- unticked (user-written)
      	ghci> :kind! F
      	F :: Bool
      	= False                 -- unticked (compiler output)
      
      	ghci> data False        -- introduce ambiguity
      	ghci> :kind! F
      	F :: Bool
      	= 'False                -- ticked by necessity (compiler output)
      
      The old behavior can be enabled by -fprint-redundant-promotion-ticks.
      
      Summary of changes:
      * Rename PrintUnqualified to NamePprCtx
      * Add QueryPromotionTick to it
      * Consult the GlobalRdrEnv to decide whether to print a tick (see mkPromTick)
      * Introduce -fprint-redundant-promotion-ticks
      
      Co-authored-by: default avatarArtyom Kuznetsov <hi@wzrd.ht>
      13d627bb
  15. Nov 11, 2022
    • Simon Peyton Jones's avatar
      Type vs Constraint: finally nailed · 778c6adc
      Simon Peyton Jones authored and Simon Peyton Jones's avatar Simon Peyton Jones committed
      This big patch addresses the rats-nest of issues that have plagued
      us for years, about the relationship between Type and Constraint.
      See #11715/#21623.
      
      The main payload of the patch is:
      * To introduce CONSTRAINT :: RuntimeRep -> Type
      * To make TYPE and CONSTRAINT distinct throughout the compiler
      
      Two overview Notes in GHC.Builtin.Types.Prim
      
      * Note [TYPE and CONSTRAINT]
      
      * Note [Type and Constraint are not apart]
        This is the main complication.
      
      The specifics
      
      * New primitive types (GHC.Builtin.Types.Prim)
        - CONSTRAINT
        - ctArrowTyCon (=>)
        - tcArrowTyCon (-=>)
        - ccArrowTyCon (==>)
        - funTyCon     FUN     -- Not new
        See Note [Function type constructors and FunTy]
        and Note [TYPE and CONSTRAINT]
      
      * GHC.Builtin.Types:
        - New type Constraint = CONSTRAINT LiftedRep
        - I also stopped nonEmptyTyCon being built-in; it only needs to be wired-in
      
      * Exploit the fact that Type and Constraint are distinct throughout GHC
        - Get rid of tcView in favour of coreView.
        - Many tcXX functions become XX functions.
          e.g. tcGetCastedTyVar --> getCastedTyVar
      
      * Kill off Note [ForAllTy and typechecker equality], in (old)
        GHC.Tc.Solver.Canonical.  It said that typechecker-equality should ignore
        the specified/inferred distinction when comparein two ForAllTys.  But
        that wsa only weakly supported and (worse) implies that we need a separate
        typechecker equality, different from core equality. No no no.
      
      * GHC.Core.TyCon: kill off FunTyCon in data TyCon.  There was no need for it,
        and anyway now we have four of them!
      
      * GHC.Core.TyCo.Rep: add two FunTyFlags to FunCo
        See Note [FunCo] in that module.
      
      * GHC.Core.Type.  Lots and lots of changes driven by adding CONSTRAINT.
        The key new function is sORTKind_maybe; most other changes are built
        on top of that.
      
        See also `funTyConAppTy_maybe` and `tyConAppFun_maybe`.
      
      * Fix a longstanding bug in GHC.Core.Type.typeKind, and Core Lint, in
        kinding ForAllTys.  See new tules (FORALL1) and (FORALL2) in GHC.Core.Type.
        (The bug was that before (forall (cv::t1 ~# t2). blah), where
        blah::TYPE IntRep, would get kind (TYPE IntRep), but it should be
        (TYPE LiftedRep).  See Note [Kinding rules for types] in GHC.Core.Type.
      
      * GHC.Core.TyCo.Compare is a new module in which we do eqType and cmpType.
        Of course, no tcEqType any more.
      
      * GHC.Core.TyCo.FVs. I moved some free-var-like function into this module:
        tyConsOfType, visVarsOfType, and occCheckExpand.  Refactoring only.
      
      * GHC.Builtin.Types.  Compiletely re-engineer boxingDataCon_maybe to
        have one for each /RuntimeRep/, rather than one for each /Type/.
        This dramatically widens the range of types we can auto-box.
        See Note [Boxing constructors] in GHC.Builtin.Types
        The boxing types themselves are declared in library ghc-prim:GHC.Types.
      
        GHC.Core.Make.  Re-engineer the treatment of "big" tuples (mkBigCoreVarTup
        etc) GHC.Core.Make, so that it auto-boxes unboxed values and (crucially)
        types of kind Constraint. That allows the desugaring for arrows to work;
        it gathers up free variables (including dictionaries) into tuples.
        See  Note [Big tuples] in GHC.Core.Make.
      
        There is still work to do here: #22336. But things are better than
        before.
      
      * GHC.Core.Make.  We need two absent-error Ids, aBSENT_ERROR_ID for types of
        kind Type, and aBSENT_CONSTRAINT_ERROR_ID for vaues of kind Constraint.
        Ditto noInlineId vs noInlieConstraintId in GHC.Types.Id.Make;
        see Note [inlineId magic].
      
      * GHC.Core.TyCo.Rep. Completely refactor the NthCo coercion.  It is now called
        SelCo, and its fields are much more descriptive than the single Int we used to
        have.  A great improvement.  See Note [SelCo] in GHC.Core.TyCo.Rep.
      
      * GHC.Core.RoughMap.roughMatchTyConName.  Collapse TYPE and CONSTRAINT to
        a single TyCon, so that the rough-map does not distinguish them.
      
      * GHC.Core.DataCon
        - Mainly just improve documentation
      
      * Some significant renamings:
        GHC.Core.Multiplicity: Many -->  ManyTy (easier to grep for)
                               One  -->  OneTy
        GHC.Core.TyCo.Rep TyCoBinder      -->   GHC.Core.Var.PiTyBinder
        GHC.Core.Var      TyCoVarBinder   -->   ForAllTyBinder
                          AnonArgFlag     -->   FunTyFlag
                          ArgFlag         -->   ForAllTyFlag
        GHC.Core.TyCon    TyConTyCoBinder --> TyConPiTyBinder
        Many functions are renamed in consequence
        e.g. isinvisibleArgFlag becomes isInvisibleForAllTyFlag, etc
      
      * I refactored FunTyFlag (was AnonArgFlag) into a simple, flat data type
          data FunTyFlag
            = FTF_T_T           -- (->)  Type -> Type
            | FTF_T_C           -- (-=>) Type -> Constraint
            | FTF_C_T           -- (=>)  Constraint -> Type
            | FTF_C_C           -- (==>) Constraint -> Constraint
      
      * GHC.Tc.Errors.Ppr.  Some significant refactoring in the TypeEqMisMatch case
        of pprMismatchMsg.
      
      * I made the tyConUnique field of TyCon strict, because I
        saw code with lots of silly eval's.  That revealed that
        GHC.Settings.Constants.mAX_SUM_SIZE can only be 63, because
        we pack the sum tag into a 6-bit field.  (Lurking bug squashed.)
      
      Fixes
      * #21530
      
      Updates haddock submodule slightly.
      
      Performance changes
      ~~~~~~~~~~~~~~~~~~~
      I was worried that compile times would get worse, but after
      some careful profiling we are down to a geometric mean 0.1%
      increase in allocation (in perf/compiler).  That seems fine.
      
      There is a big runtime improvement in T10359
      
      Metric Decrease:
          LargeRecord
          MultiLayerModulesTH_OneShot
          T13386
          T13719
      Metric Increase:
          T8095
      778c6adc
  16. Sep 13, 2022
    • sheaf's avatar
      Diagnostic codes: acccept test changes · 362cca13
      sheaf authored and Marge Bot's avatar Marge Bot committed
      The testsuite output now contains diagnostic codes, so many tests need
      to be updated at once.
      We decided it was best to keep the diagnostic codes in the testsuite
      output, so that contributors don't inadvertently make changes to the
      diagnostic codes.
      362cca13
  17. Aug 26, 2022
    • sheaf's avatar
      Pmc: consider any 2 dicts of the same type equal · 4786acf7
      sheaf authored and Marge Bot's avatar Marge Bot committed
      This patch massages the keys used in the `TmOracle` `CoreMap` to ensure
      that dictionaries of coherent classes give the same key.
      That is, whenever we have an expression we want to insert or lookup in
      the `TmOracle` `CoreMap`, we first replace any dictionary
      `$dict_abcd :: ct` with a value of the form `error @ct`.
      
      This allows us to common-up view pattern functions with required
      constraints whose arguments differed only in the uniques of the
      dictionaries they were provided, thus fixing #21662.
      
      This is a rather ad-hoc change to the keys used in the
      `TmOracle` `CoreMap`. In the long run, we would probably want to use
      a different representation for the keys instead of simply using
      `CoreExpr` as-is. This more ambitious plan is outlined in #19272.
      
      Fixes #21662
      Updates unix submodule
      4786acf7
  18. Jul 22, 2022
    • sheaf's avatar
      Add test for #21360 · 6379f942
      sheaf authored and Marge Bot's avatar Marge Bot committed
      The way record updates are typechecked/desugared changed in MR !7981.
      Because we desugar in the typechecker to a simple case expression, the
      pattern match checker becomes able to spot the long-distance information
      and avoid emitting an incorrect pattern match warning.
      
      Fixes #21360
      6379f942
  19. Jun 06, 2022
  20. May 25, 2022
    • CarrieMY's avatar
      Desugar RecordUpd in `tcExpr` · e74fc066
      CarrieMY authored and sheaf's avatar sheaf committed
      This patch typechecks record updates by desugaring them inside
      the typechecker using the HsExpansion mechanism, and then typechecking
      this desugared result.
      
      Example:
      
          data T p q = T1 { x :: Int, y :: Bool, z :: Char }
                     | T2 { v :: Char }
                     | T3 { x :: Int }
                     | T4 { p :: Float, y :: Bool, x :: Int }
                     | T5
      
      The record update `e { x=e1, y=e2 }` desugars as follows
      
        e { x=e1, y=e2 }
          ===>
        let { x' = e1; y' = e2 } in
        case e of
           T1 _ _ z -> T1 x' y' z
           T4 p _ _ -> T4 p y' x'
      
      The desugared expression is put into an HsExpansion, and we typecheck
      that.
      
      The full details are given in Note [Record Updates] in GHC.Tc.Gen.Expr.
      
      Fixes #2595 #3632 #10808 #10856 #16501 #18311 #18802 #21158 #21289
      
      Updates haddock submodule
      e74fc066
  21. Apr 01, 2022
    • Jakob Brünker's avatar
      Implement \cases (Proposal 302) · 32070e6c
      Jakob Brünker authored
      This commit implements proposal 302: \cases - Multi-way lambda
      expressions.
      
      This adds a new expression heralded by \cases, which works exactly like
      \case, but can match multiple apats instead of a single pat.
      
      Updates submodule haddock to support the ITlcases token.
      
      Closes #20768
      32070e6c
  22. Feb 26, 2022
  23. Jan 17, 2022
  24. Jan 03, 2022
  25. Nov 17, 2021
    • Sebastian Graf's avatar
      testsuite: Refactor pmcheck all.T · c591ab1f
      Sebastian Graf authored and Marge Bot's avatar Marge Bot committed
      c591ab1f
    • Sebastian Graf's avatar
      Pmc: Don't case split on wildcard matches (#20642) · 29086749
      Sebastian Graf authored and Marge Bot's avatar Marge Bot committed
      Since 8.10, when formatting a pattern match warning, we'd case split on a
      wildcard match such as
      ```hs
      foo :: [a] -> [a]
      foo [] = []
      foo xs = ys
        where
        (_, ys@(_:_)) = splitAt 0 xs
      -- Pattern match(es) are non-exhaustive
      -- In a pattern binding:
      --     Patterns not matched:
      --         ([], [])
      --         ((_:_), [])
      ```
      But that's quite verbose and distracts from which part of the pattern was
      actually the inexhaustive one. We'd prefer a wildcard for the first pair
      component here, like it used to be in GHC 8.8.
      
      On the other hand, case splitting is pretty handy for `-XEmptyCase` to know the
      different constructors we could've matched on:
      ```hs
      f :: Bool -> ()
      f x = case x of {}
      -- Pattern match(es) are non-exhaustive
      -- In a pattern binding:
      --     Patterns not matched:
      --         False
      --         True
      ```
      The solution is to communicate that we want a top-level case split to
      `generateInhabitingPatterns` for `-XEmptyCase`, which is exactly what
      this patch arranges. Details in `Note [Case split inhabiting patterns]`.
      
      Fixes #20642.
      29086749
  26. Nov 07, 2021
    • Sebastian Graf's avatar
      Pmc: Do inhabitation test for unlifted vars (#20631) · 56705da8
      Sebastian Graf authored and Marge Bot's avatar Marge Bot committed
      Although I thought we were already set to handle unlifted datatypes correctly,
      it appears we weren't. #20631 showed that it's wrong to assume
      `vi_bot=IsNotBot` for `VarInfo`s of unlifted types from their inception if we
      don't follow up with an inhabitation test to see if there are any habitable
      constructors left. We can't trigger the test from `emptyVarInfo`, so now we
      instead fail early in `addBotCt` for variables of unlifted types.
      
      Fixed #20631.
      56705da8
  27. Aug 15, 2021
    • sheaf's avatar
      Detect TypeError when checking for insolubility · 1e896b47
      sheaf authored and Marge Bot's avatar Marge Bot committed
      We detect insoluble Givens by making getInertInsols
      take into account TypeError constraints, on top of insoluble equalities
      such as Int ~ Bool (which it already took into account).
      
      This allows pattern matches with insoluble contexts to be reported
      as redundant (tyOracle calls tcCheckGivens which calls getInertInsols).
      
      As a bonus, we get to remove a workaround in Data.Typeable.Internal:
      we can directly use a NotApplication type family, as opposed to
      needing to cook up an insoluble equality constraint.
      
      Fixes #11503 #14141 #16377 #20180
      1e896b47
  28. Jun 03, 2021
    • Alfredo Di Napoli's avatar
      Port HsToCore messages to new infrastructure · d5b89ed4
      Alfredo Di Napoli authored and Marge Bot's avatar Marge Bot committed
      This commit converts a bunch of HsToCore (Ds) messages to use the new
      GHC's diagnostic message infrastructure. In particular the DsMessage
      type has been expanded with a lot of type constructors, each
      encapsulating a particular error and warning emitted during desugaring.
      
      Due to the fact that levity polymorphism checking can happen both at the
      Ds and at the TcRn level, a new `TcLevityCheckDsMessage` constructor has
      been added to the `TcRnMessage` type.
      d5b89ed4
  29. Apr 29, 2021
    • Ryan Scott's avatar
      Redesign withDict (formerly magicDict) · 5981ac7d
      Ryan Scott authored and Marge Bot's avatar Marge Bot committed
      This gives a more precise type signature to `magicDict` as proposed in #16646.
      In addition, this replaces the constant-folding rule for `magicDict` in
      `GHC.Core.Opt.ConstantFold` with a special case in the desugarer in
      `GHC.HsToCore.Expr.dsHsWrapped`. I have also renamed `magicDict` to `withDict`
      in light of the discussion in
      https://mail.haskell.org/pipermail/ghc-devs/2021-April/019833.html.
      All of this has the following benefits:
      
      * `withDict` is now more type safe than before. Moreover, if a user applies
        `withDict` at an incorrect type, the special-casing in `dsHsWrapped` will
        now throw an error message indicating what the user did incorrectly.
      * `withDict` can now work with classes that have multiple type arguments, such
        as `Typeable @k a`. This means that `Data.Typeable.Internal.withTypeable` can
        now be implemented in terms of `withDict`.
      * Since the special-casing for `withDict` no longer needs to match on the
        structure of the expression passed as an argument to `withDict`, it no
        longer cares about the presence or absence of `Tick`s. In effect, this
        obsoletes the fix for #19667.
      
      The new `T16646` test case demonstrates the new version of `withDict` in
      action, both in terms of `base` functions defined in terms of `withDict`
      as well as in terms of functions from the `reflection` and `singletons`
      libraries. The `T16646Fail` test case demonstrates the error message that GHC
      throws when `withDict` is applied incorrectly.
      
      This fixes #16646. By adding more tests for `withDict`, this also
      fixes #19673 as a side effect.
      5981ac7d
  30. Apr 02, 2021
  31. Mar 14, 2021
    • Sebastian Graf's avatar
      Pmc: Consider Required Constraints when guessing PatSyn arg types (#19475) · 1793ca9d
      Sebastian Graf authored and Marge Bot's avatar Marge Bot committed
      
      This patch makes `guessConLikeUnivTyArgsFromResTy` consider required
      Thetas of PatSynCons, by treating them as Wanted constraints to be
      discharged with the constraints from the Nabla's TyState and saying
      "does not match the match type" if the Wanted constraints are unsoluble.
      It calls out into a new function `GHC.Tc.Solver.tcCheckWanteds` to do
      so.
      
      In pushing the failure logic around call sites of `initTcDsForSolver`
      inside it by panicking, I realised that there was a bunch of dead code
      surrounding `pmTopMoraliseType`: I was successfully able to delete the
      `NoChange` data constructor of `TopNormaliseTypeResult`.
      
      The details are in `Note [Matching against a ConLike result type]` and
      `Note [Instantiating a ConLike].
      
      The regression test is in `T19475`. It's pretty much a fork of `T14422`
      at the moment.
      
      Co-authored-by: default avatarCale Gibbard <cgibbard@gmail.com>
      1793ca9d
  32. Mar 10, 2021
  33. Mar 07, 2021
    • Ben Gamari's avatar
      Implement BoxedRep proposal · 3e082f8f
      Ben Gamari authored
      This implements the BoxedRep proposal, refactoring the `RuntimeRep`
      hierarchy from:
      
      ```haskell
      data RuntimeRep = LiftedPtrRep | UnliftedPtrRep | ...
      ```
      
      to
      
      ```haskell
      data RuntimeRep = BoxedRep Levity | ...
      data Levity = Lifted | Unlifted
      ```
      
      Updates binary, haddock submodules.
      
      Closes #17526.
      
      Metric Increase:
          T12545
      3e082f8f
  34. Mar 05, 2021
    • cgibbard's avatar
      Bring back COMPLETE sets filtered by result TyCon (#14422) · 4cdf8b5e
      cgibbard authored and Marge Bot's avatar Marge Bot committed
      
      Commit 2a942285 dramatically simplified the implementation and improved
      the performance of COMPLETE sets while making them applicable in more
      scenarios at the same time.
      But it turned out that there was a change in semantics that (to me
      unexpectedly) broke users' expectations (see #14422): They relied on the
      "type signature" of a COMPLETE pragma to restrict the scrutinee types of
      a pattern match for which they are applicable.
      
      This patch brings back that filtering, so the semantics is the same as
      it was in GHC 9.0.
      See the updated Note [Implementation of COMPLETE pragmas].
      
      There are a few testsuite output changes (`completesig13`, `T14422`)
      which assert this change.
      
      Co-authored-by: default avatarSebastian Graf <sebastian.graf@kit.edu>
      4cdf8b5e
  35. Mar 01, 2021
    • Sebastian Graf's avatar
      Pmc: Implement `considerAccessible` (#18610) · e571eda7
      Sebastian Graf authored and Marge Bot's avatar Marge Bot committed
      Consider (`T18610`):
      ```hs
        f :: Bool -> Int
        f x = case (x, x) of
          (True,  True)  -> 1
          (False, False) -> 2
          (True,  False) -> 3 -- Warning: Redundant
      ```
      The third clause will be flagged as redundant. Nevertheless, the
      programmer might intend to keep the clause in order to avoid bitrot.
      
      After this patch, the programmer can write
      ```hs
        g :: Bool -> Int
        g x = case (x, x) of
          (True,  True)  -> 1
          (False, False) -> 2
          (True,  False) | GHC.Exts.considerAccessible -> 3 -- No warning
      ```
      And won't be bothered any longer. See also `Note [considerAccessible]`
      and the updated entries in the user's guide.
      
      Fixes #18610 and #19228.
      e571eda7
  36. Feb 27, 2021
  37. Feb 06, 2021
Loading