1. 19 Aug, 2019 1 commit
  2. 19 Jul, 2019 1 commit
  3. 09 Jul, 2019 1 commit
    • Ryan Scott's avatar
      Use an empty data type in TTG extension constructors (#15247) · 6a03d77b
      Ryan Scott authored
      To avoid having to `panic` any time a TTG extension constructor is
      consumed, this MR introduces an uninhabited 'NoExtCon' type and uses
      that in every extension constructor's type family instance where it
      is appropriate. This also introduces a 'noExtCon' function which
      eliminates a 'NoExtCon', much like 'Data.Void.absurd' eliminates
      a 'Void'.
      I also renamed the existing `NoExt` type to `NoExtField` to better
      distinguish it from `NoExtCon`. Unsurprisingly, there is a lot of
      code churn resulting from this.
      Bumps the Haddock submodule. Fixes #15247.
  4. 05 Jul, 2019 1 commit
  5. 21 Jun, 2019 1 commit
    • Matthías Páll Gissurarson's avatar
      Add HoleFitPlugins and RawHoleFits · c311277b
      Matthías Páll Gissurarson authored
      This patch adds a new kind of plugin, Hole fit plugins. These plugins
      can change what candidates are considered when looking for valid hole
      fits, and add hole fits of their own. The type of a plugin is relatively
      type FitPlugin = TypedHole -> [HoleFit] -> TcM [HoleFit]
      type CandPlugin = TypedHole -> [HoleFitCandidate] -> TcM [HoleFitCandidate]
      data HoleFitPlugin = HoleFitPlugin { candPlugin :: CandPlugin
                                         , fitPlugin :: FitPlugin }
      data TypedHole = TyH { tyHRelevantCts :: Cts
                             -- ^ Any relevant Cts to the hole
                           , tyHImplics :: [Implication]
                             -- ^ The nested implications of the hole with the
                             --   innermost implication first.
                           , tyHCt :: Maybe Ct
                             -- ^ The hole constraint itself, if available.
      This allows users and plugin writers to interact with the candidates and
      fits as they wish, even going as far as to allow them to reimplement the
      current functionality (since `TypedHole` contains all the relevant
      As an example, consider the following plugin:
      module HolePlugin where
      import GhcPlugins
      import TcHoleErrors
      import Data.List (intersect, stripPrefix)
      import RdrName (importSpecModule)
      import TcRnTypes
      import System.Process
      plugin :: Plugin
      plugin = defaultPlugin { holeFitPlugin = hfp, pluginRecompile = purePlugin }
      hfp :: [CommandLineOption] -> Maybe HoleFitPluginR
      hfp opts = Just (fromPureHFPlugin $ HoleFitPlugin (candP opts) (fp opts))
      toFilter :: Maybe String -> Maybe String
      toFilter = flip (>>=) (stripPrefix "_module_")
      replace :: Eq a => a -> a -> [a] -> [a]
      replace match repl str = replace' [] str
          replace' sofar (x:xs) | x == match = replace' (repl:sofar) xs
          replace' sofar (x:xs) = replace' (x:sofar) xs
          replace' sofar [] = reverse sofar
      -- | This candidate plugin filters the candidates by module,
      --   using the name of the hole as module to search in
      candP :: [CommandLineOption] -> CandPlugin
      candP _ hole cands =
        do let he = case tyHCt hole of
                      Just (CHoleCan _ h) -> Just (occNameString $ holeOcc h)
                      _ -> Nothing
           case toFilter he of
              Just undscModName -> do let replaced = replace '_' '.' undscModName
                                      let res = filter (greNotInOpts [replaced]) cands
                                      return $ res
              _ -> return cands
        where greNotInOpts opts (GreHFCand gre)  = not $ null $ intersect (inScopeVia gre) opts
              greNotInOpts _ _ = True
              inScopeVia = map (moduleNameString . importSpecModule) . gre_imp
      -- Yes, it's pretty hacky, but it is just an example :)
      searchHoogle :: String -> IO [String]
      searchHoogle ty = lines <$> (readProcess "hoogle" [(show ty)] [])
      fp :: [CommandLineOption] -> FitPlugin
      fp ("hoogle":[]) hole hfs =
          do dflags <- getDynFlags
             let tyString = showSDoc dflags . ppr . ctPred <$> tyHCt hole
             res <- case tyString of
                      Just ty -> liftIO $ searchHoogle ty
                      _ -> return []
             return $ (take 2 $ map (RawHoleFit . text . ("Hoogle says: " ++)) res) ++ hfs
      fp _ _ hfs = return hfs
      with this plugin available, you can compile the following file
      {-# OPTIONS -fplugin=HolePlugin -fplugin-opt=HolePlugin:hoogle #-}
      module Main where
      import Prelude hiding (head, last)
      import Data.List (head, last)
      t :: [Int] -> Int
      t = _module_Prelude
      g :: [Int] -> Int
      g = _module_Data_List
      main :: IO ()
      main = print $ t [1,2,3]
      and get the following output:
      Main.hs:14:5: error:
          • Found hole: _module_Prelude :: [Int] -> Int
            Or perhaps ‘_module_Prelude’ is mis-spelled, or not in scope
          • In the expression: _module_Prelude
            In an equation for ‘t’: t = _module_Prelude
          • Relevant bindings include
              t :: [Int] -> Int (bound at Main.hs:14:1)
            Valid hole fits include
              Hoogle says: GHC.List length :: [a] -> Int
              Hoogle says: GHC.OldList length :: [a] -> Int
              t :: [Int] -> Int (bound at Main.hs:14:1)
              g :: [Int] -> Int (bound at Main.hs:17:1)
              length :: forall (t :: * -> *) a. Foldable t => t a -> Int
                with length @[] @Int
                (imported from ‘Prelude’ at Main.hs:5:1-34
                 (and originally defined in ‘Data.Foldable’))
              maximum :: forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
                with maximum @[] @Int
                (imported from ‘Prelude’ at Main.hs:5:1-34
                 (and originally defined in ‘Data.Foldable’))
              (Some hole fits suppressed; use -fmax-valid-hole-fits=N or -fno-max-valid-hole-fits)
      14 | t = _module_Prelude
         |     ^^^^^^^^^^^^^^^
      Main.hs:17:5: error:
          • Found hole: _module_Data_List :: [Int] -> Int
            Or perhaps ‘_module_Data_List’ is mis-spelled, or not in scope
          • In the expression: _module_Data_List
            In an equation for ‘g’: g = _module_Data_List
          • Relevant bindings include
              g :: [Int] -> Int (bound at Main.hs:17:1)
            Valid hole fits include
              Hoogle says: GHC.List length :: [a] -> Int
              Hoogle says: GHC.OldList length :: [a] -> Int
              g :: [Int] -> Int (bound at Main.hs:17:1)
              head :: forall a. [a] -> a
                with head @Int
                (imported from ‘Data.List’ at Main.hs:7:19-22
                 (and originally defined in ‘GHC.List’))
              last :: forall a. [a] -> a
                with last @Int
                (imported from ‘Data.List’ at Main.hs:7:25-28
                 (and originally defined in ‘GHC.List’))
      17 | g = _module_Data_List
      This relatively simple plugin has two functions, as an example of what
      is possible to do with hole fit plugins. The candidate plugin starts by
      filtering the candidates considered by module, indicated by the name of
      the hole (`_module_Data_List`). The second function is in the fit
      plugin, where the plugin invokes a local hoogle instance to search by
      the type of the hole.
      By adding the `RawHoleFit` type, we can also allow these completely free
      suggestions, used in the plugin above to display fits found by Hoogle.
      Additionally, the `HoleFitPluginR` wrapper can be used for plugins to
      maintain state between invocations, which can be used to speed up
      invocation of plugins that have expensive initialization.
      -- | HoleFitPluginR adds a TcRef to hole fit plugins so that plugins can
      -- track internal state. Note the existential quantification, ensuring that
      -- the state cannot be modified from outside the plugin.
      data HoleFitPluginR = forall s. HoleFitPluginR
        { hfPluginInit :: TcM (TcRef s)
          -- ^ Initializes the TcRef to be passed to the plugin
        , hfPluginRun :: TcRef s -> HoleFitPlugin
          -- ^ The function defining the plugin itself
        , hfPluginStop :: TcRef s -> TcM ()
          -- ^ Cleanup of state, guaranteed to be called even on error
      Of course, the syntax here is up for debate, but hole fit plugins allow
      us to experiment relatively easily with ways to interact with
      typed-holes without having to dig deep into GHC.
      Reviewers: bgamari
      Subscribers: rwbarton, carter
      Differential Revision: https://phabricator.haskell.org/D5373
  6. 20 Jun, 2019 2 commits
    • Simon Peyton Jones's avatar
      Comments and tiny refactor · 3ae23992
      Simon Peyton Jones authored
      * Added Note [Quantified varaibles in partial type signatures]
        in TcRnTypes
      * Kill dVarSetElemsWellScoped; it was only called in
        one function, quantifyTyVars.  I inlined it because it
        was only scopedSort . dVarSetElems
      * Kill Type.tyCoVarsOfBindersWellScoped, never called.
    • Simon Peyton Jones's avatar
      Fix typechecking of partial type signatures · 48fb3482
      Simon Peyton Jones authored
      Partial type sigs had grown hair.  tcHsParialSigType was
      doing lots of unnecessary work, and tcInstSig was cloning it
      unnecessarily -- and the result didn't even work: #16728.
      This patch cleans it all up, described by TcHsType
        Note [Checking parital type signatures]
      I basically just deleted code... but very carefully!
      Some refactoring along the way
      * Distinguish more explicintly between "anonymous" wildcards "_"
        and "named" wildcards "_a".  I changed the names of a number
        of functions to make this distinction much more apparent.
      The patch also revealed that the code in `TcExpr`
      that implements the special typing rule for `($)` was wrong.
      It called `getRuntimeRep` in a situation where where was no
      particular reason to suppose that the thing had kind `TYPE r`.
      This caused a crash in typecheck/should_run/T10846.
      The fix was easy, and actually simplifies the code in `TcExpr`
      quite a bit.  Hooray.
  7. 12 Jun, 2019 1 commit
  8. 09 Jun, 2019 1 commit
    • Richard Eisenberg's avatar
      Fix #16517 by bumping the TcLevel for method sigs · a22e51ea
      Richard Eisenberg authored
      There were actually two bugs fixed here:
      1. candidateQTyVarsOfType needs to be careful that it does not
         try to zap metavariables from an outer scope as "naughty"
         quantification candidates. This commit adds a simple check
         to avoid doing so.
      2. We weren't bumping the TcLevel in kcHsKindSig, which was used
         only for class method sigs. This mistake led to the acceptance
           class C a where
             meth :: forall k. Proxy (a :: k) -> ()
         Note that k is *locally* quantified. This patch fixes the
         problem by using tcClassSigType, which correctly bumps the
         level. It's a bit inefficient because tcClassSigType does other
         work, too, but it would be tedious to repeat much of the code
         there with only a few changes. This version works well and is
      And, while updating comments, etc., I noticed that tcRnType was
      missing a pushTcLevel, leading to #16767, which this patch also
      fixes, by bumping the level. In the refactoring here, I also
      use solveEqualities. This initially failed ghci/scripts/T15415,
      but that was fixed by teaching solveEqualities to respect
      This patch also cleans up some Notes around error generation that
      came up in conversation.
      Test case: typecheck/should_fail/T16517, ghci/scripts/T16767
  9. 07 Jun, 2019 1 commit
    • Sebastian Graf's avatar
      TmOracle: Replace negative term equalities by refutable PmAltCons · e963beb5
      Sebastian Graf authored
      The `PmExprEq` business was a huge hack and was at the same time vastly
      too powerful and not powerful enough to encode negative term equalities,
      i.e. facts of the form "forall y. x ≁ Just y".
      This patch introduces the concept of 'refutable shapes': What matters
      for the pattern match checker is being able to encode knowledge of the
      kind "x can no longer be the literal 5". We encode this knowledge in a
      `PmRefutEnv`, mapping a set of newly introduced `PmAltCon`s (which are
      just `PmLit`s at the moment) to each variable denoting above
      So, say we have `x ≁ 42 ∈ refuts` in the term oracle context and
      try to solve an equality like `x ~ 42`. The entry in the refutable
      environment will immediately lead to a contradiction.
      This machinery renders the whole `PmExprEq` and `ComplexEq` business
      unnecessary, getting rid of a lot of (mostly dead) code.
      See the Note [Refutable shapes] in TmOracle for a place to start.
      Metric Decrease:
  10. 03 May, 2019 1 commit
    • Vladislav Zavialov's avatar
      Pattern/expression ambiguity resolution · 52fc2719
      Vladislav Zavialov authored
      This patch removes 'EWildPat', 'EAsPat', 'EViewPat', and 'ELazyPat'
      from 'HsExpr' by using the ambiguity resolution system introduced
      earlier for the command/expression ambiguity.
      Problem: there are places in the grammar where we do not know whether we
      are parsing an expression or a pattern, for example:
      	do { Con a b <- x } -- 'Con a b' is a pattern
      	do { Con a b }      -- 'Con a b' is an expression
      Until we encounter binding syntax (<-) we don't know whether to parse
      'Con a b' as an expression or a pattern.
      The old solution was to parse as HsExpr always, and rejig later:
      	checkPattern :: LHsExpr GhcPs -> P (LPat GhcPs)
      This meant polluting 'HsExpr' with pattern-related constructors. In
      other words, limitations of the parser were affecting the AST, and all
      other code (the renamer, the typechecker) had to deal with these extra
      We fix this abstraction leak by parsing into an overloaded
      	class DisambECP b where ...
      	newtype ECP = ECP { runECP_PV :: forall b. DisambECP b => PV (Located b) }
      See Note [Ambiguous syntactic categories] for details.
      Now the intricacies of parsing have no effect on the hsSyn AST when it
      comes to the expression/pattern ambiguity.
  11. 25 Mar, 2019 1 commit
    • Takenobu Tani's avatar
      Update Wiki URLs to point to GitLab · 3769e3a8
      Takenobu Tani authored
      This moves all URL references to Trac Wiki to their corresponding
      GitLab counterparts.
      This substitution is classified as follows:
      1. Automated substitution using sed with Ben's mapping rule [1]
          Old: ghc.haskell.org/trac/ghc/wiki/XxxYyy...
          New: gitlab.haskell.org/ghc/ghc/wikis/xxx-yyy...
      2. Manual substitution for URLs containing `#` index
          Old: ghc.haskell.org/trac/ghc/wiki/XxxYyy...#Zzz
          New: gitlab.haskell.org/ghc/ghc/wikis/xxx-yyy...#zzz
      3. Manual substitution for strings starting with `Commentary`
          Old: Commentary/XxxYyy...
          New: commentary/xxx-yyy...
      See also !539
      [1]: https://gitlab.haskell.org/bgamari/gitlab-migration/blob/master/wiki-mapping.json
  12. 15 Mar, 2019 1 commit
  13. 27 Feb, 2019 1 commit
    • Vladislav Zavialov's avatar
      Treat kind/type variables identically, demolish FKTV · 5bc195b1
      Vladislav Zavialov authored
      Implements GHC Proposal #24: .../ghc-proposals/blob/master/proposals/0024-no-kind-vars.rst
      Fixes Trac #16334, Trac #16315
      With this patch, scoping rules for type and kind variables have been
      unified: kind variables no longer receieve special treatment. This
      simplifies both the language and the implementation.
      User-facing changes
      * Kind variables are no longer implicitly quantified when an explicit
        forall is used:
          p ::             Proxy (a :: k)    -- still accepted
          p :: forall k a. Proxy (a :: k)    -- still accepted
          p :: forall   a. Proxy (a :: k)    -- no longer accepted
        In other words, now we adhere to the "forall-or-nothing" rule more
        Related function: RnTypes.rnImplicitBndrs
      * The -Wimplicit-kind-vars warning has been deprecated.
      * Kind variables are no longer implicitly quantified in constructor
          data T a        = T1 (S (a :: k) | forall (b::k). T2 (S b)  -- no longer accepted
          data T (a :: k) = T1 (S (a :: k) | forall (b::k). T2 (S b)  -- still accepted
        Related function: RnTypes.extractRdrKindSigVars
      * Implicitly quantified kind variables are no longer put in front of
        other variables:
          f :: Proxy (a :: k) -> Proxy (b :: j)
          f :: forall k j (a :: k) (b :: j). Proxy a -> Proxy b   -- old order
          f :: forall k (a :: k) j (b :: j). Proxy a -> Proxy b   -- new order
        This is a breaking change for users of TypeApplications. Note that
        we still respect the dpendency order: 'k' before 'a', 'j' before 'b'.
        See "Ordering of specified variables" in the User's Guide.
        Related function: RnTypes.rnImplicitBndrs
      * In type synonyms and type family equations, free variables on the RHS
        are no longer implicitly quantified unless used in an outermost kind
          type T = Just (Nothing :: Maybe a)         -- no longer accepted
          type T = Just Nothing :: Maybe (Maybe a)   -- still accepted
        The latter form is a workaround due to temporary lack of an explicit
        quantification method. Ideally, we would write something along these
          type T @a = Just (Nothing :: Maybe a)
        Related function: RnTypes.extractHsTyRdrTyVarsKindVars
      * Named wildcards in kinds are fixed (Trac #16334):
          x :: (Int :: _t)    -- this compiles, infers (_t ~ Type)
        Related function: RnTypes.partition_nwcs
      Implementation notes
      * One of the key changes is the removal of FKTV in RnTypes:
        - data FreeKiTyVars = FKTV { fktv_kis    :: [Located RdrName]
        -                          , fktv_tys    :: [Located RdrName] }
        + type FreeKiTyVars = [Located RdrName]
        We used to keep track of type and kind variables separately, but
        now that they are on equal footing when it comes to scoping, we
        can put them in the same list.
      * extract_lty and family are no longer parametrized by TypeOrKind,
        as we now do not distinguish kind variables from type variables.
      * PatSynExPE and the related Note [Pattern synonym existentials do not scope]
        have been removed (Trac #16315). With no implicit kind quantification,
        we can no longer trigger the error.
      * reportFloatingKvs and the related Note [Free-floating kind vars]
        have been removed. With no implicit kind quantification,
        we can no longer trigger the error.
  14. 24 Feb, 2019 2 commits
    • Vladislav Zavialov's avatar
      Expression/command ambiguity resolution · e61f6e35
      Vladislav Zavialov authored
      This patch removes 'HsArrApp' and 'HsArrForm' from 'HsExpr' by
      introducing a new ambiguity resolution system in the parser.
      Problem: there are places in the grammar where we do not know whether we
      are parsing an expression or a command:
      	proc x -> do { (stuff) -< x }   -- 'stuff' is an expression
      	proc x -> do { (stuff) }        -- 'stuff' is a command
      Until we encounter arrow syntax (-<) we don't know whether to parse
      'stuff' as an expression or a command.
      The old solution was to parse as HsExpr always, and rejig later:
      	checkCommand :: LHsExpr GhcPs -> P (LHsCmd GhcPs)
      This meant polluting 'HsExpr' with command-related constructors. In
      other words, limitations of the parser were affecting the AST, and
      all other code (the renamer, the typechecker) had to deal with these
      extra constructors by panicking.
      We fix this abstraction leak by parsing into an intermediate
      representation, 'ExpCmd':
      	data ExpCmdG b where
      	  ExpG :: ExpCmdG HsExpr
      	  CmdG :: ExpCmdG HsCmd
      	type ExpCmd = forall b. ExpCmdG b -> PV (Located (b GhcPs))
      	checkExp :: ExpCmd -> PV (LHsExpr GhcPs)
      	checkCmd :: ExpCmd -> PV (LHsCmd GhcPs)
      	checkExp f = f ExpG  -- interpret as an expression
      	checkCmd f = f CmdG  -- interpret as a command
      See Note [Ambiguous syntactic categories] for details.
      Now the intricacies of parsing have no effect on the hsSyn AST when it
      comes to the expression/command ambiguity.
      Future work: apply the same principles to the expression/pattern
    • Simon Peyton Jones's avatar
      Add AnonArgFlag to FunTy · 6cce36f8
      Simon Peyton Jones authored
      The big payload of this patch is:
        Add an AnonArgFlag to the FunTy constructor
        of Type, so that
          (FunTy VisArg   t1 t2) means (t1 -> t2)
          (FunTy InvisArg t1 t2) means (t1 => t2)
      The big payoff is that we have a simple, local test to make
      when decomposing a type, leading to many fewer calls to
      isPredTy. To me the code seems a lot tidier, and probably
      more efficient (isPredTy has to take the kind of the type).
      See Note [Function types] in TyCoRep.
      There are lots of consequences
      * I made FunTy into a record, so that it'll be easier
        when we add a linearity field, something that is coming
        down the road.
      * Lots of code gets touched in a routine way, simply because it
        pattern matches on FunTy.
      * I wanted to make a pattern synonym for (FunTy2 arg res), which
        picks out just the argument and result type from the record. But
        alas the pattern-match overlap checker has a heart attack, and
        either reports false positives, or takes too long.  In the end
        I gave up on pattern synonyms.
        There's some commented-out code in TyCoRep that shows what I
        wanted to do.
      * Much more clarity about predicate types, constraint types
        and (in particular) equality constraints in kinds.  See TyCoRep
        Note [Types for coercions, predicates, and evidence]
        and Note [Constraints in kinds].
        This made me realise that we need an AnonArgFlag on
        AnonTCB in a TyConBinder, something that was really plain
        wrong before. See TyCon Note [AnonTCB InivsArg]
      * When building function types we must know whether we
        need VisArg (mkVisFunTy) or InvisArg (mkInvisFunTy).
        This turned out to be pretty easy in practice.
      * Pretty-printing of types, esp in IfaceType, gets
        tidier, because we were already recording the (->)
        vs (=>) distinction in an ad-hoc way.  Death to
      * mkLamType needs to keep track of whether it is building
        (t1 -> t2) or (t1 => t2).  See Type
        Note [mkLamType: dictionary arguments]
      Other minor stuff
      * Some tidy-up in validity checking involving constraints;
        Trac #16263
  15. 21 Jan, 2019 1 commit
  16. 18 Jan, 2019 1 commit
  17. 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).
  18. 29 Nov, 2018 1 commit
    • Simon Peyton Jones's avatar
      Taming the Kind Inference Monster · 2257a86d
      Simon Peyton Jones authored
      My original goal was (Trac #15809) to move towards using level numbers
      as the basis for deciding which type variables to generalise, rather
      than searching for the free varaibles of the environment.  However
      it has turned into a truly major refactoring of the kind inference
      Let's deal with the level-numbers part first:
      * Augment quantifyTyVars to calculate the type variables to
        quantify using level numbers, and compare the result with
        the existing approach.  That is; no change in behaviour,
        just a WARNing if the two approaches give different answers.
      * To do this I had to get the level number right when calling
        quantifyTyVars, and this entailed a bit of care, especially
        in the code for kind-checking type declarations.
      * However, on the way I was able to eliminate or simplify
        a number of calls to solveEqualities.
      This work is incomplete: I'm not /using/ level numbers yet.
      When I subsequently get rid of any remaining WARNings in
      quantifyTyVars, that the level-number answers differ from
      the current answers, then I can rip out the current
      "free vars of the environment" stuff.
      Anyway, this led me into deep dive into kind inference for type and
      class declarations, which is an increasingly soggy part of GHC.
      Richard already did some good work recently in
         commit 5e45ad10
         Date:   Thu Sep 13 09:56:02 2018 +0200
          Finish fix for #14880.
          The real change that fixes the ticket is described in
          Note [Naughty quantification candidates] in TcMType.
      but I kept turning over stones. So this patch has ended up
      with a pretty significant refactoring of that code too.
      Kind inference for types and classes
      * Major refactoring in the way we generalise the inferred kind of
        a TyCon, in kcTyClGroup.  Indeed, I made it into a new top-level
        function, generaliseTcTyCon.  Plus a new Note to explain it
        Note [Inferring kinds for type declarations].
      * We decided (Trac #15592) not to treat class type variables specially
        when dealing with Inferred/Specified/Required for associated types.
        That simplifies things quite a bit. I also rewrote
        Note [Required, Specified, and Inferred for types]
      * Major refactoring of the crucial function kcLHsQTyVars:
        I split it into
             kcLHsQTyVars_Cusk  and  kcLHsQTyVars_NonCusk
        because the two are really quite different. The CUSK case is
        almost entirely rewritten, and is much easier because of our new
        decision not to treat the class variables specially
      * I moved all the error checks from tcTyClTyVars (which was a bizarre
        place for it) into generaliseTcTyCon and/or the CUSK case of
        kcLHsQTyVars.  Now tcTyClTyVars is extremely simple.
      * I got rid of all the all the subtleties in tcImplicitTKBndrs. Indeed
        now there is no difference between tcImplicitTKBndrs and
        kcImplicitTKBndrs; there is now a single bindImplicitTKBndrs.
        Same for kc/tcExplicitTKBndrs.  None of them monkey with level
        numbers, nor build implication constraints.  scopeTyVars is gone
        entirely, as is kcLHsQTyVarBndrs. It's vastly simpler.
        I found I could get rid of kcLHsQTyVarBndrs entirely, in favour of
        the bnew bindExplicitTKBndrs.
      * I now deal with the "naughty quantification candidates"
        of the previous patch in candidateQTyVars, rather than in
        quantifyTyVars; see Note [Naughty quantification candidates]
        in TcMType.
        I also killed off closeOverKindsCQTvs in favour of the same
        strategy that we use for tyCoVarsOfType: namely, close over kinds
        at the occurrences.
        And candidateQTyVars no longer needs a gbl_tvs argument.
      * Passing the ContextKind, rather than the expected kind itself,
        to tc_hs_sig_type_and_gen makes it easy to allocate the expected
        result kind (when we are in inference mode) at the right level.
      Type families
      * I did a major rewrite of the impenetrable tcFamTyPats. The result
        is vastly more comprehensible.
      * I got rid of kcDataDefn entirely, quite a big function.
      * I re-did the way that checkConsistentFamInst works, so
        that it allows alpha-renaming of invisible arguments.
      * The interaction of kind signatures and family instances is tricky.
          Type families: see Note [Apparently-nullary families]
          Data families: see Note [Result kind signature for a data family instance]
                         and Note [Eta-reduction for data families]
      * The consistent instantation of an associated type family is tricky.
        See Note [Checking consistent instantiation] and
            Note [Matching in the consistent-instantation check]
        in TcTyClsDecls.  It's now checked in TcTyClsDecls because that is
        when we have the relevant info to hand.
      * I got tired of the compromises in etaExpandFamInst, so I did the
        job properly by adding a field cab_eta_tvs to CoAxBranch.
        See Coercion.etaExpandCoAxBranch.
      tcInferApps and friends
      * I got rid of the mysterious and horrible ClsInstInfo argument
        to tcInferApps, checkExpectedKindX, and various checkValid
        functions.  It was horrible!
      * I got rid of [Type] result of tcInferApps.  This list was used
        only in tcFamTyPats, when checking the LHS of a type instance;
        and if there is a cast in the middle, the list is meaningless.
        So I made tcInferApps simpler, and moved the complexity
        (not much) to tcInferApps.
        Result: tcInferApps is now pretty comprehensible again.
      * I refactored the many function in TcMType that instantiate skolems.
      Smaller things
      * I rejigged the error message in checkValidTelescope; I think it's
        quite a bit better now.
      * checkValidType was not rejecting constraints in a kind signature
           forall (a :: Eq b => blah). blah2
        That led to further errors when we then do an ambiguity check.
        So I make checkValidType reject it more aggressively.
      * I killed off quantifyConDecl, instead calling kindGeneralize
      * I fixed an outright bug in tyCoVarsOfImplic, where we were not
        colleting the tyvar of the kind of the skolems
      * Renamed ClsInstInfo to AssocInstInfo, and made it into its
        own data type
      * Some fiddling around with pretty-printing of family
        instances which was trickier than I thought.  I wanted
        wildcards to print as plain "_" in user messages, although
        they each need a unique identity in the CoAxBranch.
      Some other oddments
      * Refactoring around the trace messages from reportUnsolved.
      * A bit of extra tc-tracing in TcHsSyn.commitFlexi
      This patch fixes a raft of bugs, and includes tests for them.
       * #14887
       * #15740
       * #15764
       * #15789
       * #15804
       * #15817
       * #15870
       * #15874
       * #15881
  19. 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
  20. 27 Oct, 2018 1 commit
    • mayac's avatar
      More explicit foralls (GHC Proposal 0007) · 512eeb9b
      mayac authored
      Allow the user to explicitly bind type/kind variables in type and data
      family instances (including associated instances), closed type family
      equations, and RULES pragmas. Follows the specification of GHC
      Proposal 0007, also fixes #2600. Advised by Richard Eisenberg.
      This modifies the Template Haskell AST -- old code may break!
      Other Changes:
      - convert HsRule to a record
      - make rnHsSigWcType more general
      - add repMaybe to DsMeta
      Includes submodule update for Haddock.
      Test Plan: validate
      Reviewers: goldfire, bgamari, alanz
      Subscribers: simonpj, RyanGlScott, goldfire, rwbarton,
                   thomie, mpickering, carter
      GHC Trac Issues: #2600, #14268
      Differential Revision: https://phabricator.haskell.org/D4894
  21. 25 Oct, 2018 1 commit
    • Simon Peyton Jones's avatar
      Remove a zonkTcTyVarToTyVar · 29978ef1
      Simon Peyton Jones authored
      This patch fixes Trac #15778 by removing a zonkTcTyVarToTyVar
      from tcHsSigType.
      Nww that a pattern-bound type variable can refer to a type, it's
      obvoiusly wrong to expect it to be a TyVar!  Moreover, that zonk
      is entirely unnecessary.
      I added a new Note [Type variables in the type environment]
      in TcRnTypes
  22. 24 Oct, 2018 3 commits
  23. 05 Oct, 2018 1 commit
  24. 04 Oct, 2018 1 commit
    • Simon Peyton Jones's avatar
      Fail fast on pattern synonyms · 9ebfa03d
      Simon Peyton Jones authored
      We were recovering too eagerly from errors in pattern-synonym
      type inference, leading to a cascade of confusing follow up errors
      (Trac #15685, #15692).
      The underlying issue is that a pattern synonym should have a closed,
      fixed type, with no unification variables in it.  But it wasn't!
      Fixing this made me change the interface to simplifyInfer slightly.
      Instead of /emitting/ a residual implication constraint, it
      now /returns/ it, so that the caller can decide what to do.
  25. 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.
      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
  26. 13 Sep, 2018 1 commit
  27. 24 Aug, 2018 1 commit
  28. 21 Aug, 2018 1 commit
    • Andreas Klebinger's avatar
      Replace most occurences of foldl with foldl'. · 09c1d5af
      Andreas Klebinger authored
      This patch adds foldl' to GhcPrelude and changes must occurences
      of foldl to foldl'. This leads to better performance especially
      for quick builds where GHC does not perform strictness analysis.
      It does change strictness behaviour when we use foldl' to turn
      a argument list into function applications. But this is only a
      drawback if code looks ONLY at the last argument but not at the first.
      And as the benchmarks show leads to fewer allocations in practice
      at O2.
      Compiler performance for Nofib:
      O2 Allocations:
              -1 s.d.                -----            -0.0%
              +1 s.d.                -----            -0.0%
              Average                -----            -0.0%
      O2 Compile Time:
              -1 s.d.                -----            -2.8%
              +1 s.d.                -----            +1.3%
              Average                -----            -0.8%
      O0 Allocations:
              -1 s.d.                -----            -0.2%
              +1 s.d.                -----            -0.1%
              Average                -----            -0.2%
      Test Plan: ci
      Reviewers: goldfire, bgamari, simonmar, tdammers, monoidal
      Reviewed By: bgamari, monoidal
      Subscribers: tdammers, rwbarton, thomie, carter
      Differential Revision: https://phabricator.haskell.org/D4929
  29. 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
  30. 25 Jul, 2018 1 commit
  31. 24 Jul, 2018 1 commit
    • Ryan Scott's avatar
      Suppress -Winaccessible-code in derived code · 44a7b9ba
      Ryan Scott authored
      It's rather unfortunate that derived code can produce inaccessible
      code warnings (as demonstrated in #8128, #8740, and #15398), since
      the programmer has no control over the generated code. This patch
      aims to suppress `-Winaccessible-code` in all derived code. It
      accomplishes this by doing the following:
      * Generalize the `ic_env :: TcLclEnv` field of `Implication` to
        be of type `Env TcGblEnc TcLclEnv` instead. This way, it also
        captures `DynFlags`, which record the flag state at the time
        the `Implication` was created.
      * When typechecking derived code, turn off `-Winaccessible-code`.
        This way, any insoluble given `Implication`s that are created when
        typechecking this derived code will remember that
        `-Winaccessible-code` was disabled.
      * During error reporting, consult the `DynFlags` of an
        `Implication` before making the decision to report an inaccessible
        code warning.
      Test Plan: make test TEST="T8128 T8740 T15398"
      Reviewers: simonpj, bgamari
      Reviewed By: simonpj
      Subscribers: monoidal, rwbarton, thomie, carter
      GHC Trac Issues: #8128, #8740, #15398
      Differential Revision: https://phabricator.haskell.org/D4993
  32. 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
      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.
  33. 18 Jun, 2018 1 commit
  34. 17 Jun, 2018 1 commit
    • Ryan Scott's avatar
      Provide a better error message for unpromotable data constructor contexts · c6375411
      Ryan Scott authored
      Trac #14845 brought to light a corner case where a data
      constructor could not be promoted (even with `-XTypeInType`) due to
      an unpromotable constraint in its context. However, the error message
      was less than helpful, so this patch adds an additional check to
      `tcTyVar` catch unpromotable data constructors like these //before//
      they're promoted, and to give a sensible error message in such cases.
      Test Plan: make test TEST="T13895 T14845"
      Reviewers: simonpj, goldfire, bgamari
      Reviewed By: bgamari
      Subscribers: rwbarton, thomie, carter
      GHC Trac Issues: #13895, #14845
      Differential Revision: https://phabricator.haskell.org/D4728
  35. 14 Jun, 2018 1 commit
    • Vladislav Zavialov's avatar
      Embrace -XTypeInType, add -XStarIsType · d650729f
      Vladislav Zavialov authored
      Implement the "Embrace Type :: Type" GHC proposal,
      GHC 8.0 included a major change to GHC's type system: the Type :: Type
      axiom. Though casual users were protected from this by hiding its
      features behind the -XTypeInType extension, all programs written in GHC
      8+ have the axiom behind the scenes. In order to preserve backward
      compatibility, various legacy features were left unchanged. For example,
      with -XDataKinds but not -XTypeInType, GADTs could not be used in types.
      Now these restrictions are lifted and -XTypeInType becomes a redundant
      flag that will be eventually deprecated.
      * Incorporate the features currently in -XTypeInType into the
        -XPolyKinds and -XDataKinds extensions.
      * Introduce a new extension -XStarIsType to control how to parse * in
        code and whether to print it in error messages.
      Test Plan: Validate
      Reviewers: goldfire, hvr, bgamari, alanz, simonpj
      Reviewed By: goldfire, simonpj
      Subscribers: rwbarton, thomie, mpickering, carter
      GHC Trac Issues: #15195
      Differential Revision: https://phabricator.haskell.org/D4748
  36. 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
        #9123 (especially!  higher kinded roles)
      The wiki page is
      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
        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