1. 19 Nov, 2019 1 commit
  2. 16 Oct, 2019 1 commit
    • Richard Eisenberg's avatar
      Break up TcRnTypes, among other modules. · 51fad9e6
      Richard Eisenberg authored
      This introduces three new modules:
       - basicTypes/Predicate.hs describes predicates, moving
         this logic out of Type. Predicates don't really exist
         in Core, and so don't belong in Type.
       - typecheck/TcOrigin.hs describes the origin of constraints
         and types. It was easy to remove from other modules and
         can often be imported instead of other, scarier modules.
       - typecheck/Constraint.hs describes constraints as used in
         the solver. It is taken from TcRnTypes.
      No work other than module splitting is in this patch.
      This is the first step toward homogeneous equality, which will
      rely more strongly on predicates. And homogeneous equality is the
      next step toward a dependently typed core language.
  3. 08 Oct, 2019 2 commits
    • Richard Eisenberg's avatar
      Solve constraints from top-level groups sooner · 9612e91c
      Richard Eisenberg authored
      Previously, all constraints from all top-level groups (as
      separated by top-level splices) were lumped together and solved
      at the end. This could leak metavariables to TH, though, and
      that's bad. This patch solves each group's constraints before
      running the next group's splice.
      Naturally, we now report fewer errors in some cases.
      One nice benefit is that this also fixes #11680, but in a much
      simpler way than the original fix for that ticket. Admittedly,
      the error messages degrade just a bit from the fix from #11680
      (previously, we informed users about variables that will be
      brought into scope below a top-level splice, and now we just
      report an out-of-scope error), but the amount of complexity
      required throughout GHC to get that error was just not worth it.
      This patch thus reverts much of
      Fixes #16980
      Test cases: th/T16980{,a}
    • Ryan Scott's avatar
      Mark newtype constructors as used in the Coercible solver (#10347) · bf02c264
      Ryan Scott authored
      Currently, newtype constructors are not marked as used when they are
      accessed under the hood by uses of `coerce`, as described in #10347.
      This fixes #10347 by co-opting the `tcg_keep` field of `TcGblEnv`
      to track uses of newtype constructors in the `Coercible` solver.
      See `Note [Tracking unused binding and imports]` in `TcRnTypes`.
      Since #10347 is fixed, I was able to simplify the code in `TcDeriv`
      slightly, as the hack described in
      `Note [Newtype deriving and unused constructors]`
      is no longer necessary.
  4. 01 Oct, 2019 1 commit
  5. 25 Sep, 2019 1 commit
    • Sebastian Graf's avatar
      PmCheck: Only ever check constantly many models against a single pattern · ebc65025
      Sebastian Graf authored
      Introduces a new flag `-fmax-pmcheck-deltas` to achieve that. Deprecates
      the old `-fmax-pmcheck-iter` mechanism in favor of this new flag.
      From the user's guide:
      Pattern match checking can be exponential in some cases. This limit makes sure
      we scale polynomially in the number of patterns, by forgetting refined
      information gained from a partially successful match. For example, when
      matching `x` against `Just 4`, we split each incoming matching model into two
      sub-models: One where `x` is not `Nothing` and one where `x` is `Just y` but
      `y` is not `4`. When the number of incoming models exceeds the limit, we
      continue checking the next clause with the original, unrefined model.
      This also retires the incredibly hard to understand "maximum number of
      refinements" mechanism, because the current mechanism is more general
      and should catch the same exponential cases like PrelRules at the same
      Metric Decrease:
  6. 20 Sep, 2019 1 commit
  7. 19 Sep, 2019 2 commits
    • Sebastian Graf's avatar
      Extract PmTypes module from PmExpr and PmOracle · baf47661
      Sebastian Graf authored
      Apparently ghc-lib-parser's API blew up because the newly induced cyclic
      dependency between TcRnTypes and PmOracle pulled in the other half of
      GHC into the relevant strongly-connected component.
      This patch arranges it so that PmTypes exposes mostly data type
      definitions and type class instances to be used within PmOracle, without
      importing the any of the possibly offending modules DsMonad, TcSimplify
      and FamInst.
    • Richard Eisenberg's avatar
      Use level numbers for generalisation · f594a68a
      Richard Eisenberg authored
      This fixes #15809, and is covered in
      Note [Use level numbers for quantification] in TcMType.
      This patch removes the "global tyvars" from the
      environment, a nice little win.
  8. 16 Sep, 2019 1 commit
    • Sebastian Graf's avatar
      Encode shape information in `PmOracle` · 7915afc6
      Sebastian Graf authored
      Previously, we had an elaborate mechanism for selecting the warnings to
      generate in the presence of different `COMPLETE` matching groups that,
      albeit finely-tuned, produced wrong results from an end user's
      perspective in some cases (#13363).
      The underlying issue is that at the point where the `ConVar` case has to
      commit to a particular `COMPLETE` group, there's not enough information
      to do so and the status quo was to just enumerate all possible complete
      sets nondeterministically.  The `getResult` function would then pick the
      outcome according to metrics defined in accordance to the user's guide.
      But crucially, it lacked knowledge about the order in which affected
      clauses appear, leading to the surprising behavior in #13363.
      In !1010 we taught the term oracle to reason about literal values a
      variable can certainly not take on. This MR extends that idea to
      `ConLike`s and thereby fixes #13363: Instead of committing to a
      particular `COMPLETE` group in the `ConVar` case, we now split off the
      matching constructor incrementally and record the newly covered case as
      a refutable shape in the oracle. Whenever the set of refutable shapes
      covers any `COMPLETE` set, the oracle recognises vacuosity of the
      uncovered set.
      This patch goes a step further: Since at this point the information
      in value abstractions is merely a cut down representation of what the
      oracle knows, value abstractions degenerate to a single `Id`, the
      semantics of which is determined by the oracle state `Delta`.
      Value vectors become lists of `[Id]` given meaning to by a single
      `Delta`, value set abstractions (of which the uncovered set is an
      instance) correspond to a union of `Delta`s which instantiate the
      same `[Id]` (akin to models of formula).
      Fixes #11528 #13021, #13363, #13965, #14059, #14253, #14851, #15753, #17096, #17149
      Metric Decrease:
  9. 19 Aug, 2019 1 commit
  10. 19 Jul, 2019 1 commit
  11. 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.
  12. 05 Jul, 2019 1 commit
  13. 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
  14. 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.
  15. 12 Jun, 2019 1 commit
  16. 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
  17. 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:
  18. 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.
  19. 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
  20. 15 Mar, 2019 1 commit
  21. 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.
  22. 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
  23. 21 Jan, 2019 1 commit
  24. 18 Jan, 2019 1 commit
  25. 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).
  26. 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
  27. 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
  28. 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
  29. 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
  30. 24 Oct, 2018 3 commits
  31. 05 Oct, 2018 1 commit
  32. 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.
  33. 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
  34. 13 Sep, 2018 1 commit