1. 14 Feb, 2019 1 commit
    • Simon Peyton Jones's avatar
      Make a smart mkAppTyM · 68278382
      Simon Peyton Jones authored
      This patch finally delivers on Trac #15952.  Specifically
      
      * Completely remove Note [The tcType invariant], along with
        its complicated consequences (IT1-IT6).
      
      * Replace Note [The well-kinded type invariant] with:
      
            Note [The Purely Kinded Type Invariant (PKTI)]
      
      * Instead, establish the (PKTI) in TcHsType.tcInferApps,
        by using a new function mkAppTyM when building a type
        application.  See Note [mkAppTyM].
      
      * As a result we can remove the delicate mkNakedXX functions
        entirely.  Specifically, mkNakedCastTy retained lots of
        extremly delicate Refl coercions which just cluttered
        everything up, and(worse) were very vulnerable to being
        silently eliminated by (say) substTy. This led to a
        succession of bug reports.
      
      The result is noticeably simpler to explain, simpler
      to code, and Richard and I are much more confident that
      it is correct.
      
      It does not actually fix any bugs, but it brings us closer.
      E.g. I hoped it'd fix #15918 and #15799, but it doesn't quite
      do so.  However, it makes it much easier to fix.
      
      I also did a raft of other minor refactorings:
      
      * Use tcTypeKind consistently in the type checker
      
      * Rename tcInstTyBinders to tcInvisibleTyBinders,
        and refactor it a bit
      
      * Refactor tcEqType, pickyEqType, tcEqTypeVis
        Simpler, probably more efficient.
      
      * Make zonkTcType zonk TcTyCons, at least if they have
        any free unification variables -- see zonk_tc_tycon
        in TcMType.zonkTcTypeMapper.
      
        Not zonking these TcTyCons was actually a bug before.
      
      * Simplify try_to_reduce_no_cache in TcFlatten (a lot)
      
      * Combine checkExpectedKind and checkExpectedKindX.
        And then combine the invisible-binder instantation code
        Much simpler now.
      
      * Fix a little bug in TcMType.skolemiseQuantifiedTyVar.
        I'm not sure how I came across this originally.
      
      * Fix a little bug in TyCoRep.isUnliftedRuntimeRep
        (the ASSERT was over-zealous).  Again I'm not certain
        how I encountered this.
      
      * Add a missing solveLocalEqualities in
        TcHsType.tcHsPartialSigType.
        I came across this when trying to get level numbers
        right.
      68278382
  2. 12 Feb, 2019 1 commit
    • Richard Eisenberg's avatar
      Fix #16188 · 4a4ae70f
      Richard Eisenberg authored
      There was an awful lot of zipping going on in
      canDecomposableTyConAppOK, and one of the lists being zipped
      was too short, causing the result to be too short. Easily
      fixed.
      
      Also fixes #16204 and #16225
      
      test case: typecheck/should_compile/T16188
                 typecheck/should_compile/T16204[ab]
                 typecheck/should_fail/T16204c
                 typecheck/should_compile/T16225
      4a4ae70f
  3. 17 Dec, 2018 1 commit
  4. 03 Dec, 2018 1 commit
    • Simon Peyton Jones's avatar
      Introduce tcTypeKind, and use it · 03d48526
      Simon Peyton Jones authored
      In the type checker Constraint and * are distinct; and the function
      that takes the kind of a type should respect that distinction
      (Trac #15971).
      
      This patch implements the change:
      
      * Introduce Type.tcTypeKind, and use it throughout the type
        inference engine
      
      * Add new Note [Kinding rules for types] for the kinding
        rules, especially for foralls.
      
      * Redefine
          isPredTy ty = tcIsConstraintKind (tcTypeKind ty)
        (it had a much more complicated definition before)
      
      Some miscellaneous refactoring
      
      * Get rid of TyCoRep.isTYPE, Kind.isTYPEApp,
        in favour of TyCoRep.kindRep, kindRep_maybe
      
      * Rename Type.getRuntimeRepFromKind_maybe
        to getRuntimeRep_maybe
      
      I did some spot-checks on compiler perf, and it really doesn't
      budge (as expected).
      03d48526
  5. 22 Nov, 2018 1 commit
    • David Eichmann's avatar
      Fix unused-import warnings · 6353efc7
      David Eichmann authored
      This patch fixes a fairly long-standing bug (dating back to 2015) in
      RdrName.bestImport, namely
      
         commit 9376249b
         Author: Simon Peyton Jones <simonpj@microsoft.com>
         Date:   Wed Oct 28 17:16:55 2015 +0000
      
         Fix unused-import stuff in a better way
      
      In that patch got the sense of the comparison back to front, and
      thereby failed to implement the unused-import rules described in
        Note [Choosing the best import declaration] in RdrName
      
      This led to Trac #13064 and #15393
      
      Fixing this bug revealed a bunch of unused imports in libraries;
      the ones in the GHC repo are part of this commit.
      
      The two important changes are
      
      * Fix the bug in bestImport
      
      * Modified the rules by adding (a) in
           Note [Choosing the best import declaration] in RdrName
        Reason: the previosu rules made Trac #5211 go bad again.  And
        the new rule (a) makes sense to me.
      
      In unravalling this I also ended up doing a few other things
      
      * Refactor RnNames.ImportDeclUsage to use a [GlobalRdrElt] for the
        things that are used, rather than [AvailInfo]. This is simpler
        and more direct.
      
      * Rename greParentName to greParent_maybe, to follow GHC
        naming conventions
      
      * Delete dead code RdrName.greUsedRdrName
      
      Bumps a few submodules.
      
      Reviewers: hvr, goldfire, bgamari, simonmar, jrtc27
      
      Subscribers: rwbarton, carter
      
      Differential Revision: https://phabricator.haskell.org/D5312
      6353efc7
  6. 24 Oct, 2018 2 commits
    • Simon Peyton Jones's avatar
      Don't print out undefined coercions · 7d903644
      Simon Peyton Jones authored
      A debug-print was trying to print the coercion returned
      by the flattener.  But that coercion can be undefined
      in the case of Derived constraints.  Because we might
      rewrite it with [D] a ~ ty, and there is no evidence
      for that.
      
      Solution: don't attempt to print the coercion.
      7d903644
    • Simon Peyton Jones's avatar
      Refactor the treatment of predicate types · 0faf7fd3
      Simon Peyton Jones authored
      Trac #15648 showed that GHC was a bit confused about the
      difference between the types for
      
      * Predicates
      * Coercions
      * Evidence (in the typechecker constraint solver)
      
      This patch cleans it up. See especially Type.hs
      Note [Types for coercions, predicates, and evidence]
      
      Particular changes
      
      * Coercion types (a ~# b) and (a ~#R b) are not predicate types
        (so isPredTy reports False for them) and are not implicitly
        instantiated by the type checker.  This is a real change, but
        it consistently reflects that fact that (~#) and (~R#) really
        are different from predicates.
      
      * isCoercionType is renamed to isCoVarType
      
      * During type inference, simplifyInfer, we do /not/ want to infer
        a constraint (a ~# b), because that is no longer a predicate type.
        So we 'lift' it to (a ~ b). See TcType
        Note [Lift equality constaints when quantifying]
      
      * During type inference for pattern synonyms, we need to 'lift'
        provided constraints of type (a ~# b) to (a ~ b).  See
        Note [Equality evidence in pattern synonyms] in PatSyn
      
      * But what about (forall a. Eq a => a ~# b)? Is that a
        predicate type?  No -- it does not have kind Constraint.
        Is it an evidence type?  Perhaps, but awkwardly so.
      
        In the end I decided NOT to make it an evidence type,
        and to ensure the the type inference engine never
        meets it.  This made me /simplify/ the code in
        TcCanonical.makeSuperClasses; see TcCanonical
        Note [Equality superclasses in quantified constraints]
      
        Instead I moved the special treatment for primitive
        equality to TcInteract.doTopReactOther.  See TcInteract
        Note [Looking up primitive equalities in quantified constraints]
      
        Also see Note [Evidence for quantified constraints] in Type.
      
        All this means I can have
           isEvVarType ty = isCoVarType ty || isPredTy ty
        which is nice.
      
      All in all, rather a lot of work for a small refactoring,
      but I think it's a real improvement.
      0faf7fd3
  7. 15 Sep, 2018 1 commit
    • Ningning Xie's avatar
      Coercion Quantification · ea5ade34
      Ningning Xie authored
      This patch corresponds to #15497.
      
      According to https://ghc.haskell.org/trac/ghc/wiki/DependentHaskell/Phase2,
       we would like to have coercion quantifications back. This will
      allow us to migrate (~#) to be homogeneous, instead of its current
      heterogeneous definition. This patch is (lots of) plumbing only. There
      should be no user-visible effects.
      
      An overview of changes:
      
      - Both `ForAllTy` and `ForAllCo` can quantify over coercion variables,
      but only in *Core*. All relevant functions are updated accordingly.
      - Small changes that should be irrelevant to the main task:
          1. removed dead code `mkTransAppCo` in Coercion
          2. removed out-dated Note Computing a coercion kind and
             roles in Coercion
          3. Added `Eq4` in Note Respecting definitional equality in
             TyCoRep, and updated `mkCastTy` accordingly.
          4. Various updates and corrections of notes and typos.
      - Haddock submodule needs to be changed too.
      
      Acknowledgments:
      This work was completed mostly during Ningning Xie's Google Summer
      of Code, sponsored by Google. It was advised by Richard Eisenberg,
      supported by NSF grant 1704041.
      
      Test Plan: ./validate
      
      Reviewers: goldfire, simonpj, bgamari, hvr, erikd, simonmar
      
      Subscribers: RyanGlScott, monoidal, rwbarton, carter
      
      GHC Trac Issues: #15497
      
      Differential Revision: https://phabricator.haskell.org/D5054
      ea5ade34
  8. 13 Sep, 2018 2 commits
    • Simon Peyton Jones's avatar
      Allow (~) in the head of a quantified constraints · bd76875a
      Simon Peyton Jones authored
      Since the introduction of quantified constraints, GHC has rejected
      a quantified constraint with (~) in the head, thus
        f :: (forall a. blah => a ~ ty) => stuff
      
      I am frankly dubious that this is ever useful.  But /is/ necessary for
      Coercible (representation equality version of (~)) and it does no harm
      to allow it for (~) as well.  Plus, our users are asking for it
      (Trac #15359, #15625).
      
      It was really only excluded by accident, so
      this patch lifts the restriction. See TcCanonical
      Note [Equality superclasses in quantified constraints]
      
      There are a number of wrinkles:
      
      * If the context of the quantified constraint is empty, we
        can get trouble when we get down to unboxed equality (a ~# b)
        or (a ~R# b), as Trac #15625 showed. This is even more of
        a corner case, but it produced an outright crash, so I elaborated
        the superclass machinery in TcCanonical.makeStrictSuperClasses
        to add a void argument in this case.  See
        Note [Equality superclasses in quantified constraints]
      
      * The restriction on (~) was in TcValidity.checkValidInstHead.
        In lifting the restriction I discovered an old special case for
        (~), namely
            | clas_nm `elem` [ heqTyConName, eqTyConName]
            , nameModule clas_nm /= this_mod
        This was (solely) to support the strange instance
            instance a ~~ b => a ~ b
        in Data.Type.Equality. But happily that is no longer
        with us, since
           commit f265008f
           Refactor (~) to reduce the suerpclass stack
        So I removed the special case.
      
      * I found that the Core invariants on when we could have
             co = <expr>
        were entirely not written down. (Getting this wrong ws
        the proximate source of the crash in Trac #15625.  So
      
        - Documented them better in CoreSyn
            Note [CoreSyn type and coercion invariant],
        - Modified CoreOpt and CoreLint to match
        - Modified CoreUtils.bindNonRec to match
        - Made MkCore.mkCoreLet use bindNonRec, rather
          than duplicate its logic
        - Made Simplify.rebuildCase case-to-let respect
            Note [CoreSyn type and coercion invariant],
      bd76875a
    • Simon Peyton Jones's avatar
      Delete duplicated comment line · 6bf11e67
      Simon Peyton Jones authored
      6bf11e67
  9. 03 Sep, 2018 1 commit
    • Simon Peyton Jones's avatar
      canCFunEqCan: use isTcReflexiveCo (not isTcReflCo) · 2e226a46
      Simon Peyton Jones authored
      As Trac #15577 showed, it was possible for a /homo-kinded/
      constraint to trigger the /hetero-kinded/ branch of canCFunEqCan,
      and that triggered an infinite loop.
      
      The fix is easier, but there remains a deeper questions: why is
      the flattener producing giant refexive coercions?
      2e226a46
  10. 17 Aug, 2018 1 commit
    • Joachim Breitner's avatar
      Rename SigTv to TyVarTv (#15480) · a50244c6
      Joachim Breitner authored
      because since #15050, these are no longer used in pattern SIGnatures,
      but still in other places where meta-variables should only be unified
      with TYpe VARiables.
      
      I also found mentions of `SigTv` in parts of the renamer and desugarer
      that do not seem to directly relate to `SigTv` as used in the type
      checker, but rather to uses of `forall a.` in type signatures. I renamed
      these to `ScopedTv`.
      
      Differential Revision: https://phabricator.haskell.org/D5074
      a50244c6
  11. 23 Jul, 2018 1 commit
    • Simon Peyton Jones's avatar
      Stop marking soluble ~R# constraints as insoluble · f0d27f51
      Simon Peyton Jones authored
      We had a constraint (a b ~R# Int), and were marking it as 'insoluble'.
      That's bad; it isn't.  And it caused Trac #15431. Soultion is simple.
      
      I did a tiny refactor on can_eq_app, so that it is used only for
      nominal equalities.
      f0d27f51
  12. 10 Jul, 2018 1 commit
    • Ningning Xie's avatar
      Refactor coercion rule · 55a3f855
      Ningning Xie authored
      Summary:
      The patch is an attempt on #15192.
      
      It defines a new coercion rule
      
      ```
       | GRefl Role Type MCoercion
      ```
      
      which correspondes to the typing rule
      
      ```
           t1 : k1
        ------------------------------------
        GRefl r t1 MRefl: t1 ~r t1
      
           t1 : k1       co :: k1 ~ k2
        ------------------------------------
        GRefl r t1 (MCo co) : t1 ~r t1 |> co
      ```
      
      MCoercion wraps a coercion, which might be reflexive (MRefl)
      or not (MCo co). To know more about MCoercion see #14975.
      
      We keep Refl ty as a special case for nominal reflexive coercions,
      naemly, Refl ty :: ty ~n ty.
      
      This commit is meant to be a general performance improvement,
      but there are a few regressions. See #15192, comment:13 for
      more information.
      
      Test Plan: ./validate
      
      Reviewers: bgamari, goldfire, simonpj
      
      Subscribers: rwbarton, thomie, carter
      
      GHC Trac Issues: #15192
      
      Differential Revision: https://phabricator.haskell.org/D4747
      55a3f855
  13. 22 Jun, 2018 1 commit
    • Simon Peyton Jones's avatar
      Instances in no-evidence implications · 32eb4199
      Simon Peyton Jones authored
      Trac #15290 showed that it's possible that we might attempt to use a
      quantified constraint to solve an equality in a situation where we
      don't have anywhere to put the evidence bindings.  This made GHC crash.
      
      This patch stops the crash, but still rejects the pogram.  See
      Note [Instances in no-evidence implications] in TcInteract.
      
      Finding this bug revealed another lurking bug:
      
      * An infelicity in the treatment of superclasses -- we were expanding
        them locally at the leaves, rather than at their binding site; see
        (3a) in Note [The superclass story].
      
        As a consequence, TcRnTypes.superclassesMightHelp must look inside
        implications.
      
      In more detail:
      
      * Stop the crash, by making TcInteract.chooseInstance test for
        the no-evidence-bindings case.  In that case we simply don't
        use the instance.  This entailed a slight change to the type
        of chooseInstance.
      
      * Make TcSMonad.getPendingScDicts (now renamed getPendingGivenScs)
        return only Givens from the /current level/; and make
        TcRnTypes.superClassesMightHelp look inside implications.
      
      * Refactor the simpl_loop and superclass-expansion stuff in
        TcSimplify.  The logic is much easier to understand now, and
        has less duplication.
      32eb4199
  14. 04 Jun, 2018 1 commit
    • Simon Peyton Jones's avatar
      Implement QuantifiedConstraints · 7df58960
      Simon Peyton Jones authored
      We have wanted quantified constraints for ages and, as I hoped,
      they proved remarkably simple to implement.   All the machinery was
      already in place.
      
      The main ticket is Trac #2893, but also relevant are
        #5927
        #8516
        #9123 (especially!  higher kinded roles)
        #14070
        #14317
      
      The wiki page is
        https://ghc.haskell.org/trac/ghc/wiki/QuantifiedConstraints
      which in turn contains a link to the GHC Proposal where the change
      is specified.
      
      Here is the relevant Note:
      
      Note [Quantified constraints]
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      The -XQuantifiedConstraints extension allows type-class contexts like
      this:
      
        data Rose f x = Rose x (f (Rose f x))
      
        instance (Eq a, forall b. Eq b => Eq (f b))
              => Eq (Rose f a)  where
          (Rose x1 rs1) == (Rose x2 rs2) = x1==x2 && rs1 >= rs2
      
      Note the (forall b. Eq b => Eq (f b)) in the instance contexts.
      This quantified constraint is needed to solve the
       [W] (Eq (f (Rose f x)))
      constraint which arises form the (==) definition.
      
      Here are the moving parts
        * Language extension {-# LANGUAGE QuantifiedConstraints #-}
          and add it to ghc-boot-th:GHC.LanguageExtensions.Type.Extension
      
        * A new form of evidence, EvDFun, that is used to discharge
          such wanted constraints
      
        * checkValidType gets some changes to accept forall-constraints
          only in the right places.
      
        * Type.PredTree gets a new constructor ForAllPred, and
          and classifyPredType analyses a PredType to decompose
          the new forall-constraints
      
        * Define a type TcRnTypes.QCInst, which holds a given
          quantified constraint in the inert set
      
        * TcSMonad.InertCans gets an extra field, inert_insts :: [QCInst],
          which holds all the Given forall-constraints.  In effect,
          such Given constraints are like local instance decls.
      
        * When trying to solve a class constraint, via
          TcInteract.matchInstEnv, use the InstEnv from inert_insts
          so that we include the local Given forall-constraints
          in the lookup.  (See TcSMonad.getInstEnvs.)
      
        * topReactionsStage calls doTopReactOther for CIrredCan and
          CTyEqCan, so they can try to react with any given
          quantified constraints (TcInteract.matchLocalInst)
      
        * TcCanonical.canForAll deals with solving a
          forall-constraint.  See
             Note [Solving a Wanted forall-constraint]
             Note [Solving a Wanted forall-constraint]
      
        * We augment the kick-out code to kick out an inert
          forall constraint if it can be rewritten by a new
          type equality; see TcSMonad.kick_out_rewritable
      
      Some other related refactoring
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      
      * Move SCC on evidence bindings to post-desugaring, which fixed
        #14735, and is generally nicer anyway because we can use
        existing CoreSyn free-var functions.  (Quantified constraints
        made the free-vars of an ev-term a bit more complicated.)
      
      * In LookupInstResult, replace GenInst with OneInst and NotSure,
        using the latter for multiple matches and/or one or more
        unifiers
      7df58960
  15. 23 May, 2018 1 commit
    • Simon Peyton Jones's avatar
      Use dischargeFunEq consistently · a32c8f75
      Simon Peyton Jones authored
      Trac #15122 turned out to be interesting.
      
      * Were calling dischargeFmv in three places.
      
      * In all three cases we dealt with the Given case
        separately.
      
      * In two of the three cases the Given code was right,
        (albeit duplicated).
      
      * In the third case (in TcCanonical.canCFunEqCan), we had
           ; case flav of
               Given -> return () -- nothing more to do.
        which was utterly wrong.
      
      The solution is easy: move the Given-case handling into
      dischargeFmv (now reenamed dischargeFunEq), and delete it
      from the call sites.
      
      Result: less code, easier to understand (dischargeFunEq handles
      all three cases, not just two out of three), and Trac #15122 is fixed.
      a32c8f75
  16. 18 May, 2018 1 commit
    • Simon Peyton Jones's avatar
      Orient TyVar/TyVar equalities with deepest on the left · 2bbdd00c
      Simon Peyton Jones authored
      Trac #15009 showed that, for Given TyVar/TyVar equalities, we really
      want to orient them with the deepest-bound skolem on the left. As it
      happens, we also want to do the same for Wanteds, but for a different
      reason (more likely to be touchable).  Either way, deepest wins:
      see TcUnify Note [Deeper level on the left].
      
      This observation led me to some significant changes:
      
      * A SkolemTv already had a TcLevel, but the level wasn't really being
        used.   Now it is!
      
      * I updated added invariant (SkolInf) to TcType
        Note [TcLevel and untouchable type variables], documenting that
        the level number of all the ic_skols should be the same as the
        ic_tclvl of the implication
      
      * FlatSkolTvs and FlatMetaTvs previously had a dummy level-number of
        zero, which messed the scheme up.   Now they get a level number the
        same way as all other TcTyVars, instead of being a special case.
      
      * To make sure that FlatSkolTvs and FlatMetaTvs are untouchable (which
        was previously done via their magic zero level) isTouchableMetaTyVar
        just tests for those two cases.
      
      * TcUnify.swapOverTyVars is the crucial orientation function; see the
        new Note [TyVar/TyVar orientation].  I completely rewrote this function,
        and it's now much much easier to understand.
      
      I ended up doing some related refactoring, of course
      
      * I noticed that tcImplicitTKBndrsX and tcExplicitTKBndrsX were doing
        a lot of useless work in the case where there are no skolems; I
        added a fast-patch
      
      * Elminate the un-used tcExplicitTKBndrsSig; and thereby get rid of
        the higher-order parameter to tcExpliciTKBndrsX.
      
      * Replace TcHsType.emitTvImplication with TcUnify.checkTvConstraints,
        by analogy with TcUnify.checkConstraints.
      
      * Inline TcUnify.buildImplication into its only call-site in
        TcUnify.checkConstraints
      
      * TcS.buildImplication becomes TcS.CheckConstraintsTcS, with a
        simpler API
      
      * Now that we have NoEvBindsVar we have no need of termEvidenceAllowed;
        nuke the latter, adding Note [No evidence bindings] to TcEvidence.
      2bbdd00c
  17. 20 Apr, 2018 1 commit
    • Tobias Dammers's avatar
      Caching coercion roles in NthCo and coercionKindsRole refactoring · 2fbe0b51
      Tobias Dammers authored
      While addressing nonlinear behavior related to coercion roles,
      particularly `NthCo`, we noticed that coercion roles are recalculated
      often even though they should be readily at hand already in most cases.
      This patch adds a `Role` to the `NthCo` constructor so that we can cache
      them rather than having to recalculate them on the fly.
      https://ghc.haskell.org/trac/ghc/ticket/11735#comment:23 explains the
      approach.
      
      Performance improvement over GHC HEAD, when compiling Grammar.hs (see below):
      
      GHC 8.2.1:
      ```
      ghc Grammar.hs  176.27s user 0.23s system 99% cpu 2:56.81 total
      ```
      
      before patch (but with other optimizations applied):
      ```
      ghc Grammar.hs -fforce-recomp  175.77s user 0.19s system 100% cpu 2:55.78 total
      ```
      
      after:
      ```
      ../../ghc/inplace/bin/ghc-stage2 Grammar.hs  10.32s user 0.17s system 98% cpu 10.678 total
      ```
      
      Introduces the following regressions:
      
      - perf/compiler/parsing001 (possibly false positive)
      - perf/compiler/T9872
      - perf/compiler/haddock.base
      
      Reviewers: goldfire, bgamari, simonpj
      
      Reviewed By: simonpj
      
      Subscribers: rwbarton, thomie, carter
      
      GHC Trac Issues: #11735
      
      Differential Revision: https://phabricator.haskell.org/D4394
      2fbe0b51
  18. 26 Mar, 2018 1 commit
    • Richard Eisenberg's avatar
      Fix #12919 by making the flattener homegeneous. · e3dbb44f
      Richard Eisenberg authored
      This changes a key invariant of the flattener. Previously,
      flattening a type meant flattening its kind as well. But now,
      flattening is always homogeneous -- that is, the kind of the
      flattened type is the same as the kind of the input type.
      This is achieved by various wizardry in the TcFlatten.flatten_many
      function, as described in Note [flatten_many].
      
      There are several knock-on effects, including some refactoring
      in the canonicalizer to take proper advantage of the flattener's
      changed behavior. In particular, the tyvar case of can_eq_nc' no
      longer needs to take casts into account.
      
      Another effect is that flattening a tyconapp might change it
      into a casted tyconapp. This might happen if the result kind
      of the tycon contains a variable, and that variable changes
      during flattening. Because the flattener is homogeneous, it tacks
      on a cast to keep the tyconapp kind the same. However, this
      is problematic when flattening CFunEqCans, which need to have
      an uncasted tyconapp on the LHS and must remain homogeneous.
      The solution is a more involved canCFunEqCan, described in
      Note [canCFunEqCan].
      
      This patch fixes #13643 (as tested in typecheck/should_compile/T13643)
      and the panic in typecheck/should_compile/T13822 (as reported in #14024).
      Actually, there were two bugs in T13822: the first was just some
      incorrect logic in tryFill (part of the unflattener) -- also fixed
      in this patch -- and the other was the main bug fixed in this ticket.
      
      The changes in this patch exposed a long-standing flaw in OptCoercion,
      in that breaking apart an AppCo sometimes has unexpected effects on
      kinds. See new Note [EtaAppCo] in OptCoercion, which explains the
      problem and fix.
      
      Also here is a reversion of the major change in
      09bf135a, affecting ctEvCoercion.
      It turns out that making the flattener homogeneous changes the
      invariants on the algorithm, making the change in that patch
      no longer necessary.
      
      This patch also fixes:
        #14038 (dependent/should_compile/T14038)
        #13910 (dependent/should_compile/T13910)
        #13938 (dependent/should_compile/T13938)
        #14441 (typecheck/should_compile/T14441)
        #14556 (dependent/should_compile/T14556)
        #14720 (dependent/should_compile/T14720)
        #14749 (typecheck/should_compile/T14749)
      
      Sadly, this patch negatively affects performance of type-family-
      heavy code. The following patch fixes these performance degradations.
      However, the performance fixes are somewhat invasive and so I've
      kept them as a separate patch, labeling this one as [skip ci] so
      that validation doesn't fail on the performance cases.
      e3dbb44f
  19. 08 Feb, 2018 1 commit
    • Simon Peyton Jones's avatar
      Fix isDroppableCt (Trac #14763) · 6edafe3b
      Simon Peyton Jones authored
      When finishing up an implication constraint, it's a bit tricky to
      decide which Derived constraints to retain (for error reporting) and
      which to discard.  I got this wrong in commit
         f20cf982
         (Remove wc_insol from WantedConstraints)
      
      The particular problem in Trac #14763 was that we were reporting as an
      error a fundep-generated constraint
        (ex ~ T)
      where 'ex' is an existentially-bound variable in a pattern match.
      But this isn't really an error at all.
      
      This patch fixes the problem. Indeed, since I had to understand
      this rather tricky code, I took the opportunity to clean it up
      and document better.  See
        isDroppableCt :: Ct -> Bool
      and Note [Dropping derived constraints]
      
      I also removed wl_deriv altogether from the WorkList data type.  It
      was there in the hope of gaining efficiency by not even processing
      lots of derived constraints, but it has turned out that most derived
      constraints (notably equalities) must be processed anyway; see
      Note [Prioritise equalities] in TcSMonad.
      
      The two are coupled because to decide which constraints to put in
      wl_deriv I was using another variant of isDroppableCt.  Now it's much
      simpler -- and perhaps even more efficient too.
      6edafe3b
  20. 07 Feb, 2018 1 commit
    • Simon Peyton Jones's avatar
      Fix solveOneFromTheOther for RecursiveSuperclasses · 65069806
      Simon Peyton Jones authored
      This patch fixes the redundant superclass expansion
      in Trac #14774.
      
      The main change is to fix TcInterac.solveOneFromTheOther, so
      that it does not prefer a work-item with a binding if that binding
      transitively depends on the inert item we are comparing it with.
      
      Explained in Note [Replacement vs keeping] in TcInert, esp
      item (c) of the "Constraints coming from the same level" part.
      
      To make this work I refactored out a new function
      TcEvidence.findNeededEvVars, which was previously buried
      inside TcSimplify.neededEvVars.
      
      I added quite a few more comments and signposts about superclass
      expansion.
      65069806
  21. 01 Feb, 2018 1 commit
    • Simon Peyton Jones's avatar
      Experiment with eliminating the younger tyvar · 618a805b
      Simon Peyton Jones authored
      This patch is comments only, plus a minor refactor that
      does not change behaviour.
      
      It just records an idea I had for reducing kick-out in the type
      constraint-solver.
      
      See Note [Eliminate younger unification variables] in TcUnify.
      
      Sadly, it didn't improve perf, so I've put it aside, leaving
      some breadcrumbs for future generations of GHC hackers.
      618a805b
  22. 26 Jan, 2018 1 commit
    • Joachim Breitner's avatar
      Turn EvTerm (almost) into CoreExpr (#14691) · 0e022e56
      Joachim Breitner authored
      Ideally, I'd like to do
      
          type EvTerm = CoreExpr
      
      and the type checker builds the evidence terms as it goes. This failed,
      becuase the evidence for `Typeable` refers to local identifiers that are
      added *after* the typechecker solves constraints. Therefore, `EvTerm`
      stays a data type with two constructors: `EvExpr` for `CoreExpr`
      evidence, and `EvTypeable` for the others.
      
      Delted `Note [Memoising typeOf]`, its reference (and presumably
      relevance) was removed in 8fa4bf9a.
      
      Differential Revision: https://phabricator.haskell.org/D4341
      0e022e56
  23. 21 Dec, 2017 1 commit
    • Simon Peyton Jones's avatar
      Refactor coercion holes · a492af06
      Simon Peyton Jones authored
      In fixing Trac #14584 I found that it would be /much/ more
      convenient if a "hole" in a coercion (much like a unification
      variable in a type) acutally had a CoVar associated with it
      rather than just a Unique.  Then I can ask what the free variables
      of a coercion is, and get a set of CoVars including those
      as-yet-un-filled in holes.
      
      Once that is done, it makes no sense to stuff coercion holes
      inside UnivCo.  They were there before so we could know the
      kind and role of a "hole" coercion, but once there is a CoVar
      we can get that info from the CoVar.  So I removed HoleProv
      from UnivCoProvenance and added HoleCo to Coercion.
      
      In summary:
      
      * Add HoleCo to Coercion and remove HoleProv from UnivCoProvanance
      
      * Similarly in IfaceCoercion
      
      * Make CoercionHole have a CoVar in it, not a Unique
      
      * Make tyCoVarsOfCo return the free coercion-hole variables
        as well as the ordinary free CoVars.  Similarly, remember
        to zonk the CoVar in a CoercionHole
      
      We could go further, and remove CoercionHole as a distinct type
      altogther, just collapsing it into HoleCo.  But I have not done
      that yet.
      a492af06
  24. 19 Dec, 2017 1 commit
  25. 30 Oct, 2017 2 commits
  26. 20 Oct, 2017 1 commit
  27. 18 Oct, 2017 2 commits
    • Simon Peyton Jones's avatar
      Better solving for representational equalities · 5a66d574
      Simon Peyton Jones authored
      This patch adds a bit of extra solving power for representational
      equality constraints to fix Trac #14333
      
      The main changes:
      
      * Fix a buglet in TcType.isInsolubleOccursCheck which wrongly
        reported a definite occurs-check error for (a ~R# b a)
      
      * Get rid of TcSMonad.emitInsolubles.  It had an ad-hoc duplicate-removal
        piece that is better handled in interactIrred, now that insolubles
        are Irreds.
      
        We need a little care to keep inert_count (which does not include
        insolubles) accurate.
      
      * Refactor TcInteract.solveOneFromTheOther, to return a much simpler
        type.  It was just over-complicated before.
      
      * Make TcInteract.interactIrred look for constraints that match
        either way around, in TcInteract.findMatchingIrreds
      
      This wasn't hard and it cleaned up quite a bit of code.
      5a66d574
    • Simon Peyton Jones's avatar
      Don't deeply expand insolubles · 74cd1be0
      Simon Peyton Jones authored
      Trac #13450 went bananas if we expand insoluble constraints.
      Better just to leave them un-expanded.
      
      I'm not sure in detail about why it goes so badly wrong; but
      regardless, the less we mess around with insoluble contraints
      the better the error messages will be.
      74cd1be0
  28. 11 Oct, 2017 1 commit
    • Simon Peyton Jones's avatar
      Remove wc_insol from WantedConstraints · f20cf982
      Simon Peyton Jones authored
      This patch is a pure refactoring, which I've wanted to do for
      some time.  The main payload is
      
      * Remove the wc_insol field from WantedConstraints;
        instead put all the insolubles in wc_simple
      
      * Remove inert_insols from InertCans
        Instead put all the insolubles in inert_irreds
      
      * Add a cc_insol flag to CIrredCan, to record that
        the constraint is definitely insoluble
      
      Reasons
      
      * Quite a bit of code gets slightly simpler
      * Fewer concepts to keep separate
      * Insolubles don't happen at all in production code that is
        just being recompiled, so previously there was a lot of
        moving-about of empty sets
      
      A couple of error messages acutally improved.
      f20cf982
  29. 25 Sep, 2017 1 commit
    • Simon Peyton Jones's avatar
      Fix solving of implicit parameter constraints · abed9bf5
      Simon Peyton Jones authored
      Trac #14218 showed that we were not solving implicit-parameter
      constraints correctly.  In particular,
      
      - A tuple constraint could "hide" an implicit-parameter wanted
        constraint, and that in turn could that we solved it from the
        wrong implicit-parameter binding.
      
      - As a special case the HasCallStack constraint (which is just
        short for (IP "callStack" CallStack), was getting mis-solved.
      
      The big change is to arrange that, in TcSMonad.findDict when looking
      for a dictionary, either when looking for a matching inert or solved
      dictionary, we fail for
      
        - Tuples that are hiding implicit parameters
          See Note [Tuples hiding implicit parameters]
      
        - HasCallStack constraints where we have not yet pushed
          on the call-site info
          See Note [Solving CallStack constraints]
      
      I also did a little refactoring
      
      * Move naturallyCoherentClass from Class to TcInteract, its sole
        use site.  Class.hs seems like the wrong place.  (And I also
        do not understand the reason that we need the eq/Coercible/
        Typable stuff in this predicate, but I'll tackle that separately.)
      
      * Move the code that pushes call-site info onto a call stack
        from the "interact" part to the "canonicalise" part of the solver.
      abed9bf5
  30. 19 Sep, 2017 1 commit
    • Herbert Valerio Riedel's avatar
      compiler: introduce custom "GhcPrelude" Prelude · f63bc730
      Herbert Valerio Riedel authored
      This switches the compiler/ component to get compiled with
      -XNoImplicitPrelude and a `import GhcPrelude` is inserted in all
      modules.
      
      This is motivated by the upcoming "Prelude" re-export of
      `Semigroup((<>))` which would cause lots of name clashes in every
      modulewhich imports also `Outputable`
      
      Reviewers: austin, goldfire, bgamari, alanz, simonmar
      
      Reviewed By: bgamari
      
      Subscribers: goldfire, rwbarton, thomie, mpickering, bgamari
      
      Differential Revision: https://phabricator.haskell.org/D3989
      f63bc730
  31. 28 Jul, 2017 1 commit
    • Simon Peyton Jones's avatar
      Fix ASSERT failure in tc269 · b1317a35
      Simon Peyton Jones authored
      This ASSERT failure (in substTy) was reported in Trac #14024.
      
      This patch gets the in-scope set right.
      
      (Does not fix tests T13822 or T13594.)
      b1317a35
  32. 27 Jul, 2017 3 commits
    • Richard Eisenberg's avatar
      Fix #12176 by being a bit more careful instantiating. · 1696dbf4
      Richard Eisenberg authored
      Previously, looking up a TyCon that said "no" to mightBeUnsaturated
      would then instantiate all of its invisible binders. But this is
      wrong for vanilla type synonyms, whose RHS kind might legitimately
      start with invisible binders. So a little more care is taken now,
      only to instantiate those invisible binders that need to be (so that
      the TyCon isn't unsaturated).
      1696dbf4
    • Richard Eisenberg's avatar
      Track visibility in TypeEqOrigin · fb752133
      Richard Eisenberg authored
      A type equality error can arise from a mismatch between
      *invisible* arguments just as easily as from visible arguments.
      But we should really prefer printing out errors from visible
      arguments over invisible ones. Suppose we have a mismatch between
      `Proxy Int` and `Proxy Maybe`. Would you rather get an error
      between `Int` and `Maybe`? Or between `*` and `* -> *`? I thought
      so, too.
      
      There is a fair amount of plumbing with this one, but I think
      it's worth it.
      
      This commit introduces a performance regression in test
      perf/compiler/T5631. The cause of the regression is not the
      new visibility stuff, directly: it's due to a change from
      zipWithM to zipWith3M in TcUnify. To my surprise, zipWithM
      is nicely optimized (it fuses away), but zipWith3M is not.
      There are other examples of functions that could be made faster,
      so I've posted a separate ticket, #14037, to track these
      improvements. For now, I've accepted the small (6.6%) regression.
      fb752133
    • Richard Eisenberg's avatar
      Improve error messages around kind mismatches. · 8e15e3d3
      Richard Eisenberg authored
      Previously, when canonicalizing (or unifying, in uType) a
      heterogeneous equality, we emitted a kind equality and used the
      resulting coercion to cast one side of the heterogeneous equality.
      
      While sound, this led to terrible error messages. (See the bugs
      listed below.) The problem is that using the coercion built from
      the emitted kind equality is a bit like a wanted rewriting a wanted.
      The solution is to keep heterogeneous equalities as irreducible.
      
      See Note [Equalities with incompatible kinds] in TcCanonical.
      
      This commit also removes a highly suspicious switch to FM_SubstOnly
      when flattening in the kinds of a type variable. I have no idea
      why this was there, other than as a holdover from pre-TypeInType.
      I've not left a Note because there is simply no reason I can conceive
      of that the FM_SubstOnly should be there.
      
      One challenge with this patch is that the emitted derived equalities
      might get emitted several times: when a heterogeneous equality is
      in an implication and then gets floated out from the implication,
      the Derived is present both in and out of the implication. This
      causes a duplicate error message. (Test case:
      typecheck/should_fail/T7368) Solution: track the provenance of
      Derived constraints and refuse to float out a constraint that has
      an insoluble Derived.
      
      Lastly, this labels one test (dependent/should_fail/RAE_T32a)
      as expect_broken, because the problem is really #12919. The
      different handling of constraints in this patch exposes the error.
      
      This fixes bugs #11198, #12373, #13530, and #13610.
      
      test cases:
      typecheck/should_fail/{T8262,T8603,tcail122,T12373,T13530,T13610}
      8e15e3d3
  33. 20 Jul, 2017 1 commit
  34. 28 Jun, 2017 1 commit
    • Simon Peyton Jones's avatar
      Fix constraint solving for forall-types · fae672f6
      Simon Peyton Jones authored
      Trac #13879 showed that when we were trying to solve
      
        (forall z1 (y1::z1). ty1)  ~  (forall z2 (y2:z2). ty2)
      
      we'd end up spitting out z1~z2 with no binding site for them.
      Those kind equalities need to be inside the implication.
      
      I ended up re-factoring the code for solving forall-equalities.
      It's quite nice now.
      fae672f6