diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..4e09cca093022a0e9077f6d428005258578b3745
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: Bug report
+about: Create a report to help us improve
+title: ''
+labels: ''
+assignees: ''
+
+---
+
+**Describe the bug**
+A clear and concise description of what the bug is.
+
+**To Reproduce**
+Steps to reproduce the behavior:
+
+```
+$ cabal v2-build ...
+```
+
+Please use version-prefixed commands (e.g. `v2-build` or `v1-build`) to avoid ambiguity.
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.
+
+**System informataion**
+ - Operating system
+ - `cabal`, `ghc` versions
+
+**Additional context**
+Add any other context about the problem here.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index fa7f4ef715a4db148abed0ca3e322bc391636be3..11c20b4a33c606d4d3d3d566ece7778a7a9541f2 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -2,7 +2,7 @@
 ---
 Please include the following checklist in your PR:
 
-* [ ] Patches conform to the [coding conventions](https://github.com/haskell/cabal/#conventions).
+* [ ] Patches conform to the [coding conventions](https://github.com/haskell/cabal/blob/master/CONTRIBUTING.md#conventions).
 * [ ] Any changes that could be relevant to users have been recorded in the changelog.
 * [ ] The documentation has been updated, if necessary.
 * [ ] If the change is docs-only, `[ci skip]` is used to avoid triggering the build bots.
diff --git a/.mailmap b/.mailmap
index 27a2a3843086a169ffddf41783dcd134d9333beb..671fdf1db23c0b3ab307fce790b84c224481b690 100644
--- a/.mailmap
+++ b/.mailmap
@@ -20,6 +20,7 @@ Andres Löh                  <andres.loeh@gmail.com>                <andres@well
 Andres Löh                  <andres.loeh@gmail.com>                <ksgithub@andres-loeh.de>
 Andres Löh                  <andres.loeh@gmail.com>                <mail@andres-loeh.de>
 Andy Craze                  <accraze@gmail.com>
+Arian van Putten            <arian.vanputten@gmail.com>            <aeroboy94@gmail.com>
 Audrey Tang                 <audreyt@audreyt.org>                  audreyt <audreyt@audreyt.org>
 Austin Seipp                <aseipp@pobox.com>
 Austin Seipp                <aseipp@pobox.com>                     <aseipp@well-typed.com>
@@ -57,6 +58,7 @@ Duncan Coutts               <duncan@community.haskell.org>         unknown <unkn
 Edward Z. Yang              <ezyang@cs.stanford.edu>               <ezyang@fb.com>
 Edward Z. Yang              <ezyang@cs.stanford.edu>               <ezyang@mit.edu>
 Einar Karttunen             <ekarttun@cs.helsinki.fi>
+Emily Pillmore              <emilypi@cohomolo.gy>                  <emily@kadena.io>
 Federico Mastellone         <fmaste@users.noreply.github.com>
 Felix Yan                   <felixonmars@archlinux.org>            Felix Yan <felixonmars@gmail.com>
 Francesco Gazzetta          <fgaz@fgaz.me>                         <fgaz@users.noreply.github.com>
@@ -117,6 +119,7 @@ Li-yao Xia                  <lysxia@gmail.com>
 Malcolm Wallace             <Malcolm.Wallace@me.com>               Malcolm.Wallace <Malcolm.Wallace@cs.york.ac.uk>
 Mark Weber                  <marco-oweber@gmx.de>                  marco-oweber <marco-oweber@gmx.de>
 Martin Sjögren              <msjogren@gmail.com>                   md9ms <md9ms@mdstud.chalmers.se>
+Matt Renaud                 <matt@m-renaud.com>                    <mrenaud@google.com>
 Mikhail Glushenkov          <mikhail.glushenkov@gmail.com>         <c05mgv@cs.umu.se>
 Mikhail Glushenkov          <mikhail.glushenkov@gmail.com>         <mikhail@scrive.com>
 Mikhail Glushenkov          <mikhail.glushenkov@gmail.com>         <the.dead.shall.rise@gmail.com>
@@ -156,8 +159,8 @@ Thomas Tuegel               <ttuegel@gmail.com>
 Thomas Tuegel               <ttuegel@gmail.com>                    <ttuegel@mailbox.org>
 Thomas Tuegel               <ttuegel@gmail.com>                    <ttuegel@secure.mailbox.org>
 Veronika Romashkina         <vrom911@gmail.com>
+Zejun Wu                    <zejun.wu@gmail.com>                   <watashi@watashi.ws>
 capsjac                     <capsjac@gmail.com>                              # Goes by that name online
 ghthrowaway7                <41365123+ghthrowaway7@users.noreply.github.com> # Goes by that name online
 quasicomputational          <quasicomputational@gmail.com>                   # Goes by that name online
 vedksah                     <31156362+vedksah@users.noreply.github.com>      # Goes by that name online
-!
diff --git a/.travis.yml b/.travis.yml
index fa60ae347374e1166044c830e07eccc8eeea9004..1fbec4bbaa9e35b0a5f19bcc2c38c697a214c221 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -13,6 +13,7 @@ sudo: true
 branches:
   only:
     - master
+    - "3.0"
     - "2.4"
     - "2.2"
     - "2.0"
diff --git a/AUTHORS b/AUTHORS
index b7cd9ea0899da8bf1c00a1c6ba04138e8f3b5fb4..a02c318d77b5e52f697ec553d4acf1cb063d4115 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -16,6 +16,7 @@ Alexander Vershilov      <alexander.vershilov@gmail.com>
 Alexei Pastuchov         <alexei.pastuchov@telecolumbus.de>
 Alexis Williams          <alexis@typedr.at>
 Alistair Bailey          <alistair@abayley.org>
+Alp Mestanogullari       <alpmestan@gmail.com>
 Alson Kemp               <alson@alsonkemp.com>
 Amir Mohammad Saied      <amirsaied@gmail.com>
 Anders Kaseorg           <andersk@mit.edu>
@@ -29,7 +30,7 @@ Angus Lepper             <angus.lepper@gmail.com>
 Antoine Latter           <aslatter@gmail.com>
 Anton Dessiatov          <anton.dessiatov@gmail.com>
 Antonio Nikishaev        <a@lelf.me>
-Arian van Putten         <aeroboy94@gmail.com>
+Arian van Putten         <arian.vanputten@gmail.com>
 Arun Tejasvi Chaganty    <arunchaganty@gmail.com>
 Atze Dijkstra            <atze@cs.uu.nl>
 Audrey Tang              <audreyt@audreyt.org>
@@ -66,6 +67,7 @@ Clint Adams              <clint@debian.org>
 Colin Wahl               <colin.t.wahl@gmail.com>
 Conal Elliott            <conal@conal.net>
 Curtis Gagliardi         <curtis@curtis.io>
+Dale Wijnand             <344610+dwijnand@users.noreply.github.com>
 Dan Burton               <danburton.email@gmail.com>
 Daniel Buckmaster        <dan.buckmaster@gmail.com>
 Daniel Díaz Carrete      <daniel@bogusemailserver.com>
@@ -75,6 +77,7 @@ Daniel Velkov            <norcobg@gmail.com>
 Daniel Wagner            <daniel@wagner-home.com>
 Danny Navarro            <j@dannynavarro.net>
 Dave Laing               <dave.laing.80@gmail.com>
+David Eichmann           <EichmannD@gmail.com>
 David Feuer              <David.Feuer@gmail.com>
 David Fox                <dsf@seereason.com>
 David Himmelstrup        <lemmih@gmail.com>
@@ -97,6 +100,7 @@ Echo Nolan               <echo@echonolan.net>
 Edsko de Vries           <edsko@well-typed.com>
 Edward Z. Yang           <ezyang@cs.stanford.edu>
 Einar Karttunen          <ekarttun@cs.helsinki.fi>
+Emily Pillmore           <emilypi@cohomolo.gy>
 Eric Kow                 <eric.kow@gmail.com>
 Eric Seidel              <gridaphobe@gmail.com>
 Erik Hesselink           <hesselink@gmail.com>
@@ -106,6 +110,7 @@ Esa Ilari Vuokko         <ei@vuokko.info>
 Eugene Sukhodolin        <eugene@sukhodolin.com>
 Eyal Lotem               <eyal.lotem@gmail.com>
 Fabián Orccón            <fabian.orccon@pucp.pe>
+Fangyi Zhou              <fangyi.zhou15@imperial.ac.uk>
 Federico Mastellone      <fmaste@users.noreply.github.com>
 Felix Yan                <felixonmars@archlinux.org>
 Florian Hartwig          <florian.j.hartwig@gmail.com>
@@ -125,6 +130,7 @@ Gleb Popov               <6yearold@gmail.com>
 Gregory Collins          <greg@gregorycollins.net>
 Gwern Branwen            <gwern0@gmail.com>
 Haisheng.Wu              <freizl@gmail.com>
+Harrison Houghton        <haro@constant.gripe>
 Harry Garrood            <harry@garrood.me>
 Heather                  <heather@live.ru>
 Henk-Jan van Tuyl        <hjgtuyl@chello.nl>
@@ -145,6 +151,7 @@ JP Moresmau              <jp@moresmau.fr>
 Jacco Krijnen            <jaccokrijnen@gmail.com>
 Jack Henahan             <jhenahan@uvm.edu>
 Jake Wheat               <jakewheatmail@gmail.com>
+James Earl Douglas       <james@earldouglas.com>
 Jan Path                 <jan@jpath.de>
 Jason Dagit              <dagitj@gmail.com>
 Jean-Philippe Bernardy   <jeanphilippe.bernardy@gmail.com>
@@ -168,6 +175,7 @@ Jookia                   <166291@gmail.com>
 Josef Svenningsson       <josef.svenningsson@gmail.com>
 Josh Hoyt                <josh.hoyt@galois.com>
 Josh Kalderimis          <josh.kalderimis@gmail.com>
+Josh Meredith            <joshmeredith2008@gmail.com>
 Judah Jacobson           <judah.jacobson@gmail.com>
 Jürgen Nicklisch-Franken <jnf@arcor.de>
 Karel Gardas             <karel.gardas@centrum.cz>
@@ -200,6 +208,7 @@ Martin Vlk               <martin@vlkk.cz>
 Masahiro Yamauchi        <sgt.yamauchi@gmail.com>
 Mathieu Boespflug        <mboes@tweag.net>
 Matt Renaud              <matt@m-renaud.com>
+Matthew Pickering        <matthewtpickering@gmail.com>
 Matthew William Cox      <matt@mattcox.ca>
 Matthias Fischmann       <mf@zerobuzz.net>
 Matthias Kilian          <kili@outback.escape.de>
@@ -253,6 +262,7 @@ Peter Trško              <peter.trsko@gmail.com>
 Phil Ruffwind            <rf@rufflewind.com>
 Philipp Schumann         <philipp.schumann@gmail.com>
 Philipp Schuster         <pschuster@uni-koblenz.de>
+Piyush P Kurur           <ppk@cse.iitk.ac.in>
 Pranit Bauva             <pranit.bauva@gmail.com>
 Prayag Verma             <prayag.verma@gmail.com>
 Randy Polen              <randen@users.noreply.github.com>
@@ -274,6 +284,8 @@ Ryan Newton              <rrnewton@gmail.com>
 Ryan Scott               <ryan.gl.scott@gmail.com>
 Ryan Trinkle             <ryan.trinkle@gmail.com>
 RyanGlScott              <ryan.gl.scott@gmail.com>
+Sam Boosalis             <SamBoosalis@gmail.com>
+Sam Halliday             <sam.halliday@gmail.com>
 Samuel Bronson           <naesten@gmail.com>
 Samuel Gélineau          <gelisam+github@gmail.com>
 Sergei Trofimovich       <slyfox@community.haskell.org>
@@ -305,21 +317,27 @@ Tim Chevalier            <chevalier@alum.wellesley.edu>
 Tim Humphries            <tim.humphries@ambiata.com>
 Tim McGilchrist          <timmcgil@gmail.com>
 Tomas Vestelind          <tomas.vestelind@gmail.com>
+Toon Nolten              <toonn@toonn.io>
 Toshio Ito               <debug.ito@gmail.com>
 Travis Cardwell          <travis.cardwell@extellisys.com>
 Travis Whitaker          <pi.boy.travis@gmail.com>
+Tseen She                <ts33n.sh3@gmail.com>
 Tuncer Ayaz              <tuncer.ayaz@gmail.com>
 Vaibhav Sagar            <vaibhavsagar@gmail.com>
+Vanessa McHale           <vanessa.mchale@iohk.io>
 Veronika Romashkina      <vrom911@gmail.com>
 Vincent Hanquez          <vincent@snarc.org>
 Vladislav Zavialov       <vlad.z.4096@gmail.com>
 Vo Minh Thu              <noteed@gmail.com>
+Wasif Hasan Baig         <pr.wasif@gmail.com>
 Wojciech Danilo          <wojtek.danilo@gmail.com>
 Yitzchak Gale            <gale@sefer.org>
 Yuras Shumovich          <shumovichy@gmail.com>
 Yuriy Syrovetskiy        <cblp@cblp.su>
-Zejun Wu                 <watashi@watashi.ws>
+Zejun Wu                 <zejun.wu@gmail.com>
 capsjac                  <capsjac@gmail.com>
+codetriage-readme-bot    <schneemanbuys@gmail.com>
+fendor                   <power.walross@gmail.com>
 ghthrowaway7             <41365123+ghthrowaway7@users.noreply.github.com>
 quasicomputational       <quasicomputational@gmail.com>
 vedksah                  <31156362+vedksah@users.noreply.github.com>
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 8a93badfebb2755a7e83c8c5af9302f4312f25c2..4cb1c865ed57ed60bcf0da2769dca872914dcc38 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -248,3 +248,7 @@ API Documentation
 -----------------
 
 Auto-generated API documentation for the `master` branch of Cabal is automatically uploaded here: http://haskell.github.io/cabal-website/doc/html/Cabal/.
+
+## Issue triage [![Open Source Helpers](https://www.codetriage.com/haskell/cabal/badges/users.svg)](https://www.codetriage.com/haskell/cabal)
+
+You can contribute by triaging issues which may include reproducing bug reports or asking for vital information, such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to [subscribe to cabal on CodeTriage](https://www.codetriage.com/haskell/cabal).
diff --git a/Cabal/Cabal.cabal b/Cabal/Cabal.cabal
index f7961d02ef78511fae49b6a70d9aac22514a155c..73ab549f0f2f8baef88452909aa07432015ef574 100644
--- a/Cabal/Cabal.cabal
+++ b/Cabal/Cabal.cabal
@@ -1,6 +1,6 @@
 cabal-version: >=1.10
 name:          Cabal
-version:       3.0.0.0
+version:       3.1.0.0
 copyright:     2003-2019, Cabal Development Team (see AUTHORS file)
 license:       BSD3
 license-file:  LICENSE
@@ -282,10 +282,15 @@ library
   if impl(ghc >= 8.0)
     ghc-options: -Wcompat -Wnoncanonical-monad-instances
                  -Wnoncanonical-monadfail-instances
-  else
-    -- at least one of lib:Cabal's dependency (`parsec`)
-    -- already depends on `fail` transitively
-    build-depends: fail == 4.9.*
+
+  if !impl(ghc >= 8.0)
+    -- at least one of lib:Cabal's dependency (i.e. `parsec`)
+    -- already depends on `fail` and `semigroups` transitively
+    build-depends: fail == 4.9.*, semigroups >= 0.18.3 && < 0.20
+
+  if !impl(ghc >= 7.8)
+    -- semigroups depends on tagged.
+    build-depends:  tagged >=0.8.6 && <0.9
 
   exposed-modules:
     Distribution.Backpack
@@ -309,6 +314,7 @@ library
     Distribution.Compat.Graph
     Distribution.Compat.Internal.TempFile
     Distribution.Compat.Newtype
+    Distribution.Compat.ResponseFile
     Distribution.Compat.Prelude.Internal
     Distribution.Compat.Semigroup
     Distribution.Compat.Stack
@@ -352,6 +358,7 @@ library
     Distribution.Simple.Hpc
     Distribution.Simple.Install
     Distribution.Simple.InstallDirs
+    Distribution.Simple.InstallDirs.Internal
     Distribution.Simple.LocalBuildInfo
     Distribution.Simple.PackageIndex
     Distribution.Simple.PreProcess
@@ -373,6 +380,7 @@ library
     Distribution.Simple.Program.Types
     Distribution.Simple.Register
     Distribution.Simple.Setup
+    Distribution.Simple.ShowBuildInfo
     Distribution.Simple.SrcDist
     Distribution.Simple.Test
     Distribution.Simple.Test.ExeV10
@@ -447,6 +455,7 @@ library
     Distribution.Types.TargetInfo
     Distribution.Types.Version
     Distribution.Types.VersionRange
+    Distribution.Types.VersionRange.Internal
     Distribution.Types.VersionInterval
     Distribution.Types.GivenComponent
     Distribution.Types.PackageVersionConstraint
@@ -455,6 +464,7 @@ library
     Distribution.Utils.ShortText
     Distribution.Utils.Progress
     Distribution.Verbosity
+    Distribution.Verbosity.Internal
     Distribution.Version
     Language.Haskell.Extension
     Distribution.Compat.Binary
@@ -530,6 +540,7 @@ library
     Distribution.Simple.GHC.EnvironmentParser
     Distribution.Simple.GHC.Internal
     Distribution.Simple.GHC.ImplInfo
+    Distribution.Simple.Utils.Json
     Paths_Cabal
 
   if flag(bundled-binary-generic)
@@ -593,6 +604,7 @@ test-suite unit-tests
   build-depends:
     array,
     base,
+    binary,
     bytestring,
     containers,
     directory,
@@ -629,6 +641,9 @@ test-suite parser-tests
   ghc-options: -Wall
   default-language: Haskell2010
 
+  if !impl(ghc >= 8.0)
+    build-depends:  semigroups
+
   if impl(ghc >= 7.8)
     build-depends:
       tree-diff      >= 0.0.2 && <0.1
@@ -653,6 +668,8 @@ test-suite check-tests
     Cabal
   ghc-options: -Wall
   default-language: Haskell2010
+  if !impl(ghc >= 8.0)
+    build-depends:  semigroups
 
 test-suite custom-setup-tests
   type: exitcode-stdio-1.0
diff --git a/Cabal/ChangeLog.md b/Cabal/ChangeLog.md
index ab89a2899e57e05009d324273d72659bbb321e67..81cb7f3348a3d6568ad263684287399e30e3a3df 100644
--- a/Cabal/ChangeLog.md
+++ b/Cabal/ChangeLog.md
@@ -1,14 +1,23 @@
-# 3.0.0.0 (current development version)
+# 3.1.0.0 (current development version)
+
+# 3.0.0.0 TBD
   * TODO
   * Introduce set notation for `^>=` and `==` operators
     ([#5906](https://github.com/haskell/cabal/pull/5906)).
   * 'check' reports warnings for various ghc-\*-options fields separately
     ([#5342](https://github.com/haskell/cabal/issues/5432)).
-  * `KnownExtension`: added new extension `DerivingVia`.
+  * `KnownExtension`: added new extensions `DerivingVia` and
+    `EmptyDataDeriving`.
   * Add `extra-dynamic-library-flavours`, to specify extra dynamic library
     flavours to build and install from a .cabal file.
   * `autoconfUserHooks` now passes `--host=$HOST` when cross-compiling
-  * Add a `LibraryVisibility` field to `InstalledPackageInfo`.
+  * Introduce multiple public libraries feature
+    ([#5526](https://github.com/haskell/cabal/pull/5526)).
+    * New build-depends syntax
+    * Add a set of library components to the `Dependency` datatype
+    * New `visibility` field in the `library` stanza
+    * New `LibraryVisibility` field in `InstalledPackageInfo`
+    * New syntax for the `--dependency` Cabal flag
   * Static linking
     * Add `--enable-executable-static` flag for building fully
       static executables (GHC's normal "statish" linking links
@@ -21,6 +30,15 @@
   * Fix corrupted config file header for non-ASCII package names
     ([2557](https://github.com/haskell/cabal/issues/2557)).
   * Extend `Distribution.Simple.Utils.rewriteFileEx` from ASCII to UTF-8 encoding.
+  * Change the arguments of `Newtype` class to better suit @DeriveAnyClass@ usage,
+    add default implementation in terms of `coerce` / `unsafeCoerce`.
+  * Implement support for response file arguments to defaultMain* and cabal-install.
+  * Uniformly provide 'Semigroup' instances for `base < 4.9` via `semigroups` package
+  * Setting `debug-info` now implies `library-stripping: False` and
+    `executable-stripping: False) ([#2702](https://github.com/haskell/cabal/issues/2702))
+  * `Setup.hs copy` and `install` now work in the presence of
+    `data-files` that use `**` syntax
+    ([#6125](https://github.com/haskell/cabal/issues/6125)).
 
 ----
 
@@ -59,6 +77,8 @@
     `non`) and an optics to access the modules in a component
     of a `PackageDescription` by the `ComponentName`:
     `componentBuildInfo` and `componentModules`
+  * Linker `ld-options` are now passed to GHC as `-optl` options
+    ([#4925](https://github.com/haskell/cabal/pull/4925)).
   * Add `readGhcEnvironmentFile` to parse GHC environment files.
   * Drop support for GHC 7.4, since it is out of our support window
     (and has been for over a year!)
diff --git a/Cabal/Distribution/CabalSpecVersion.hs b/Cabal/Distribution/CabalSpecVersion.hs
index f53d999ae66fd67b5805f04d957cde5fd08a478b..b1f8c2f7ffeb5aca2dabf784acacddf289d6e6a6 100644
--- a/Cabal/Distribution/CabalSpecVersion.hs
+++ b/Cabal/Distribution/CabalSpecVersion.hs
@@ -26,12 +26,14 @@ data CabalSpecVersion
     | CabalSpecV2_2
     | CabalSpecV2_4
     | CabalSpecV3_0
+    | CabalSpecV3_2
   deriving (Eq, Ord, Show, Read, Enum, Bounded, Typeable, Data, Generic)
 
 -- | Show cabal spec version, but not the way in the .cabal files
 --
 -- @since 3.0.0.0
 showCabalSpecVersion :: CabalSpecVersion -> String
+showCabalSpecVersion CabalSpecV3_2  = "3.2"
 showCabalSpecVersion CabalSpecV3_0  = "3.0"
 showCabalSpecVersion CabalSpecV2_4  = "2.4"
 showCabalSpecVersion CabalSpecV2_2  = "2.2"
@@ -49,10 +51,11 @@ showCabalSpecVersion CabalSpecV1_2  = "1.2"
 showCabalSpecVersion CabalSpecV1_0  = "1.0"
 
 cabalSpecLatest :: CabalSpecVersion
-cabalSpecLatest = CabalSpecV3_0
+cabalSpecLatest = CabalSpecV3_2
 
 cabalSpecFromVersionDigits :: [Int] -> CabalSpecVersion
 cabalSpecFromVersionDigits v
+    | v >= [3,1]  = CabalSpecV3_2
     | v >= [2,5]  = CabalSpecV3_0
     | v >= [2,3]  = CabalSpecV2_4
     | v >= [2,1]  = CabalSpecV2_2
diff --git a/Cabal/Distribution/Compat/Newtype.hs b/Cabal/Distribution/Compat/Newtype.hs
index e45e97cf9271f45182c0911c2542e81d07320ccb..3e6d1c3aa3adb099fe9509927a8fbbb72881ee55 100644
--- a/Cabal/Distribution/Compat/Newtype.hs
+++ b/Cabal/Distribution/Compat/Newtype.hs
@@ -1,3 +1,5 @@
+{-# LANGUAGE CPP                    #-}
+{-# LANGUAGE DefaultSignatures      #-}
 {-# LANGUAGE FlexibleInstances      #-}
 {-# LANGUAGE FunctionalDependencies #-}
 -- | Per Conor McBride, the 'Newtype' typeclass represents the packing and
@@ -14,31 +16,50 @@ module Distribution.Compat.Newtype (
 import Data.Functor.Identity (Identity (..))
 import Data.Monoid (Sum (..), Product (..), Endo (..))
 
+#if MIN_VERSION_base(4,7,0)
+import Data.Coerce (coerce, Coercible)
+#else
+import Unsafe.Coerce (unsafeCoerce)
+#endif
+
 -- | The @FunctionalDependencies@ version of 'Newtype' type-class.
 --
--- /Note:/ for actual newtypes the implementation can be
--- @pack = coerce; unpack = coerce@. We don't have default implementation,
--- because @Cabal@ have to support older than @base >= 4.7@ compilers.
--- Also, 'Newtype' could witness a non-structural isomorphism.
-class Newtype n o | n -> o where
+-- Since Cabal-3.0 class arguments are in a different order than in @newtype@ package.
+-- This change is to allow usage with @DeriveAnyClass@ (and @DerivingStrategies@, in GHC-8.2).
+-- Unfortunately one have to repeat inner type.
+--
+-- @
+-- newtype New = New Old
+--   deriving anyclass (Newtype Old)
+-- @
+--
+-- Another approach would be to use @TypeFamilies@ (and possibly
+-- compute inner type using "GHC.Generics"), but we think @FunctionalDependencies@
+-- version gives cleaner type signatures.
+--
+class Newtype o n | n -> o where
     pack   :: o -> n
-    unpack :: n -> o
-
-instance Newtype (Identity a) a where
-    pack   = Identity
-    unpack = runIdentity
+#if MIN_VERSION_base(4,7,0)
+    default pack :: Coercible o n => o -> n
+    pack = coerce
+#else
+    default pack :: o -> n
+    pack = unsafeCoerce
+#endif
 
-instance Newtype (Sum a) a where
-    pack   = Sum
-    unpack = getSum
-
-instance Newtype (Product a) a where
-    pack   = Product
-    unpack = getProduct
+    unpack :: n -> o
+#if MIN_VERSION_base(4,7,0)
+    default unpack :: Coercible n o => n -> o
+    unpack = coerce
+#else
+    default unpack :: n -> o
+    unpack = unsafeCoerce
+#endif
 
-instance Newtype (Endo a) (a -> a) where
-    pack   = Endo
-    unpack = appEndo
+instance Newtype a (Identity a)
+instance Newtype a (Sum a)
+instance Newtype a (Product a)
+instance Newtype (a -> a) (Endo a)
 
 -- |
 --
@@ -49,7 +70,7 @@ instance Newtype (Endo a) (a -> a) where
 --
 -- >>> ala (Sum . (+1)) foldMap [1, 2, 3, 4 :: Int]
 -- 10
-ala :: (Newtype n o, Newtype n' o') => (o -> n) -> ((o -> n) -> b -> n') -> (b -> o')
+ala :: (Newtype o n, Newtype o' n') => (o -> n) -> ((o -> n) -> b -> n') -> (b -> o')
 ala pa hof = alaf pa hof id
 
 -- |
@@ -58,13 +79,13 @@ ala pa hof = alaf pa hof id
 -- 12
 --
 -- /Note:/ as with 'ala', the user supplied function for the newtype is /ignored/.
-alaf :: (Newtype n o, Newtype n' o') => (o -> n) -> ((a -> n) -> b -> n') -> (a -> o) -> (b -> o')
+alaf :: (Newtype o n, Newtype o' n') => (o -> n) -> ((a -> n) -> b -> n') -> (a -> o) -> (b -> o')
 alaf _ hof f = unpack . hof (pack . f)
 
 -- | Variant of 'pack', which takes a phantom type.
-pack' :: Newtype n o => (o -> n) -> o -> n
+pack' :: Newtype o n => (o -> n) -> o -> n
 pack' _ = pack
 
 -- | Variant of 'pack', which takes a phantom type.
-unpack' :: Newtype n o => (o -> n) -> n -> o
+unpack' :: Newtype o n => (o -> n) -> n -> o
 unpack' _ = unpack
diff --git a/Cabal/Distribution/Compat/Parsing.hs b/Cabal/Distribution/Compat/Parsing.hs
index ea78746afb8f89b90ff0c48f3ecc921c493abacf..afc995fa02a9dd68b63104f42117cf72ad1944cb 100644
--- a/Cabal/Distribution/Compat/Parsing.hs
+++ b/Cabal/Distribution/Compat/Parsing.hs
@@ -26,7 +26,7 @@ module Distribution.Compat.Parsing
   , many     -- from Control.Applicative
   , sepBy
   , sepBy1
-  -- , sepByNonEmpty
+  , sepByNonEmpty
   , sepEndBy1
   -- , sepEndByNonEmpty
   , sepEndBy
@@ -106,13 +106,11 @@ sepBy1 p sep = (:) <$> p <*> many (sep *> p)
 -- toList <$> sepByNonEmpty p sep
 {-# INLINE sepBy1 #-}
 
-{-
 -- | @sepByNonEmpty p sep@ parses /one/ or more occurrences of @p@, separated
 -- by @sep@. Returns a non-empty list of values returned by @p@.
 sepByNonEmpty :: Alternative m => m a -> m sep -> m (NonEmpty a)
 sepByNonEmpty p sep = (:|) <$> p <*> many (sep *> p)
 {-# INLINE sepByNonEmpty #-}
--}
 
 -- | @sepEndBy1 p sep@ parses /one/ or more occurrences of @p@,
 -- separated and optionally ended by @sep@. Returns a list of values
diff --git a/Cabal/Distribution/Compat/Prelude.hs b/Cabal/Distribution/Compat/Prelude.hs
index f60b8e71ac98adaa97a8f635399c935e97c6055c..c3bc040bb7fca633716ce50fcec7a34cae411cce 100644
--- a/Cabal/Distribution/Compat/Prelude.hs
+++ b/Cabal/Distribution/Compat/Prelude.hs
@@ -59,6 +59,9 @@ module Distribution.Compat.Prelude (
     sort, sortBy,
     nub, nubBy,
 
+    -- * Data.List.NonEmpty
+    NonEmpty((:|)), foldl1, foldr1,
+
     -- * Data.Foldable
     Foldable, foldMap, foldr,
     null, length,
@@ -100,6 +103,7 @@ import Prelude                       as BasePrelude hiding
   ( IO, mapM, mapM_, sequence, null, length, foldr, any, all
   -- partial functions
   , read
+  , foldr1, foldl1
 #if MINVER_base_411
   -- As of base 4.11.0.0 Prelude exports part of Semigroup(..).
   -- Hide this so we instead rely on Distribution.Compat.Semigroup.
@@ -122,6 +126,7 @@ import Data.Foldable                 (length, null)
 
 import Data.Foldable                 (Foldable (foldMap, foldr), find, foldl', for_, traverse_, any, all)
 import Data.Traversable              (Traversable (traverse, sequenceA), for)
+import qualified Data.Foldable
 
 import Control.Applicative           (Alternative (..))
 import Control.DeepSeq               (NFData (..))
@@ -141,6 +146,7 @@ import Data.Char
 import Data.List                     (intercalate, intersperse, isPrefixOf,
                                       isSuffixOf, nub, nubBy, sort, sortBy,
                                       unfoldr)
+import Data.List.NonEmpty            (NonEmpty((:|)))
 import Data.Maybe
 import Data.String                   (IsString (..))
 import Data.Int
@@ -214,3 +220,28 @@ instance (GNFData a, GNFData b) => GNFData (a :+: b) where
   grnf (L1 x) = grnf x
   grnf (R1 x) = grnf x
   {-# INLINEABLE grnf #-}
+
+
+-- TODO: if we want foldr1/foldl1 to work on more than NonEmpty, we
+-- can define a local typeclass 'Foldable1', e.g.
+--
+-- @
+-- class Foldable f => Foldable1 f
+--
+-- instance Foldable1 NonEmpty
+--
+-- foldr1 :: Foldable1 t => (a -> a -> a) -> t a -> a
+-- foldr1 = Data.Foldable.foldr1
+--
+-- foldl1 :: Foldable1 t => (a -> a -> a) -> t a -> a
+-- foldl1 = Data.Foldable.foldl1
+-- @
+--
+
+{-# INLINE foldr1 #-}
+foldr1 :: (a -> a -> a) -> NonEmpty a -> a
+foldr1 = Data.Foldable.foldr1
+
+{-# INLINE foldl1 #-}
+foldl1 :: (a -> a -> a) -> NonEmpty a -> a
+foldl1 = Data.Foldable.foldl1
diff --git a/Cabal/Distribution/Compat/ResponseFile.hs b/Cabal/Distribution/Compat/ResponseFile.hs
new file mode 100755
index 0000000000000000000000000000000000000000..5ddfe57b99bb47898e7e71efdd790502b1f8a67d
--- /dev/null
+++ b/Cabal/Distribution/Compat/ResponseFile.hs
@@ -0,0 +1,68 @@
+{-# LANGUAGE CPP, RankNTypes, FlexibleContexts #-}
+
+-- Compatibility layer for GHC.ResponseFile
+-- Implementation from base 4.12.0 is used.
+-- http://hackage.haskell.org/package/base-4.12.0.0/src/LICENSE
+module Distribution.Compat.ResponseFile (expandResponse) where
+
+import Prelude (mapM)
+import Distribution.Compat.Prelude
+
+import System.Exit
+import System.FilePath
+import System.IO (hPutStrLn, stderr)
+import System.IO.Error
+
+#if MIN_VERSION_base(4,12,0)
+import GHC.ResponseFile (unescapeArgs)
+#else
+
+unescapeArgs :: String -> [String]
+unescapeArgs = filter (not . null) . unescape
+
+data Quoting = NoneQ | SngQ | DblQ
+
+unescape :: String -> [String]
+unescape args = reverse . map reverse $ go args NoneQ False [] []
+    where
+      -- n.b., the order of these cases matters; these are cribbed from gcc
+      -- case 1: end of input
+      go []     _q    _bs   a as = a:as
+      -- case 2: back-slash escape in progress
+      go (c:cs) q     True  a as = go cs q     False (c:a) as
+      -- case 3: no back-slash escape in progress, but got a back-slash
+      go (c:cs) q     False a as
+        | '\\' == c              = go cs q     True  a     as
+      -- case 4: single-quote escaping in progress
+      go (c:cs) SngQ  False a as
+        | '\'' == c              = go cs NoneQ False a     as
+        | otherwise              = go cs SngQ  False (c:a) as
+      -- case 5: double-quote escaping in progress
+      go (c:cs) DblQ  False a as
+        | '"' == c               = go cs NoneQ False a     as
+        | otherwise              = go cs DblQ  False (c:a) as
+      -- case 6: no escaping is in progress
+      go (c:cs) NoneQ False a as
+        | isSpace c              = go cs NoneQ False []    (a:as)
+        | '\'' == c              = go cs SngQ  False a     as
+        | '"'  == c              = go cs DblQ  False a     as
+        | otherwise              = go cs NoneQ False (c:a) as
+
+#endif
+
+expandResponse :: [String] -> IO [String]
+expandResponse = go recursionLimit "."
+  where
+    recursionLimit = 100
+
+    go :: Int -> FilePath -> [String] -> IO [String]
+    go n dir
+      | n >= 0    = fmap concat . mapM (expand n dir)
+      | otherwise = const $ hPutStrLn stderr "Error: response file recursion limit exceeded." >> exitFailure
+
+    expand :: Int -> FilePath -> String -> IO [String]
+    expand n dir arg@('@':f) = readRecursively n (dir </> f) `catchIOError` (const $ print "?" >> return [arg])
+    expand _n _dir x = return [x]
+
+    readRecursively :: Int -> FilePath -> IO [String]
+    readRecursively n f = go (n - 1) (takeDirectory f) =<< unescapeArgs <$> readFile f
diff --git a/Cabal/Distribution/Compat/Semigroup.hs b/Cabal/Distribution/Compat/Semigroup.hs
index d50a93c8da5986c2d99db362f31c35fc64811414..f8ffa95f81c675ee5943bf92bd5e3c4ce5a939b2 100644
--- a/Cabal/Distribution/Compat/Semigroup.hs
+++ b/Cabal/Distribution/Compat/Semigroup.hs
@@ -11,113 +11,54 @@ module Distribution.Compat.Semigroup
     , All(..)
     , Any(..)
 
+    , First'(..)
     , Last'(..)
 
+    , Option'(..)
+
     , gmappend
     , gmempty
     ) where
 
 import Distribution.Compat.Binary (Binary)
 
-import Control.Applicative as App
 import GHC.Generics
-#if __GLASGOW_HASKELL__ >= 711
--- Data.Semigroup is available since GHC 8.0/base-4.9
+-- Data.Semigroup is available since GHC 8.0/base-4.9 in `base`
+-- for older GHC/base, it's provided by `semigroups`
 import Data.Semigroup
 import qualified Data.Monoid as Mon
-#else
--- provide internal simplified non-exposed class for older GHCs
-import Data.Monoid as Mon (Monoid(..), All(..), Any(..), Dual(..))
--- containers
-import Data.Set (Set)
-import Data.IntSet (IntSet)
-import Data.Map (Map)
-import Data.IntMap (IntMap)
-
-
-class Semigroup a where
-    (<>) :: a -> a -> a
-
--- several primitive instances
-instance Semigroup () where
-    _ <> _ = ()
-
-instance Semigroup [a] where
-    (<>) = (++)
-
-instance Semigroup a => Semigroup (Dual a) where
-    Dual a <> Dual b = Dual (b <> a)
-
-instance Semigroup a => Semigroup (Maybe a) where
-    Nothing <> b       = b
-    a       <> Nothing = a
-    Just a  <> Just b  = Just (a <> b)
-
-instance Semigroup (Either a b) where
-    Left _ <> b = b
-    a      <> _ = a
-
-instance Semigroup Ordering where
-    LT <> _ = LT
-    EQ <> y = y
-    GT <> _ = GT
 
-instance Semigroup b => Semigroup (a -> b) where
-    f <> g = \a -> f a <> g a
 
-instance Semigroup All where
-    All a <> All b = All (a && b)
+-- | A copy of 'Data.Semigroup.First'.
+newtype First' a = First' { getFirst' :: a }
+  deriving (Eq, Ord, Show)
 
-instance Semigroup Any where
-    Any a <> Any b = Any (a || b)
+instance Semigroup (First' a) where
+  a <> _ = a
 
-instance (Semigroup a, Semigroup b) => Semigroup (a, b) where
-    (a,b) <> (a',b') = (a<>a',b<>b')
+-- | A copy of 'Data.Semigroup.Last'.
+newtype Last' a = Last' { getLast' :: a }
+  deriving (Eq, Ord, Read, Show, Binary)
 
-instance (Semigroup a, Semigroup b, Semigroup c)
-         => Semigroup (a, b, c) where
-    (a,b,c) <> (a',b',c') = (a<>a',b<>b',c<>c')
-
-instance (Semigroup a, Semigroup b, Semigroup c, Semigroup d)
-         => Semigroup (a, b, c, d) where
-    (a,b,c,d) <> (a',b',c',d') = (a<>a',b<>b',c<>c',d<>d')
-
-instance (Semigroup a, Semigroup b, Semigroup c, Semigroup d, Semigroup e)
-         => Semigroup (a, b, c, d, e) where
-    (a,b,c,d,e) <> (a',b',c',d',e') = (a<>a',b<>b',c<>c',d<>d',e<>e')
-
--- containers instances
-instance Semigroup IntSet where
-  (<>) = mappend
-
-instance Ord a => Semigroup (Set a) where
-  (<>) = mappend
-
-instance Semigroup (IntMap v) where
-  (<>) = mappend
+instance Semigroup (Last' a) where
+  _ <> b = b
 
-instance Ord k => Semigroup (Map k v) where
-  (<>) = mappend
-#endif
+instance Functor Last' where
+  fmap f (Last' x) = Last' (f x)
 
--- | Cabal's own 'Data.Monoid.Last' copy to avoid requiring an orphan
--- 'Binary' instance.
---
--- Once the oldest `binary` version we support provides a 'Binary'
--- instance for 'Data.Monoid.Last' we can remove this one here.
---
--- NB: 'Data.Semigroup.Last' is defined differently and not a 'Monoid'
-newtype Last' a = Last' { getLast' :: Maybe a }
-                deriving (Eq, Ord, Read, Show, Binary,
-                          Functor, App.Applicative, Generic)
+-- | A wrapper around 'Maybe', providing the 'Semigroup' and 'Monoid' instances
+-- implemented for 'Maybe' since @base-4.11@.
+newtype Option' a = Option' { getOption' :: Maybe a }
+  deriving (Eq, Ord, Read, Show, Binary, Functor)
 
-instance Semigroup (Last' a) where
-    x <> Last' Nothing = x
-    _ <> x             = x
+instance Semigroup a => Semigroup (Option' a) where
+  Option' (Just a) <> Option' (Just b) = Option' (Just (a <> b))
+  Option' Nothing  <> b                = b
+  a                <> Option' Nothing  = a
 
-instance Monoid (Last' a) where
-    mempty = Last' Nothing
-    mappend = (<>)
+instance Semigroup a => Monoid (Option' a) where
+  mempty = Option' Nothing
+  mappend = (<>)
 
 -------------------------------------------------------------------------------
 -------------------------------------------------------------------------------
diff --git a/Cabal/Distribution/FieldGrammar/Class.hs b/Cabal/Distribution/FieldGrammar/Class.hs
index e1939fad666d2af0c689f678aa3dec271f4ec682..872b402bb4fa6373703cbe2e24b44569ccf3e673 100644
--- a/Cabal/Distribution/FieldGrammar/Class.hs
+++ b/Cabal/Distribution/FieldGrammar/Class.hs
@@ -33,7 +33,7 @@ class FieldGrammar g where
 
     -- | Field which should be defined, exactly once.
     uniqueFieldAla
-        :: (Parsec b, Pretty b, Newtype b a)
+        :: (Parsec b, Pretty b, Newtype a b)
         => FieldName   -- ^ field name
         -> (a -> b)    -- ^ 'Newtype' pack
         -> ALens' s a  -- ^ lens into the field
@@ -48,7 +48,7 @@ class FieldGrammar g where
 
     -- | Optional field.
     optionalFieldAla
-        :: (Parsec b, Pretty b, Newtype b a)
+        :: (Parsec b, Pretty b, Newtype a b)
         => FieldName          -- ^ field name
         -> (a -> b)           -- ^ 'pack'
         -> ALens' s (Maybe a) -- ^ lens into the field
@@ -56,7 +56,7 @@ class FieldGrammar g where
 
     -- | Optional field with default value.
     optionalFieldDefAla
-        :: (Parsec b, Pretty b, Newtype b a, Eq a)
+        :: (Parsec b, Pretty b, Newtype a b, Eq a)
         => FieldName   -- ^ field name
         -> (a -> b)    -- ^ 'Newtype' pack
         -> ALens' s a  -- ^ @'Lens'' s a@: lens into the field
@@ -88,7 +88,7 @@ class FieldGrammar g where
     -- /Note:/ 'optionalFieldAla' is a @monoidalField@ with 'Last' monoid.
     --
     monoidalFieldAla
-        :: (Parsec b, Pretty b, Monoid a, Newtype b a)
+        :: (Parsec b, Pretty b, Monoid a, Newtype a b)
         => FieldName   -- ^ field name
         -> (a -> b)    -- ^ 'pack'
         -> ALens' s a  -- ^ lens into the field
diff --git a/Cabal/Distribution/FieldGrammar/Parsec.hs b/Cabal/Distribution/FieldGrammar/Parsec.hs
index 45a58079140d7e91a24f5c180c971e679afb07b3..7b712e33448af6dbe9ec2567c05e1b1d58c594d7 100644
--- a/Cabal/Distribution/FieldGrammar/Parsec.hs
+++ b/Cabal/Distribution/FieldGrammar/Parsec.hs
@@ -266,7 +266,7 @@ instance FieldGrammar ParsecFieldGrammar where
                 for_ (Map.toList unknownFields) $ \(name, fields) ->
                     for_ fields $ \(MkNamelessField pos _) ->
                         parseWarning pos PWTUnknownField $
-                            "The field " <> show name <> " is available only since the Cabal specification version " ++ showCabalSpecVersion vs ++ "."
+                            "The field " <> show name <> " is available only since the Cabal specification version " ++ showCabalSpecVersion vs ++ ". This field will be ignored."
 
                 pure def
 
diff --git a/Cabal/Distribution/Fields/ConfVar.hs b/Cabal/Distribution/Fields/ConfVar.hs
index f86a92883fbca20cbfa9f066d01010fc3c3e86f4..083505d1960b3d9d782003d19dce41f6ef35a037 100644
--- a/Cabal/Distribution/Fields/ConfVar.hs
+++ b/Cabal/Distribution/Fields/ConfVar.hs
@@ -37,11 +37,14 @@ parseConditionConfVar args =
 
 type Parser = P.Parsec [SectionArg Position] ()
 
+sepByNonEmpty :: Parser a -> Parser sep -> Parser (NonEmpty a)
+sepByNonEmpty p sep = (:|) <$> p <*> many (sep *> p)
+
 parser :: Parser (Condition ConfVar)
 parser = condOr
   where
-    condOr       = P.sepBy1 condAnd (oper "||") >>= return . foldl1 COr
-    condAnd      = P.sepBy1 cond    (oper "&&") >>= return . foldl1 CAnd
+    condOr       = sepByNonEmpty condAnd (oper "||") >>= return . foldl1 COr
+    condAnd      = sepByNonEmpty cond    (oper "&&") >>= return . foldl1 CAnd
     cond         = P.choice
          [ boolLiteral, parens condOr,  notCond, osCond, archCond, flagCond, implCond ]
 
@@ -63,8 +66,8 @@ parser = condOr
 
     versionRange = expr
       where
-        expr = foldl1 unionVersionRanges     <$> P.sepBy1 term   (oper "||")
-        term = foldl1 intersectVersionRanges <$> P.sepBy1 factor (oper "&&")
+        expr = foldl1 unionVersionRanges     <$> sepByNonEmpty term   (oper "||")
+        term = foldl1 intersectVersionRanges <$> sepByNonEmpty factor (oper "&&")
 
         factor = P.choice
             $ parens expr
diff --git a/Cabal/Distribution/Fields/ParseResult.hs b/Cabal/Distribution/Fields/ParseResult.hs
index e5eb08b493d177ccbe73bc8a227df5478061eb1c..52965e2ea3d70ca5169b505602210c84310878bf 100644
--- a/Cabal/Distribution/Fields/ParseResult.hs
+++ b/Cabal/Distribution/Fields/ParseResult.hs
@@ -50,13 +50,14 @@ emptyPRState = PRState [] [] Nothing
 -- | Destruct a 'ParseResult' into the emitted warnings and either
 -- a successful value or
 -- list of errors and possibly recovered a spec-version declaration.
-runParseResult :: ParseResult a -> ([PWarning], Either (Maybe Version, [PError]) a)
+runParseResult :: ParseResult a -> ([PWarning], Either (Maybe Version, NonEmpty PError) a)
 runParseResult pr = unPR pr emptyPRState failure success
   where
-    failure (PRState warns errs v)   = (warns, Left (v, errs))
-    success (PRState warns [] _)   x = (warns, Right x)
+    failure (PRState warns []         v)   = (warns, Left (v, PError zeroPos "panic" :| []))
+    failure (PRState warns (err:errs) v)   = (warns, Left (v, err :| errs)) where
+    success (PRState warns []         _)   x = (warns, Right x)
     -- If there are any errors, don't return the result
-    success (PRState warns errs v) _ = (warns, Left (v, errs))
+    success (PRState warns (err:errs) v) _ = (warns, Left (v, err :| errs))
 
 instance Functor ParseResult where
     fmap f (PR pr) = PR $ \ !s failure success ->
diff --git a/Cabal/Distribution/Fields/Pretty.hs b/Cabal/Distribution/Fields/Pretty.hs
index cc5d2f6afa85c70497df04e80996a5f528a03e60..9c673a4469832c30c78e60551e0abf2c8d6d4403 100644
--- a/Cabal/Distribution/Fields/Pretty.hs
+++ b/Cabal/Distribution/Fields/Pretty.hs
@@ -39,6 +39,12 @@ data PrettyField ann
   deriving (Functor, Foldable, Traversable)
 
 -- | Prettyprint a list of fields.
+--
+-- Note: the first argument should return 'String's without newlines
+-- and properly prefixes (with @--@) to count as comments.
+-- This unsafety is left in place so one could generate empty lines
+-- between comment lines.
+--
 showFields :: (ann -> [String]) -> [PrettyField ann] -> String
 showFields rann = showFields' rann 4
 
diff --git a/Cabal/Distribution/InstalledPackageInfo.hs b/Cabal/Distribution/InstalledPackageInfo.hs
index 5d0da46d07416771dc86dc188ec12c706bbcc7b1..a92af015c8bf611de3d416c073597cfcbe9a38c3 100644
--- a/Cabal/Distribution/InstalledPackageInfo.hs
+++ b/Cabal/Distribution/InstalledPackageInfo.hs
@@ -26,7 +26,6 @@
 
 module Distribution.InstalledPackageInfo (
         InstalledPackageInfo(..),
-        installedPackageId,
         installedComponentId,
         installedOpenUnitId,
         sourceComponentName,
@@ -50,7 +49,7 @@ import Distribution.CabalSpecVersion         (cabalSpecLatest)
 import Distribution.FieldGrammar
 import Distribution.FieldGrammar.FieldDescrs
 import Distribution.ModuleName
-import Distribution.Package                  hiding (installedPackageId, installedUnitId)
+import Distribution.Package                  hiding (installedUnitId)
 import Distribution.Types.ComponentName
 import Distribution.Utils.Generic            (toUTF8BS)
 
@@ -83,15 +82,6 @@ installedOpenUnitId ipi
 requiredSignatures :: InstalledPackageInfo -> Set ModuleName
 requiredSignatures ipi = openModuleSubstFreeHoles (Map.fromList (instantiatedWith ipi))
 
-{-# DEPRECATED installedPackageId "Use installedUnitId instead" #-}
--- | Backwards compatibility with Cabal pre-1.24.
---
--- This type synonym is slightly awful because in cabal-install
--- we define an 'InstalledPackageId' but it's a ComponentId,
--- not a UnitId!
-installedPackageId :: InstalledPackageInfo -> UnitId
-installedPackageId = installedUnitId
-
 -- -----------------------------------------------------------------------------
 -- Munging
 
@@ -106,15 +96,15 @@ sourceComponentName = CLibName . sourceLibName
 -- /Note:/ errors array /may/ be empty, but the parse is still failed (it's a bug though)
 parseInstalledPackageInfo
     :: String
-    -> Either [String] ([String], InstalledPackageInfo)
+    -> Either (NonEmpty String) ([String], InstalledPackageInfo)
 parseInstalledPackageInfo s = case P.readFields (toUTF8BS s) of
-    Left err -> Left [show err]
+    Left err -> Left (show err :| [])
     Right fs -> case partitionFields fs of
         (fs', _) -> case P.runParseResult $ parseFieldGrammar cabalSpecLatest fs' ipiFieldGrammar of
             (ws, Right x) -> Right (ws', x) where
                 ws' = map (P.showPWarning "") ws
             (_,  Left (_, errs)) -> Left errs' where
-                errs' = map (P.showPError "") errs
+                errs' = fmap (P.showPError "") errs
 
 -- -----------------------------------------------------------------------------
 -- Pretty-printing
diff --git a/Cabal/Distribution/Make.hs b/Cabal/Distribution/Make.hs
index bda5d059a6b06edacc3ea3c2b0aceef63c9de973..cde201eb9c27b736fd7b4d397eb4267bcc92c333 100644
--- a/Cabal/Distribution/Make.hs
+++ b/Cabal/Distribution/Make.hs
@@ -60,7 +60,7 @@
 module Distribution.Make (
         module Distribution.Package,
         License(..), Version,
-        defaultMain, defaultMainArgs, defaultMainNoRead
+        defaultMain, defaultMainArgs
   ) where
 
 import Prelude ()
@@ -70,7 +70,6 @@ import Distribution.Compat.Prelude
 import Distribution.Compat.Exception
 import Distribution.Package
 import Distribution.Simple.Program
-import Distribution.PackageDescription
 import Distribution.Simple.Setup
 import Distribution.Simple.Command
 
@@ -89,10 +88,6 @@ defaultMain = getArgs >>= defaultMainArgs
 defaultMainArgs :: [String] -> IO ()
 defaultMainArgs = defaultMainHelper
 
-{-# DEPRECATED defaultMainNoRead "it ignores its PackageDescription arg" #-}
-defaultMainNoRead :: PackageDescription -> IO ()
-defaultMainNoRead = const defaultMain
-
 defaultMainHelper :: [String] -> IO ()
 defaultMainHelper args =
   case commandsRun (globalCommand commands) commands args of
diff --git a/Cabal/Distribution/ModuleName.hs b/Cabal/Distribution/ModuleName.hs
index bf3729cd49917e79c9a561d01b02869a29190ce3..e004fd1c44cb3368e3bb8639b7e08f1e03976c35 100644
--- a/Cabal/Distribution/ModuleName.hs
+++ b/Cabal/Distribution/ModuleName.hs
@@ -19,7 +19,6 @@ module Distribution.ModuleName (
         components,
         toFilePath,
         main,
-        simple,
         -- * Internal
         validModuleComponent,
   ) where
@@ -66,10 +65,6 @@ validModuleComponent []     = False
 validModuleComponent (c:cs) = isUpper c
                            && all validModuleChar cs
 
-{-# DEPRECATED simple "use ModuleName.fromString instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-simple :: String -> ModuleName
-simple str = ModuleName (stlFromStrings [str])
-
 -- | Construct a 'ModuleName' from a valid module name 'String'.
 --
 -- This is just a convenience function intended for valid module strings. It is
diff --git a/Cabal/Distribution/Package.hs b/Cabal/Distribution/Package.hs
index 0b467d11de4a07732a35fcea33003281bd6000a4..6c2950b26f01e1fff373a6cb8d9a95601685bd67 100644
--- a/Cabal/Distribution/Package.hs
+++ b/Cabal/Distribution/Package.hs
@@ -28,7 +28,6 @@ module Distribution.Package
   , Package(..), packageName, packageVersion
   , HasMungedPackageId(..), mungedName', mungedVersion'
   , HasUnitId(..)
-  , installedPackageId
   , PackageInstalled(..)
   ) where
 
@@ -87,11 +86,6 @@ instance HasMungedPackageId MungedPackageId where
 class Package pkg => HasUnitId pkg where
   installedUnitId :: pkg -> UnitId
 
-{-# DEPRECATED installedPackageId "Use installedUnitId instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
--- | Compatibility wrapper for Cabal pre-1.24.
-installedPackageId :: HasUnitId pkg => pkg -> UnitId
-installedPackageId = installedUnitId
-
 -- | Class of installed packages.
 --
 -- The primary data type which is an instance of this package is
diff --git a/Cabal/Distribution/PackageDescription.hs b/Cabal/Distribution/PackageDescription.hs
index 072989f27e0aed54d3ba8900f18b8593dc79f932..e50ed77a62f08a471a2bed2eac9e66e2f451a104 100644
--- a/Cabal/Distribution/PackageDescription.hs
+++ b/Cabal/Distribution/PackageDescription.hs
@@ -17,7 +17,6 @@ module Distribution.PackageDescription (
         specVersion,
         buildType,
         license,
-        descCabalVersion,
         BuildType(..),
         knownBuildTypes,
         allLibraries,
@@ -35,7 +34,6 @@ module Distribution.PackageDescription (
         hasLibs,
         explicitLibModules,
         libModulesAutogen,
-        libModules,
 
         -- ** Executables
         Executable(..),
diff --git a/Cabal/Distribution/PackageDescription/Check.hs b/Cabal/Distribution/PackageDescription/Check.hs
index 9ce93be61d9e466eaddfc7c36e89e51a78858915..0f2d21a2773067358561fcc5d01376b797dd54aa 100644
--- a/Cabal/Distribution/PackageDescription/Check.hs
+++ b/Cabal/Distribution/PackageDescription/Check.hs
@@ -270,6 +270,12 @@ checkLibrary pkg lib =
            "An 'autogen-module' is neither on 'exposed-modules' or "
         ++ "'other-modules'."
 
+    -- check that all autogen-includes appear on includes or install-includes
+  , check
+      (not $ and $ map (flip elem (allExplicitIncludes lib)) (view L.autogenIncludes lib)) $
+      PackageBuildImpossible $
+           "An include in 'autogen-includes' is neither in 'includes' or "
+        ++ "'install-includes'."
   ]
 
   where
@@ -282,6 +288,9 @@ checkLibrary pkg lib =
     moduleDuplicates = dups (explicitLibModules lib ++
                              map moduleReexportName (reexportedModules lib))
 
+allExplicitIncludes :: L.HasBuildInfo a => a -> [FilePath]
+allExplicitIncludes x = view L.includes x ++ view L.installIncludes x
+
 checkExecutable :: PackageDescription -> Executable -> [PackageCheck]
 checkExecutable pkg exe =
   catMaybes [
@@ -315,6 +324,11 @@ checkExecutable pkg exe =
       PackageBuildImpossible $
            "On executable '" ++ prettyShow (exeName exe) ++ "' an 'autogen-module' is not "
         ++ "on 'other-modules'"
+
+    -- check that all autogen-includes appear on includes
+  , check
+      (not $ and $ map (flip elem (view L.includes exe)) (view L.autogenIncludes exe)) $
+      PackageBuildImpossible "An include in 'autogen-includes' is not in 'includes'."
   ]
   where
     moduleDuplicates = dups (exeModules exe)
@@ -355,13 +369,15 @@ checkTestSuite pkg test =
 
     -- check that all autogen-modules appear on other-modules
   , check
-      (not $ and $ map
-        (flip elem (testModules test))
-        (testModulesAutogen test)
-      ) $
+      (not $ and $ map (flip elem (testModules test)) (testModulesAutogen test)) $
       PackageBuildImpossible $
            "On test suite '" ++ prettyShow (testName test) ++ "' an 'autogen-module' is not "
         ++ "on 'other-modules'"
+
+    -- check that all autogen-includes appear on includes
+  , check
+      (not $ and $ map (flip elem (view L.includes test)) (view L.autogenIncludes test)) $
+      PackageBuildImpossible "An include in 'autogen-includes' is not in 'includes'."
   ]
   where
     moduleDuplicates = dups $ testModules test
@@ -404,13 +420,15 @@ checkBenchmark _pkg bm =
 
     -- check that all autogen-modules appear on other-modules
   , check
-      (not $ and $ map
-        (flip elem (benchmarkModules bm))
-        (benchmarkModulesAutogen bm)
-      ) $
+      (not $ and $ map (flip elem (benchmarkModules bm)) (benchmarkModulesAutogen bm)) $
       PackageBuildImpossible $
              "On benchmark '" ++ prettyShow (benchmarkName bm) ++ "' an 'autogen-module' is "
           ++ "not on 'other-modules'"
+
+    -- check that all autogen-includes appear on includes
+  , check
+      (not $ and $ map (flip elem (view L.includes bm)) (view L.autogenIncludes bm)) $
+      PackageBuildImpossible "An include in 'autogen-includes' is not in 'includes'."
   ]
   where
     moduleDuplicates = dups $ benchmarkModules bm
@@ -1348,7 +1366,7 @@ checkCabalVersion pkg =
            && isNothing (setupBuildInfo pkg)
            && buildType pkg == Custom) $
       PackageDistSuspiciousWarn $
-           "From version 1.24 cabal supports specifiying explicit dependencies "
+           "From version 1.24 cabal supports specifying explicit dependencies "
         ++ "for Custom setup scripts. Consider using cabal-version >= 1.24 and "
         ++ "adding a 'custom-setup' section with a 'setup-depends' field "
         ++ "that specifies the dependencies of the Setup.hs script itself. "
diff --git a/Cabal/Distribution/PackageDescription/Configuration.hs b/Cabal/Distribution/PackageDescription/Configuration.hs
index 264c1d4b8969af00eaa4fb9e262932f0ba945a6a..d42c8ed5fb66573d2ec6f6c9329baa070fb6eff5 100644
--- a/Cabal/Distribution/PackageDescription/Configuration.hs
+++ b/Cabal/Distribution/PackageDescription/Configuration.hs
@@ -17,7 +17,6 @@
 
 module Distribution.PackageDescription.Configuration (
     finalizePD,
-    finalizePackageDescription,
     flattenPackageDescription,
 
     -- Utils
@@ -113,8 +112,8 @@ simplifyWithSysParams os arch cinfo cond = (cond', flags)
 parseCondition :: CabalParsing m => m (Condition ConfVar)
 parseCondition = condOr
   where
-    condOr   = sepBy1 condAnd (oper "||") >>= return . foldl1 COr
-    condAnd  = sepBy1 cond (oper "&&")>>= return . foldl1 CAnd
+    condOr   = sepByNonEmpty condAnd (oper "||") >>= return . foldl1 COr
+    condAnd  = sepByNonEmpty cond (oper "&&")>>= return . foldl1 CAnd
     -- TODO: try?
     cond     = sp >> (boolLiteral <|> inparens condOr <|> notCond <|> osCond
                       <|> archCond <|> flagCond <|> implCond )
@@ -492,20 +491,6 @@ finalizePD userflags enabled satisfyDep
                       then DepOk
                       else MissingDeps missingDeps
 
-{-# DEPRECATED finalizePackageDescription "This function now always assumes tests and benchmarks are disabled; use finalizePD with ComponentRequestedSpec to specify something more specific. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-finalizePackageDescription ::
-     FlagAssignment  -- ^ Explicitly specified flag assignments
-  -> (Dependency -> Bool) -- ^ Is a given dependency satisfiable from the set of
-                          -- available packages?  If this is unknown then use
-                          -- True.
-  -> Platform      -- ^ The 'Arch' and 'OS'
-  -> CompilerInfo  -- ^ Compiler information
-  -> [Dependency]  -- ^ Additional constraints
-  -> GenericPackageDescription
-  -> Either [Dependency]
-            (PackageDescription, FlagAssignment)
-finalizePackageDescription flags = finalizePD flags defaultComponentRequestedSpec
-
 {-
 let tst_p = (CondNode [1::Int] [Distribution.Package.Dependency "a" AnyVersion] [])
 let tst_p2 = (CondNode [1::Int] [Distribution.Package.Dependency "a" (EarlierVersion (Version [1,0] [])), Distribution.Package.Dependency "a" (LaterVersion (Version [2,0] []))] [])
diff --git a/Cabal/Distribution/PackageDescription/FieldGrammar.hs b/Cabal/Distribution/PackageDescription/FieldGrammar.hs
index 2d813ffe5f2d6d947bf8aab3674472f973d48b53..285a01b5e45aa2f2946c98cb8a33e0c6be4b7a90 100644
--- a/Cabal/Distribution/PackageDescription/FieldGrammar.hs
+++ b/Cabal/Distribution/PackageDescription/FieldGrammar.hs
@@ -427,6 +427,8 @@ buildInfoFieldGrammar = BuildInfo
     <*> monoidalFieldAla "extra-lib-dirs"       (alaList' FSep FilePathNT)    L.extraLibDirs
     <*> monoidalFieldAla "include-dirs"         (alaList' FSep FilePathNT)    L.includeDirs
     <*> monoidalFieldAla "includes"             (alaList' FSep FilePathNT)    L.includes
+    <*> monoidalFieldAla "autogen-includes"     (alaList' FSep FilePathNT)    L.autogenIncludes
+        ^^^ availableSince CabalSpecV3_0 []
     <*> monoidalFieldAla "install-includes"     (alaList' FSep FilePathNT)    L.installIncludes
     <*> optionsFieldGrammar
     <*> profOptionsFieldGrammar
diff --git a/Cabal/Distribution/Parsec/Newtypes.hs b/Cabal/Distribution/Parsec/Newtypes.hs
index b9e5687648ee12f9847c9b0c65365813c2c3141d..0cd218cb01917943261f6491637886da3478034a 100644
--- a/Cabal/Distribution/Parsec/Newtypes.hs
+++ b/Cabal/Distribution/Parsec/Newtypes.hs
@@ -34,6 +34,7 @@ import Distribution.Compat.Prelude
 import Prelude ()
 
 import Data.Functor.Identity         (Identity (..))
+import Data.Proxy                    (Proxy (..))
 import Distribution.CabalSpecVersion
 import Distribution.Compiler         (CompilerFlavor)
 import Distribution.License          (License)
@@ -61,13 +62,10 @@ data FSep = FSep
 -- | Paragraph fill list without commas. Displayed with 'fsep'.
 data NoCommaFSep = NoCommaFSep
 
--- | Proxy, internal to this module.
-data P sep = P
-
 class    Sep sep  where
-    prettySep :: P sep -> [Doc] -> Doc
+    prettySep :: Proxy sep -> [Doc] -> Doc
 
-    parseSep :: CabalParsing m => P sep -> m a -> m [a]
+    parseSep :: CabalParsing m => Proxy sep -> m a -> m [a]
 
 instance Sep CommaVCat where
     prettySep  _ = vcat . punctuate comma
@@ -95,7 +93,7 @@ instance Sep NoCommaFSep where
 
 -- | List separated with optional commas. Displayed with @sep@, arguments of
 -- type @a@ are parsed and pretty-printed as @b@.
-newtype List sep b a = List { getList :: [a] }
+newtype List sep b a = List { _getList :: [a] }
 
 -- | 'alaList' and 'alaList'' are simply 'List', with additional phantom
 -- arguments to constraint the resulting type
@@ -113,22 +111,18 @@ alaList _ = List
 alaList' :: sep -> (a -> b) -> [a] -> List sep b a
 alaList' _ _ = List
 
-instance Newtype (List sep wrapper a) [a] where
-    pack = List
-    unpack = getList
+instance Newtype [a] (List sep wrapper a)
 
-instance (Newtype b a, Sep sep, Parsec b) => Parsec (List sep b a) where
-    parsec   = pack . map (unpack :: b -> a) <$> parseSep (P :: P sep) parsec
+instance (Newtype a b, Sep sep, Parsec b) => Parsec (List sep b a) where
+    parsec   = pack . map (unpack :: b -> a) <$> parseSep (Proxy :: Proxy sep) parsec
 
-instance (Newtype b a, Sep sep, Pretty b) => Pretty (List sep b a) where
-    pretty = prettySep (P :: P sep) . map (pretty . (pack :: a -> b)) . unpack
+instance (Newtype a b, Sep sep, Pretty b) => Pretty (List sep b a) where
+    pretty = prettySep (Proxy :: Proxy sep) . map (pretty . (pack :: a -> b)) . unpack
 
 -- | Haskell string or @[^ ,]+@
 newtype Token = Token { getToken :: String }
 
-instance Newtype Token String where
-    pack = Token
-    unpack = getToken
+instance Newtype String Token
 
 instance Parsec Token where
     parsec = pack <$> parsecToken
@@ -139,9 +133,7 @@ instance Pretty Token where
 -- | Haskell string or @[^ ]+@
 newtype Token' = Token' { getToken' :: String }
 
-instance Newtype Token' String where
-    pack = Token'
-    unpack = getToken'
+instance Newtype String Token'
 
 instance Parsec Token' where
     parsec = pack <$> parsecToken'
@@ -152,9 +144,7 @@ instance Pretty Token' where
 -- | Either @"quoted"@ or @un-quoted@.
 newtype MQuoted a = MQuoted { getMQuoted :: a }
 
-instance Newtype (MQuoted a) a where
-    pack = MQuoted
-    unpack = getMQuoted
+instance Newtype a (MQuoted a)
 
 instance Parsec a => Parsec (MQuoted a) where
     parsec = pack <$> parsecMaybeQuoted parsec
@@ -173,9 +163,7 @@ instance Pretty a => Pretty (MQuoted a)  where
 --
 newtype SpecVersion = SpecVersion { getSpecVersion :: Either Version VersionRange }
 
-instance Newtype SpecVersion (Either Version VersionRange) where
-    pack = SpecVersion
-    unpack = getSpecVersion
+instance Newtype (Either Version VersionRange) SpecVersion
 
 instance Parsec SpecVersion where
     parsec = pack <$> parsecSpecVersion
@@ -198,9 +186,7 @@ specVersionFromRange versionRange = case asVersionIntervals versionRange of
 -- | SPDX License expression or legacy license
 newtype SpecLicense = SpecLicense { getSpecLicense :: Either SPDX.License License }
 
-instance Newtype SpecLicense (Either SPDX.License License) where
-    pack = SpecLicense
-    unpack = getSpecLicense
+instance Newtype (Either SPDX.License License) SpecLicense
 
 instance Parsec SpecLicense where
     parsec = do
@@ -215,9 +201,7 @@ instance Pretty SpecLicense where
 -- | Version range or just version
 newtype TestedWith = TestedWith { getTestedWith :: (CompilerFlavor, VersionRange) }
 
-instance Newtype TestedWith (CompilerFlavor, VersionRange) where
-    pack = TestedWith
-    unpack = getTestedWith
+instance Newtype (CompilerFlavor, VersionRange) TestedWith
 
 instance Parsec TestedWith where
     parsec = pack <$> parsecTestedWith
@@ -229,9 +213,7 @@ instance Pretty TestedWith where
 -- | Filepath are parsed as 'Token'.
 newtype FilePathNT = FilePathNT { getFilePathNT :: String }
 
-instance Newtype FilePathNT String where
-    pack = FilePathNT
-    unpack = getFilePathNT
+instance Newtype String FilePathNT
 
 instance Parsec FilePathNT where
     parsec = pack <$> parsecToken
diff --git a/Cabal/Distribution/SPDX/LicenseExceptionId.hs b/Cabal/Distribution/SPDX/LicenseExceptionId.hs
index 8c69d01edb5f1942903fdb7b6abba556fff2b880..ffceb4798473c4ffbcb92f95e43153dffe3fe047 100644
--- a/Cabal/Distribution/SPDX/LicenseExceptionId.hs
+++ b/Cabal/Distribution/SPDX/LicenseExceptionId.hs
@@ -17,6 +17,8 @@ import Distribution.Parsec
 import Distribution.Utils.Generic (isAsciiAlphaNum)
 import Distribution.SPDX.LicenseListVersion
 
+import qualified Data.Binary.Get as Binary
+import qualified Data.Binary.Put as Binary
 import qualified Data.Map.Strict as Map
 import qualified Distribution.Compat.CharParsing as P
 import qualified Text.PrettyPrint as Disp
@@ -43,27 +45,35 @@ data LicenseExceptionId
     | GCC_exception_2_0 -- ^ @GCC-exception-2.0@, GCC Runtime Library exception 2.0
     | GCC_exception_3_1 -- ^ @GCC-exception-3.1@, GCC Runtime Library exception 3.1
     | Gnu_javamail_exception -- ^ @gnu-javamail-exception@, GNU JavaMail exception
-    | GPL_CC_1_0 -- ^ @GPL-CC-1.0@, GPL Cooperation Commitment 1.0, SPDX License List 3.5
+    | GPL_CC_1_0 -- ^ @GPL-CC-1.0@, GPL Cooperation Commitment 1.0, SPDX License List 3.6
     | I2p_gpl_java_exception -- ^ @i2p-gpl-java-exception@, i2p GPL+Java Exception
     | Libtool_exception -- ^ @Libtool-exception@, Libtool Exception
     | Linux_syscall_note -- ^ @Linux-syscall-note@, Linux Syscall Note
-    | LLVM_exception -- ^ @LLVM-exception@, LLVM Exception, SPDX License List 3.2, SPDX License List 3.5
+    | LLVM_exception -- ^ @LLVM-exception@, LLVM Exception, SPDX License List 3.2, SPDX License List 3.6
     | LZMA_exception -- ^ @LZMA-exception@, LZMA exception
     | Mif_exception -- ^ @mif-exception@, Macros and Inline Functions Exception
     | Nokia_Qt_exception_1_1 -- ^ @Nokia-Qt-exception-1.1@, Nokia Qt LGPL exception 1.1, SPDX License List 3.0, SPDX License List 3.2
-    | OCaml_LGPL_linking_exception -- ^ @OCaml-LGPL-linking-exception@, OCaml LGPL Linking Exception, SPDX License List 3.5
+    | OCaml_LGPL_linking_exception -- ^ @OCaml-LGPL-linking-exception@, OCaml LGPL Linking Exception, SPDX License List 3.6
     | OCCT_exception_1_0 -- ^ @OCCT-exception-1.0@, Open CASCADE Exception 1.0
-    | OpenJDK_assembly_exception_1_0 -- ^ @OpenJDK-assembly-exception-1.0@, OpenJDK Assembly exception 1.0, SPDX License List 3.2, SPDX License List 3.5
+    | OpenJDK_assembly_exception_1_0 -- ^ @OpenJDK-assembly-exception-1.0@, OpenJDK Assembly exception 1.0, SPDX License List 3.2, SPDX License List 3.6
     | Openvpn_openssl_exception -- ^ @openvpn-openssl-exception@, OpenVPN OpenSSL Exception
-    | PS_or_PDF_font_exception_20170817 -- ^ @PS-or-PDF-font-exception-20170817@, PS/PDF font exception (2017-08-17), SPDX License List 3.2, SPDX License List 3.5
-    | Qt_GPL_exception_1_0 -- ^ @Qt-GPL-exception-1.0@, Qt GPL exception 1.0, SPDX License List 3.2, SPDX License List 3.5
-    | Qt_LGPL_exception_1_1 -- ^ @Qt-LGPL-exception-1.1@, Qt LGPL exception 1.1, SPDX License List 3.2, SPDX License List 3.5
+    | PS_or_PDF_font_exception_20170817 -- ^ @PS-or-PDF-font-exception-20170817@, PS/PDF font exception (2017-08-17), SPDX License List 3.2, SPDX License List 3.6
+    | Qt_GPL_exception_1_0 -- ^ @Qt-GPL-exception-1.0@, Qt GPL exception 1.0, SPDX License List 3.2, SPDX License List 3.6
+    | Qt_LGPL_exception_1_1 -- ^ @Qt-LGPL-exception-1.1@, Qt LGPL exception 1.1, SPDX License List 3.2, SPDX License List 3.6
     | Qwt_exception_1_0 -- ^ @Qwt-exception-1.0@, Qwt exception 1.0
+    | Swift_exception -- ^ @Swift-exception@, Swift Exception, SPDX License List 3.6
     | U_boot_exception_2_0 -- ^ @u-boot-exception-2.0@, U-Boot exception 2.0
+    | Universal_FOSS_exception_1_0 -- ^ @Universal-FOSS-exception-1.0@, Universal FOSS Exception, Version 1.0, SPDX License List 3.6
     | WxWindows_exception_3_1 -- ^ @WxWindows-exception-3.1@, WxWindows Library Exception 3.1
   deriving (Eq, Ord, Enum, Bounded, Show, Read, Typeable, Data, Generic)
 
-instance Binary LicenseExceptionId
+instance Binary LicenseExceptionId where
+    put = Binary.putWord8 . fromIntegral . fromEnum
+    get = do
+        i <- Binary.getWord8
+        if i > fromIntegral (fromEnum (maxBound :: LicenseExceptionId))
+        then fail "Too large LicenseExceptionId tag"
+        else return (toEnum (fromIntegral i))
 
 instance Pretty LicenseExceptionId where
     pretty = Disp.text . licenseExceptionId
@@ -116,7 +126,9 @@ licenseExceptionId PS_or_PDF_font_exception_20170817 = "PS-or-PDF-font-exception
 licenseExceptionId Qt_GPL_exception_1_0 = "Qt-GPL-exception-1.0"
 licenseExceptionId Qt_LGPL_exception_1_1 = "Qt-LGPL-exception-1.1"
 licenseExceptionId Qwt_exception_1_0 = "Qwt-exception-1.0"
+licenseExceptionId Swift_exception = "Swift-exception"
 licenseExceptionId U_boot_exception_2_0 = "u-boot-exception-2.0"
+licenseExceptionId Universal_FOSS_exception_1_0 = "Universal-FOSS-exception-1.0"
 licenseExceptionId WxWindows_exception_3_1 = "WxWindows-exception-3.1"
 
 -- | License name, e.g. @"GNU General Public License v2.0 only"@
@@ -153,7 +165,9 @@ licenseExceptionName PS_or_PDF_font_exception_20170817 = "PS/PDF font exception
 licenseExceptionName Qt_GPL_exception_1_0 = "Qt GPL exception 1.0"
 licenseExceptionName Qt_LGPL_exception_1_1 = "Qt LGPL exception 1.1"
 licenseExceptionName Qwt_exception_1_0 = "Qwt exception 1.0"
+licenseExceptionName Swift_exception = "Swift Exception"
 licenseExceptionName U_boot_exception_2_0 = "U-Boot exception 2.0"
+licenseExceptionName Universal_FOSS_exception_1_0 = "Universal FOSS Exception, Version 1.0"
 licenseExceptionName WxWindows_exception_3_1 = "WxWindows Library Exception 3.1"
 
 -------------------------------------------------------------------------------
@@ -174,7 +188,7 @@ licenseExceptionIdList LicenseListVersion_3_2 =
     , Qt_LGPL_exception_1_1
     ]
     ++ bulkOfLicenses
-licenseExceptionIdList LicenseListVersion_3_5 =
+licenseExceptionIdList LicenseListVersion_3_6 =
     [ GPL_CC_1_0
     , LLVM_exception
     , OCaml_LGPL_linking_exception
@@ -182,6 +196,8 @@ licenseExceptionIdList LicenseListVersion_3_5 =
     , PS_or_PDF_font_exception_20170817
     , Qt_GPL_exception_1_0
     , Qt_LGPL_exception_1_1
+    , Swift_exception
+    , Universal_FOSS_exception_1_0
     ]
     ++ bulkOfLicenses
 
@@ -189,7 +205,7 @@ licenseExceptionIdList LicenseListVersion_3_5 =
 mkLicenseExceptionId :: LicenseListVersion -> String -> Maybe LicenseExceptionId
 mkLicenseExceptionId LicenseListVersion_3_0 s = Map.lookup s stringLookup_3_0
 mkLicenseExceptionId LicenseListVersion_3_2 s = Map.lookup s stringLookup_3_2
-mkLicenseExceptionId LicenseListVersion_3_5 s = Map.lookup s stringLookup_3_5
+mkLicenseExceptionId LicenseListVersion_3_6 s = Map.lookup s stringLookup_3_6
 
 stringLookup_3_0 :: Map String LicenseExceptionId
 stringLookup_3_0 = Map.fromList $ map (\i -> (licenseExceptionId i, i)) $
@@ -199,9 +215,9 @@ stringLookup_3_2 :: Map String LicenseExceptionId
 stringLookup_3_2 = Map.fromList $ map (\i -> (licenseExceptionId i, i)) $
     licenseExceptionIdList LicenseListVersion_3_2
 
-stringLookup_3_5 :: Map String LicenseExceptionId
-stringLookup_3_5 = Map.fromList $ map (\i -> (licenseExceptionId i, i)) $
-    licenseExceptionIdList LicenseListVersion_3_5
+stringLookup_3_6 :: Map String LicenseExceptionId
+stringLookup_3_6 = Map.fromList $ map (\i -> (licenseExceptionId i, i)) $
+    licenseExceptionIdList LicenseListVersion_3_6
 
 --  | License exceptions in all SPDX License lists
 bulkOfLicenses :: [LicenseExceptionId]
diff --git a/Cabal/Distribution/SPDX/LicenseId.hs b/Cabal/Distribution/SPDX/LicenseId.hs
index 9a546c5289237467086357a05f124f779365bfb2..6643276f1aa0fb147bb74d16436c20528f455dd0 100644
--- a/Cabal/Distribution/SPDX/LicenseId.hs
+++ b/Cabal/Distribution/SPDX/LicenseId.hs
@@ -20,6 +20,8 @@ import Distribution.Parsec
 import Distribution.Utils.Generic (isAsciiAlphaNum)
 import Distribution.SPDX.LicenseListVersion
 
+import qualified Data.Binary.Get as Binary
+import qualified Data.Binary.Put as Binary
 import qualified Data.Map.Strict as Map
 import qualified Distribution.Compat.CharParsing as P
 import qualified Text.PrettyPrint as Disp
@@ -43,8 +45,8 @@ data LicenseId
     | AFL_3_0 -- ^ @AFL-3.0@, Academic Free License v3.0
     | Afmparse -- ^ @Afmparse@, Afmparse License
     | AGPL_1_0 -- ^ @AGPL-1.0@, Affero General Public License v1.0, SPDX License List 3.0
-    | AGPL_1_0_only -- ^ @AGPL-1.0-only@, Affero General Public License v1.0 only, SPDX License List 3.2, SPDX License List 3.5
-    | AGPL_1_0_or_later -- ^ @AGPL-1.0-or-later@, Affero General Public License v1.0 or later, SPDX License List 3.2, SPDX License List 3.5
+    | AGPL_1_0_only -- ^ @AGPL-1.0-only@, Affero General Public License v1.0 only, SPDX License List 3.2, SPDX License List 3.6
+    | AGPL_1_0_or_later -- ^ @AGPL-1.0-or-later@, Affero General Public License v1.0 or later, SPDX License List 3.2, SPDX License List 3.6
     | AGPL_3_0_only -- ^ @AGPL-3.0-only@, GNU Affero General Public License v3.0 only
     | AGPL_3_0_or_later -- ^ @AGPL-3.0-or-later@, GNU Affero General Public License v3.0 or later
     | Aladdin -- ^ @Aladdin@, Aladdin Free Public License
@@ -70,6 +72,8 @@ data LicenseId
     | Beerware -- ^ @Beerware@, Beerware License
     | BitTorrent_1_0 -- ^ @BitTorrent-1.0@, BitTorrent Open Source License v1.0
     | BitTorrent_1_1 -- ^ @BitTorrent-1.1@, BitTorrent Open Source License v1.1
+    | Blessing -- ^ @blessing@, SQLite Blessing, SPDX License List 3.6
+    | BlueOak_1_0_0 -- ^ @BlueOak-1.0.0@, Blue Oak Model License 1.0.0, SPDX License List 3.6
     | Borceux -- ^ @Borceux@, Borceux license
     | BSD_1_Clause -- ^ @BSD-1-Clause@, BSD 1-Clause License
     | BSD_2_Clause_FreeBSD -- ^ @BSD-2-Clause-FreeBSD@, BSD 2-Clause FreeBSD License
@@ -82,6 +86,7 @@ data LicenseId
     | BSD_3_Clause_No_Nuclear_License_2014 -- ^ @BSD-3-Clause-No-Nuclear-License-2014@, BSD 3-Clause No Nuclear License 2014
     | BSD_3_Clause_No_Nuclear_License -- ^ @BSD-3-Clause-No-Nuclear-License@, BSD 3-Clause No Nuclear License
     | BSD_3_Clause_No_Nuclear_Warranty -- ^ @BSD-3-Clause-No-Nuclear-Warranty@, BSD 3-Clause No Nuclear Warranty
+    | BSD_3_Clause_Open_MPI -- ^ @BSD-3-Clause-Open-MPI@, BSD 3-Clause Open MPI variant, SPDX License List 3.6
     | BSD_3_Clause -- ^ @BSD-3-Clause@, BSD 3-Clause "New" or "Revised" License
     | BSD_4_Clause_UC -- ^ @BSD-4-Clause-UC@, BSD-4-Clause (University of California-Specific)
     | BSD_4_Clause -- ^ @BSD-4-Clause@, BSD 4-Clause "Original" or "Old" License
@@ -122,6 +127,7 @@ data LicenseId
     | CC_BY_SA_2_5 -- ^ @CC-BY-SA-2.5@, Creative Commons Attribution Share Alike 2.5 Generic
     | CC_BY_SA_3_0 -- ^ @CC-BY-SA-3.0@, Creative Commons Attribution Share Alike 3.0 Unported
     | CC_BY_SA_4_0 -- ^ @CC-BY-SA-4.0@, Creative Commons Attribution Share Alike 4.0 International
+    | CC_PDDC -- ^ @CC-PDDC@, Creative Commons Public Domain Dedication and Certification, SPDX License List 3.6
     | CC0_1_0 -- ^ @CC0-1.0@, Creative Commons Zero v1.0 Universal
     | CDDL_1_0 -- ^ @CDDL-1.0@, Common Development and Distribution License 1.0
     | CDDL_1_1 -- ^ @CDDL-1.1@, Common Development and Distribution License 1.1
@@ -133,15 +139,15 @@ data LicenseId
     | CECILL_2_1 -- ^ @CECILL-2.1@, CeCILL Free Software License Agreement v2.1
     | CECILL_B -- ^ @CECILL-B@, CeCILL-B Free Software License Agreement
     | CECILL_C -- ^ @CECILL-C@, CeCILL-C Free Software License Agreement
-    | CERN_OHL_1_1 -- ^ @CERN-OHL-1.1@, CERN Open Hardware License v1.1, SPDX License List 3.5
-    | CERN_OHL_1_2 -- ^ @CERN-OHL-1.2@, CERN Open Hardware Licence v1.2, SPDX License List 3.5
+    | CERN_OHL_1_1 -- ^ @CERN-OHL-1.1@, CERN Open Hardware License v1.1, SPDX License List 3.6
+    | CERN_OHL_1_2 -- ^ @CERN-OHL-1.2@, CERN Open Hardware Licence v1.2, SPDX License List 3.6
     | ClArtistic -- ^ @ClArtistic@, Clarified Artistic License
     | CNRI_Jython -- ^ @CNRI-Jython@, CNRI Jython License
     | CNRI_Python_GPL_Compatible -- ^ @CNRI-Python-GPL-Compatible@, CNRI Python Open Source GPL Compatible License Agreement
     | CNRI_Python -- ^ @CNRI-Python@, CNRI Python License
     | Condor_1_1 -- ^ @Condor-1.1@, Condor Public License v1.1
-    | Copyleft_next_0_3_0 -- ^ @copyleft-next-0.3.0@, copyleft-next 0.3.0, SPDX License List 3.5
-    | Copyleft_next_0_3_1 -- ^ @copyleft-next-0.3.1@, copyleft-next 0.3.1, SPDX License List 3.5
+    | Copyleft_next_0_3_0 -- ^ @copyleft-next-0.3.0@, copyleft-next 0.3.0, SPDX License List 3.6
+    | Copyleft_next_0_3_1 -- ^ @copyleft-next-0.3.1@, copyleft-next 0.3.1, SPDX License List 3.6
     | CPAL_1_0 -- ^ @CPAL-1.0@, Common Public Attribution License 1.0
     | CPL_1_0 -- ^ @CPL-1.0@, Common Public License 1.0
     | CPOL_1_02 -- ^ @CPOL-1.02@, Code Project Open License 1.02
@@ -196,7 +202,7 @@ data LicenseId
     | GPL_3_0_or_later -- ^ @GPL-3.0-or-later@, GNU General Public License v3.0 or later
     | GSOAP_1_3b -- ^ @gSOAP-1.3b@, gSOAP Public License v1.3b
     | HaskellReport -- ^ @HaskellReport@, Haskell Language Report License
-    | HPND_sell_variant -- ^ @HPND-sell-variant@, Historical Permission Notice and Disclaimer - sell variant, SPDX License List 3.5
+    | HPND_sell_variant -- ^ @HPND-sell-variant@, Historical Permission Notice and Disclaimer - sell variant, SPDX License List 3.6
     | HPND -- ^ @HPND@, Historical Permission Notice and Disclaimer
     | IBM_pibs -- ^ @IBM-pibs@, IBM PowerPC Initialization and Boot Software
     | ICU -- ^ @ICU@, ICU License
@@ -212,7 +218,7 @@ data LicenseId
     | IPL_1_0 -- ^ @IPL-1.0@, IBM Public License v1.0
     | ISC -- ^ @ISC@, ISC License
     | JasPer_2_0 -- ^ @JasPer-2.0@, JasPer License
-    | JPNIC -- ^ @JPNIC@, Japan Network Information Center License, SPDX License List 3.5
+    | JPNIC -- ^ @JPNIC@, Japan Network Information Center License, SPDX License List 3.6
     | JSON -- ^ @JSON@, JSON License
     | LAL_1_2 -- ^ @LAL-1.2@, Licence Art Libre 1.2
     | LAL_1_3 -- ^ @LAL-1.3@, Licence Art Libre 1.3
@@ -225,13 +231,13 @@ data LicenseId
     | LGPL_3_0_only -- ^ @LGPL-3.0-only@, GNU Lesser General Public License v3.0 only
     | LGPL_3_0_or_later -- ^ @LGPL-3.0-or-later@, GNU Lesser General Public License v3.0 or later
     | LGPLLR -- ^ @LGPLLR@, Lesser General Public License For Linguistic Resources
-    | Libpng_2_0 -- ^ @libpng-2.0@, PNG Reference Library version 2, SPDX License List 3.5
+    | Libpng_2_0 -- ^ @libpng-2.0@, PNG Reference Library version 2, SPDX License List 3.6
     | Libpng -- ^ @Libpng@, libpng License
     | Libtiff -- ^ @libtiff@, libtiff License
     | LiLiQ_P_1_1 -- ^ @LiLiQ-P-1.1@, Licence Libre du Québec – Permissive version 1.1
     | LiLiQ_R_1_1 -- ^ @LiLiQ-R-1.1@, Licence Libre du Québec – Réciprocité version 1.1
     | LiLiQ_Rplus_1_1 -- ^ @LiLiQ-Rplus-1.1@, Licence Libre du Québec – Réciprocité forte version 1.1
-    | Linux_OpenIB -- ^ @Linux-OpenIB@, Linux Kernel Variant of OpenIB.org license, SPDX License List 3.2, SPDX License List 3.5
+    | Linux_OpenIB -- ^ @Linux-OpenIB@, Linux Kernel Variant of OpenIB.org license, SPDX License List 3.2, SPDX License List 3.6
     | LPL_1_02 -- ^ @LPL-1.02@, Lucent Public License v1.02
     | LPL_1_0 -- ^ @LPL-1.0@, Lucent Public License Version 1.0
     | LPPL_1_0 -- ^ @LPPL-1.0@, LaTeX Project Public License v1.0
@@ -241,7 +247,7 @@ data LicenseId
     | LPPL_1_3c -- ^ @LPPL-1.3c@, LaTeX Project Public License v1.3c
     | MakeIndex -- ^ @MakeIndex@, MakeIndex License
     | MirOS -- ^ @MirOS@, MirOS License
-    | MIT_0 -- ^ @MIT-0@, MIT No Attribution, SPDX License List 3.2, SPDX License List 3.5
+    | MIT_0 -- ^ @MIT-0@, MIT No Attribution, SPDX License List 3.2, SPDX License List 3.6
     | MIT_advertising -- ^ @MIT-advertising@, Enlightenment License (e16)
     | MIT_CMU -- ^ @MIT-CMU@, CMU License
     | MIT_enna -- ^ @MIT-enna@, enna License
@@ -280,12 +286,12 @@ data LicenseId
     | OCCT_PL -- ^ @OCCT-PL@, Open CASCADE Technology Public License
     | OCLC_2_0 -- ^ @OCLC-2.0@, OCLC Research Public License 2.0
     | ODbL_1_0 -- ^ @ODbL-1.0@, ODC Open Database License v1.0
-    | ODC_By_1_0 -- ^ @ODC-By-1.0@, Open Data Commons Attribution License v1.0, SPDX License List 3.2, SPDX License List 3.5
+    | ODC_By_1_0 -- ^ @ODC-By-1.0@, Open Data Commons Attribution License v1.0, SPDX License List 3.2, SPDX License List 3.6
     | OFL_1_0 -- ^ @OFL-1.0@, SIL Open Font License 1.0
     | OFL_1_1 -- ^ @OFL-1.1@, SIL Open Font License 1.1
-    | OGL_UK_1_0 -- ^ @OGL-UK-1.0@, Open Government Licence v1.0, SPDX License List 3.5
-    | OGL_UK_2_0 -- ^ @OGL-UK-2.0@, Open Government Licence v2.0, SPDX License List 3.5
-    | OGL_UK_3_0 -- ^ @OGL-UK-3.0@, Open Government Licence v3.0, SPDX License List 3.5
+    | OGL_UK_1_0 -- ^ @OGL-UK-1.0@, Open Government Licence v1.0, SPDX License List 3.6
+    | OGL_UK_2_0 -- ^ @OGL-UK-2.0@, Open Government Licence v2.0, SPDX License List 3.6
+    | OGL_UK_3_0 -- ^ @OGL-UK-3.0@, Open Government Licence v3.0, SPDX License List 3.6
     | OGTSL -- ^ @OGTSL@, Open Group Test Suite License
     | OLDAP_1_1 -- ^ @OLDAP-1.1@, Open LDAP Public License v1.1
     | OLDAP_1_2 -- ^ @OLDAP-1.2@, Open LDAP Public License v1.2
@@ -312,6 +318,7 @@ data LicenseId
     | OSL_2_0 -- ^ @OSL-2.0@, Open Software License 2.0
     | OSL_2_1 -- ^ @OSL-2.1@, Open Software License 2.1
     | OSL_3_0 -- ^ @OSL-3.0@, Open Software License 3.0
+    | Parity_6_0_0 -- ^ @Parity-6.0.0@, The Parity Public License 6.0.0, SPDX License List 3.6
     | PDDL_1_0 -- ^ @PDDL-1.0@, ODC Public Domain Dedication & License 1.0
     | PHP_3_01 -- ^ @PHP-3.01@, PHP License v3.01
     | PHP_3_0 -- ^ @PHP-3.0@, PHP License v3.0
@@ -333,11 +340,13 @@ data LicenseId
     | SAX_PD -- ^ @SAX-PD@, Sax Public Domain Notice
     | Saxpath -- ^ @Saxpath@, Saxpath License
     | SCEA -- ^ @SCEA@, SCEA Shared Source License
-    | Sendmail_8_23 -- ^ @Sendmail-8.23@, Sendmail License 8.23, SPDX License List 3.5
+    | Sendmail_8_23 -- ^ @Sendmail-8.23@, Sendmail License 8.23, SPDX License List 3.6
     | Sendmail -- ^ @Sendmail@, Sendmail License
     | SGI_B_1_0 -- ^ @SGI-B-1.0@, SGI Free Software License B v1.0
     | SGI_B_1_1 -- ^ @SGI-B-1.1@, SGI Free Software License B v1.1
     | SGI_B_2_0 -- ^ @SGI-B-2.0@, SGI Free Software License B v2.0
+    | SHL_0_51 -- ^ @SHL-0.51@, Solderpad Hardware License, Version 0.51, SPDX License List 3.6
+    | SHL_0_5 -- ^ @SHL-0.5@, Solderpad Hardware License v0.5, SPDX License List 3.6
     | SimPL_2_0 -- ^ @SimPL-2.0@, Simple Public License 2.0
     | SISSL_1_2 -- ^ @SISSL-1.2@, Sun Industry Standards Source License v1.2
     | SISSL -- ^ @SISSL@, Sun Industry Standards Source License v1.1
@@ -349,16 +358,17 @@ data LicenseId
     | Spencer_94 -- ^ @Spencer-94@, Spencer License 94
     | Spencer_99 -- ^ @Spencer-99@, Spencer License 99
     | SPL_1_0 -- ^ @SPL-1.0@, Sun Public License v1.0
+    | SSPL_1_0 -- ^ @SSPL-1.0@, Server Side Public License, v 1, SPDX License List 3.6
     | SugarCRM_1_1_3 -- ^ @SugarCRM-1.1.3@, SugarCRM Public License v1.1.3
     | SWL -- ^ @SWL@, Scheme Widget Library (SWL) Software License Agreement
-    | TAPR_OHL_1_0 -- ^ @TAPR-OHL-1.0@, TAPR Open Hardware License v1.0, SPDX License List 3.5
+    | TAPR_OHL_1_0 -- ^ @TAPR-OHL-1.0@, TAPR Open Hardware License v1.0, SPDX License List 3.6
     | TCL -- ^ @TCL@, TCL/TK License
     | TCP_wrappers -- ^ @TCP-wrappers@, TCP Wrappers License
     | TMate -- ^ @TMate@, TMate Open Source License
     | TORQUE_1_1 -- ^ @TORQUE-1.1@, TORQUE v2.5+ Software License v1.1
     | TOSL -- ^ @TOSL@, Trusster Open Source License
-    | TU_Berlin_1_0 -- ^ @TU-Berlin-1.0@, Technische Universitaet Berlin License 1.0, SPDX License List 3.2, SPDX License List 3.5
-    | TU_Berlin_2_0 -- ^ @TU-Berlin-2.0@, Technische Universitaet Berlin License 2.0, SPDX License List 3.2, SPDX License List 3.5
+    | TU_Berlin_1_0 -- ^ @TU-Berlin-1.0@, Technische Universitaet Berlin License 1.0, SPDX License List 3.2, SPDX License List 3.6
+    | TU_Berlin_2_0 -- ^ @TU-Berlin-2.0@, Technische Universitaet Berlin License 2.0, SPDX License List 3.2, SPDX License List 3.6
     | Unicode_DFS_2015 -- ^ @Unicode-DFS-2015@, Unicode License Agreement - Data Files and Software (2015)
     | Unicode_DFS_2016 -- ^ @Unicode-DFS-2016@, Unicode License Agreement - Data Files and Software (2016)
     | Unicode_TOU -- ^ @Unicode-TOU@, Unicode Terms of Use
@@ -393,7 +403,15 @@ data LicenseId
     | ZPL_2_1 -- ^ @ZPL-2.1@, Zope Public License 2.1
   deriving (Eq, Ord, Enum, Bounded, Show, Read, Typeable, Data, Generic)
 
-instance Binary LicenseId
+instance Binary LicenseId where
+    -- Word16 is encoded in big endianess
+    -- https://github.com/kolmodin/binary/blob/master/src/Data/Binary/Class.hs#L220-LL227
+    put = Binary.putWord16be . fromIntegral . fromEnum
+    get = do
+        i <- Binary.getWord16be
+        if i > fromIntegral (fromEnum (maxBound :: LicenseId))
+        then fail "Too large LicenseId tag"
+        else return (toEnum (fromIntegral i))
 
 instance Pretty LicenseId where
     pretty = Disp.text . licenseId
@@ -501,6 +519,8 @@ licenseId Barr = "Barr"
 licenseId Beerware = "Beerware"
 licenseId BitTorrent_1_0 = "BitTorrent-1.0"
 licenseId BitTorrent_1_1 = "BitTorrent-1.1"
+licenseId Blessing = "blessing"
+licenseId BlueOak_1_0_0 = "BlueOak-1.0.0"
 licenseId Borceux = "Borceux"
 licenseId BSD_1_Clause = "BSD-1-Clause"
 licenseId BSD_2_Clause_FreeBSD = "BSD-2-Clause-FreeBSD"
@@ -513,6 +533,7 @@ licenseId BSD_3_Clause_LBNL = "BSD-3-Clause-LBNL"
 licenseId BSD_3_Clause_No_Nuclear_License_2014 = "BSD-3-Clause-No-Nuclear-License-2014"
 licenseId BSD_3_Clause_No_Nuclear_License = "BSD-3-Clause-No-Nuclear-License"
 licenseId BSD_3_Clause_No_Nuclear_Warranty = "BSD-3-Clause-No-Nuclear-Warranty"
+licenseId BSD_3_Clause_Open_MPI = "BSD-3-Clause-Open-MPI"
 licenseId BSD_3_Clause = "BSD-3-Clause"
 licenseId BSD_4_Clause_UC = "BSD-4-Clause-UC"
 licenseId BSD_4_Clause = "BSD-4-Clause"
@@ -553,6 +574,7 @@ licenseId CC_BY_SA_2_0 = "CC-BY-SA-2.0"
 licenseId CC_BY_SA_2_5 = "CC-BY-SA-2.5"
 licenseId CC_BY_SA_3_0 = "CC-BY-SA-3.0"
 licenseId CC_BY_SA_4_0 = "CC-BY-SA-4.0"
+licenseId CC_PDDC = "CC-PDDC"
 licenseId CC0_1_0 = "CC0-1.0"
 licenseId CDDL_1_0 = "CDDL-1.0"
 licenseId CDDL_1_1 = "CDDL-1.1"
@@ -743,6 +765,7 @@ licenseId OSL_1_1 = "OSL-1.1"
 licenseId OSL_2_0 = "OSL-2.0"
 licenseId OSL_2_1 = "OSL-2.1"
 licenseId OSL_3_0 = "OSL-3.0"
+licenseId Parity_6_0_0 = "Parity-6.0.0"
 licenseId PDDL_1_0 = "PDDL-1.0"
 licenseId PHP_3_01 = "PHP-3.01"
 licenseId PHP_3_0 = "PHP-3.0"
@@ -769,6 +792,8 @@ licenseId Sendmail = "Sendmail"
 licenseId SGI_B_1_0 = "SGI-B-1.0"
 licenseId SGI_B_1_1 = "SGI-B-1.1"
 licenseId SGI_B_2_0 = "SGI-B-2.0"
+licenseId SHL_0_51 = "SHL-0.51"
+licenseId SHL_0_5 = "SHL-0.5"
 licenseId SimPL_2_0 = "SimPL-2.0"
 licenseId SISSL_1_2 = "SISSL-1.2"
 licenseId SISSL = "SISSL"
@@ -780,6 +805,7 @@ licenseId Spencer_86 = "Spencer-86"
 licenseId Spencer_94 = "Spencer-94"
 licenseId Spencer_99 = "Spencer-99"
 licenseId SPL_1_0 = "SPL-1.0"
+licenseId SSPL_1_0 = "SSPL-1.0"
 licenseId SugarCRM_1_1_3 = "SugarCRM-1.1.3"
 licenseId SWL = "SWL"
 licenseId TAPR_OHL_1_0 = "TAPR-OHL-1.0"
@@ -865,6 +891,8 @@ licenseName Barr = "Barr License"
 licenseName Beerware = "Beerware License"
 licenseName BitTorrent_1_0 = "BitTorrent Open Source License v1.0"
 licenseName BitTorrent_1_1 = "BitTorrent Open Source License v1.1"
+licenseName Blessing = "SQLite Blessing"
+licenseName BlueOak_1_0_0 = "Blue Oak Model License 1.0.0"
 licenseName Borceux = "Borceux license"
 licenseName BSD_1_Clause = "BSD 1-Clause License"
 licenseName BSD_2_Clause_FreeBSD = "BSD 2-Clause FreeBSD License"
@@ -877,6 +905,7 @@ licenseName BSD_3_Clause_LBNL = "Lawrence Berkeley National Labs BSD variant lic
 licenseName BSD_3_Clause_No_Nuclear_License_2014 = "BSD 3-Clause No Nuclear License 2014"
 licenseName BSD_3_Clause_No_Nuclear_License = "BSD 3-Clause No Nuclear License"
 licenseName BSD_3_Clause_No_Nuclear_Warranty = "BSD 3-Clause No Nuclear Warranty"
+licenseName BSD_3_Clause_Open_MPI = "BSD 3-Clause Open MPI variant"
 licenseName BSD_3_Clause = "BSD 3-Clause \"New\" or \"Revised\" License"
 licenseName BSD_4_Clause_UC = "BSD-4-Clause (University of California-Specific)"
 licenseName BSD_4_Clause = "BSD 4-Clause \"Original\" or \"Old\" License"
@@ -917,6 +946,7 @@ licenseName CC_BY_SA_2_0 = "Creative Commons Attribution Share Alike 2.0 Generic
 licenseName CC_BY_SA_2_5 = "Creative Commons Attribution Share Alike 2.5 Generic"
 licenseName CC_BY_SA_3_0 = "Creative Commons Attribution Share Alike 3.0 Unported"
 licenseName CC_BY_SA_4_0 = "Creative Commons Attribution Share Alike 4.0 International"
+licenseName CC_PDDC = "Creative Commons Public Domain Dedication and Certification"
 licenseName CC0_1_0 = "Creative Commons Zero v1.0 Universal"
 licenseName CDDL_1_0 = "Common Development and Distribution License 1.0"
 licenseName CDDL_1_1 = "Common Development and Distribution License 1.1"
@@ -1107,6 +1137,7 @@ licenseName OSL_1_1 = "Open Software License 1.1"
 licenseName OSL_2_0 = "Open Software License 2.0"
 licenseName OSL_2_1 = "Open Software License 2.1"
 licenseName OSL_3_0 = "Open Software License 3.0"
+licenseName Parity_6_0_0 = "The Parity Public License 6.0.0"
 licenseName PDDL_1_0 = "ODC Public Domain Dedication & License 1.0"
 licenseName PHP_3_01 = "PHP License v3.01"
 licenseName PHP_3_0 = "PHP License v3.0"
@@ -1133,6 +1164,8 @@ licenseName Sendmail = "Sendmail License"
 licenseName SGI_B_1_0 = "SGI Free Software License B v1.0"
 licenseName SGI_B_1_1 = "SGI Free Software License B v1.1"
 licenseName SGI_B_2_0 = "SGI Free Software License B v2.0"
+licenseName SHL_0_51 = "Solderpad Hardware License, Version 0.51"
+licenseName SHL_0_5 = "Solderpad Hardware License v0.5"
 licenseName SimPL_2_0 = "Simple Public License 2.0"
 licenseName SISSL_1_2 = "Sun Industry Standards Source License v1.2"
 licenseName SISSL = "Sun Industry Standards Source License v1.1"
@@ -1144,6 +1177,7 @@ licenseName Spencer_86 = "Spencer License 86"
 licenseName Spencer_94 = "Spencer License 94"
 licenseName Spencer_99 = "Spencer License 99"
 licenseName SPL_1_0 = "Sun Public License v1.0"
+licenseName SSPL_1_0 = "Server Side Public License, v 1"
 licenseName SugarCRM_1_1_3 = "SugarCRM Public License v1.1.3"
 licenseName SWL = "Scheme Widget Library (SWL) Software License Agreement"
 licenseName TAPR_OHL_1_0 = "TAPR Open Hardware License v1.0"
@@ -1231,6 +1265,8 @@ licenseIsOsiApproved Barr = False
 licenseIsOsiApproved Beerware = False
 licenseIsOsiApproved BitTorrent_1_0 = False
 licenseIsOsiApproved BitTorrent_1_1 = False
+licenseIsOsiApproved Blessing = False
+licenseIsOsiApproved BlueOak_1_0_0 = False
 licenseIsOsiApproved Borceux = False
 licenseIsOsiApproved BSD_1_Clause = False
 licenseIsOsiApproved BSD_2_Clause_FreeBSD = False
@@ -1239,10 +1275,11 @@ licenseIsOsiApproved BSD_2_Clause_Patent = True
 licenseIsOsiApproved BSD_2_Clause = True
 licenseIsOsiApproved BSD_3_Clause_Attribution = False
 licenseIsOsiApproved BSD_3_Clause_Clear = False
-licenseIsOsiApproved BSD_3_Clause_LBNL = False
+licenseIsOsiApproved BSD_3_Clause_LBNL = True
 licenseIsOsiApproved BSD_3_Clause_No_Nuclear_License_2014 = False
 licenseIsOsiApproved BSD_3_Clause_No_Nuclear_License = False
 licenseIsOsiApproved BSD_3_Clause_No_Nuclear_Warranty = False
+licenseIsOsiApproved BSD_3_Clause_Open_MPI = False
 licenseIsOsiApproved BSD_3_Clause = True
 licenseIsOsiApproved BSD_4_Clause_UC = False
 licenseIsOsiApproved BSD_4_Clause = False
@@ -1283,6 +1320,7 @@ licenseIsOsiApproved CC_BY_SA_2_0 = False
 licenseIsOsiApproved CC_BY_SA_2_5 = False
 licenseIsOsiApproved CC_BY_SA_3_0 = False
 licenseIsOsiApproved CC_BY_SA_4_0 = False
+licenseIsOsiApproved CC_PDDC = False
 licenseIsOsiApproved CC0_1_0 = False
 licenseIsOsiApproved CDDL_1_0 = True
 licenseIsOsiApproved CDDL_1_1 = False
@@ -1473,6 +1511,7 @@ licenseIsOsiApproved OSL_1_1 = False
 licenseIsOsiApproved OSL_2_0 = True
 licenseIsOsiApproved OSL_2_1 = True
 licenseIsOsiApproved OSL_3_0 = True
+licenseIsOsiApproved Parity_6_0_0 = False
 licenseIsOsiApproved PDDL_1_0 = False
 licenseIsOsiApproved PHP_3_01 = False
 licenseIsOsiApproved PHP_3_0 = True
@@ -1499,6 +1538,8 @@ licenseIsOsiApproved Sendmail = False
 licenseIsOsiApproved SGI_B_1_0 = False
 licenseIsOsiApproved SGI_B_1_1 = False
 licenseIsOsiApproved SGI_B_2_0 = False
+licenseIsOsiApproved SHL_0_51 = False
+licenseIsOsiApproved SHL_0_5 = False
 licenseIsOsiApproved SimPL_2_0 = True
 licenseIsOsiApproved SISSL_1_2 = False
 licenseIsOsiApproved SISSL = True
@@ -1510,6 +1551,7 @@ licenseIsOsiApproved Spencer_86 = False
 licenseIsOsiApproved Spencer_94 = False
 licenseIsOsiApproved Spencer_99 = False
 licenseIsOsiApproved SPL_1_0 = True
+licenseIsOsiApproved SSPL_1_0 = False
 licenseIsOsiApproved SugarCRM_1_1_3 = False
 licenseIsOsiApproved SWL = False
 licenseIsOsiApproved TAPR_OHL_1_0 = False
@@ -1572,9 +1614,13 @@ licenseIdList LicenseListVersion_3_2 =
     , TU_Berlin_2_0
     ]
     ++ bulkOfLicenses
-licenseIdList LicenseListVersion_3_5 =
+licenseIdList LicenseListVersion_3_6 =
     [ AGPL_1_0_only
     , AGPL_1_0_or_later
+    , Blessing
+    , BlueOak_1_0_0
+    , BSD_3_Clause_Open_MPI
+    , CC_PDDC
     , CERN_OHL_1_1
     , CERN_OHL_1_2
     , Copyleft_next_0_3_0
@@ -1588,7 +1634,11 @@ licenseIdList LicenseListVersion_3_5 =
     , OGL_UK_1_0
     , OGL_UK_2_0
     , OGL_UK_3_0
+    , Parity_6_0_0
     , Sendmail_8_23
+    , SHL_0_51
+    , SHL_0_5
+    , SSPL_1_0
     , TAPR_OHL_1_0
     , TU_Berlin_1_0
     , TU_Berlin_2_0
@@ -1599,7 +1649,7 @@ licenseIdList LicenseListVersion_3_5 =
 mkLicenseId :: LicenseListVersion -> String -> Maybe LicenseId
 mkLicenseId LicenseListVersion_3_0 s = Map.lookup s stringLookup_3_0
 mkLicenseId LicenseListVersion_3_2 s = Map.lookup s stringLookup_3_2
-mkLicenseId LicenseListVersion_3_5 s = Map.lookup s stringLookup_3_5
+mkLicenseId LicenseListVersion_3_6 s = Map.lookup s stringLookup_3_6
 
 stringLookup_3_0 :: Map String LicenseId
 stringLookup_3_0 = Map.fromList $ map (\i -> (licenseId i, i)) $
@@ -1609,9 +1659,9 @@ stringLookup_3_2 :: Map String LicenseId
 stringLookup_3_2 = Map.fromList $ map (\i -> (licenseId i, i)) $
     licenseIdList LicenseListVersion_3_2
 
-stringLookup_3_5 :: Map String LicenseId
-stringLookup_3_5 = Map.fromList $ map (\i -> (licenseId i, i)) $
-    licenseIdList LicenseListVersion_3_5
+stringLookup_3_6 :: Map String LicenseId
+stringLookup_3_6 = Map.fromList $ map (\i -> (licenseId i, i)) $
+    licenseIdList LicenseListVersion_3_6
 
 --  | Licenses in all SPDX License lists
 bulkOfLicenses :: [LicenseId]
diff --git a/Cabal/Distribution/SPDX/LicenseListVersion.hs b/Cabal/Distribution/SPDX/LicenseListVersion.hs
index 82d8cf18816d8d620a6891eba0991c6e4d9a610b..9e6a880babf75ef9ec6c18d11e8cd287dd2d0ca8 100644
--- a/Cabal/Distribution/SPDX/LicenseListVersion.hs
+++ b/Cabal/Distribution/SPDX/LicenseListVersion.hs
@@ -9,10 +9,11 @@ import Distribution.CabalSpecVersion
 data LicenseListVersion
     = LicenseListVersion_3_0
     | LicenseListVersion_3_2
-    | LicenseListVersion_3_5
+    | LicenseListVersion_3_6
   deriving (Eq, Ord, Show, Enum, Bounded)
 
 cabalSpecVersionToSPDXListVersion :: CabalSpecVersion -> LicenseListVersion
-cabalSpecVersionToSPDXListVersion CabalSpecV3_0 = LicenseListVersion_3_5
+cabalSpecVersionToSPDXListVersion CabalSpecV3_2 = LicenseListVersion_3_6
+cabalSpecVersionToSPDXListVersion CabalSpecV3_0 = LicenseListVersion_3_6
 cabalSpecVersionToSPDXListVersion CabalSpecV2_4 = LicenseListVersion_3_2
 cabalSpecVersionToSPDXListVersion _             = LicenseListVersion_3_0
diff --git a/Cabal/Distribution/Simple.hs b/Cabal/Distribution/Simple.hs
index 6399f769626d88c4b32a90caabfc6928650c208d..e632acc88e8a188726313f0bb79d521ccc9ec968 100644
--- a/Cabal/Distribution/Simple.hs
+++ b/Cabal/Distribution/Simple.hs
@@ -1,6 +1,6 @@
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE RankNTypes #-}
-
+{-# LANGUAGE LambdaCase #-}
 -----------------------------------------------------------------------------
 -- |
 -- Module      :  Distribution.Simple
@@ -52,13 +52,12 @@ module Distribution.Simple (
         -- ** Standard sets of hooks
         simpleUserHooks,
         autoconfUserHooks,
-        defaultUserHooks, emptyUserHooks,
-        -- ** Utils
-        defaultHookedPackageDesc
+        emptyUserHooks,
   ) where
 
-import Prelude ()
 import Control.Exception (try)
+
+import Prelude ()
 import Distribution.Compat.Prelude
 
 -- local
@@ -101,6 +100,7 @@ import System.Directory   (removeFile, doesFileExist
                           ,doesDirectoryExist, removeDirectoryRecursive)
 import System.Exit                          (exitWith,ExitCode(..))
 import System.FilePath                      (searchPathSeparator, takeDirectory, (</>), splitDirectories, dropDrive)
+import Distribution.Compat.ResponseFile (expandResponse)
 import Distribution.Compat.Directory        (makeAbsolute)
 import Distribution.Compat.Environment      (getEnvironment)
 import Distribution.Compat.GetShortPathName (getShortPathName)
@@ -149,8 +149,9 @@ defaultMainWithHooksNoReadArgs hooks pkg_descr =
   defaultMainHelper hooks { readDesc = return (Just pkg_descr) }
 
 defaultMainHelper :: UserHooks -> Args -> IO ()
-defaultMainHelper hooks args = topHandler $
-  case commandsRun (globalCommand commands) commands args of
+defaultMainHelper hooks args = topHandler $ do
+  args' <- expandResponse args
+  case commandsRun (globalCommand commands) commands args' of
     CommandHelp   help                 -> printHelp help
     CommandList   opts                 -> printOptionsList opts
     CommandErrors errs                 -> printErrors errs
@@ -178,6 +179,7 @@ defaultMainHelper hooks args = topHandler $
       [configureCommand progs `commandAddAction`
         \fs as -> configureAction hooks fs as >> return ()
       ,buildCommand     progs `commandAddAction` buildAction        hooks
+      ,showBuildInfoCommand progs `commandAddAction` showBuildInfoAction    hooks
       ,replCommand      progs `commandAddAction` replAction         hooks
       ,installCommand         `commandAddAction` installAction      hooks
       ,copyCommand            `commandAddAction` copyAction         hooks
@@ -259,10 +261,37 @@ buildAction hooks flags args = do
              (buildProgramArgs flags')
              (withPrograms lbi)
 
-  hookedAction preBuild buildHook postBuild
+  hookedAction verbosity preBuild buildHook postBuild
                (return lbi { withPrograms = progs })
                hooks flags' { buildArgs = args } args
 
+showBuildInfoAction :: UserHooks -> ShowBuildInfoFlags -> Args -> IO ()
+showBuildInfoAction hooks (ShowBuildInfoFlags flags fileOutput) args = do
+  distPref <- findDistPrefOrDefault (buildDistPref flags)
+  let verbosity = fromFlag $ buildVerbosity flags
+  lbi <- getBuildConfig hooks verbosity distPref
+  let flags' = flags { buildDistPref = toFlag distPref
+                     , buildCabalFilePath = maybeToFlag (cabalFilePath lbi)
+                     }
+
+  progs <- reconfigurePrograms verbosity
+             (buildProgramPaths flags')
+             (buildProgramArgs flags')
+             (withPrograms lbi)
+
+  pbi <- preBuild hooks args flags'
+  let lbi' = lbi { withPrograms = progs }
+      pkg_descr0 = localPkgDescr lbi'
+      pkg_descr = updatePackageDescription pbi pkg_descr0
+      -- TODO: Somehow don't ignore build hook?
+  buildInfoString <- showBuildInfo pkg_descr lbi' flags
+
+  case fileOutput of
+    Nothing -> putStr buildInfoString
+    Just fp -> writeFile fp buildInfoString
+
+  postBuild hooks args flags' pkg_descr lbi'
+
 replAction :: UserHooks -> ReplFlags -> Args -> IO ()
 replAction hooks flags args = do
   distPref <- findDistPrefOrDefault (replDistPref flags)
@@ -280,7 +309,7 @@ replAction hooks flags args = do
   -- takes the args explicitly.  UGH.   -- ezyang
   pbi <- preRepl hooks args flags'
   let pkg_descr0 = localPkgDescr lbi
-  sanityCheckHookedBuildInfo pkg_descr0 pbi
+  sanityCheckHookedBuildInfo verbosity pkg_descr0 pbi
   let pkg_descr = updatePackageDescription pbi pkg_descr0
       lbi' = lbi { withPrograms = progs
                  , localPkgDescr = pkg_descr }
@@ -295,7 +324,7 @@ hscolourAction hooks flags args = do
     let flags' = flags { hscolourDistPref = toFlag distPref
                        , hscolourCabalFilePath = maybeToFlag (cabalFilePath lbi)}
 
-    hookedAction preHscolour hscolourHook postHscolour
+    hookedAction verbosity preHscolour hscolourHook postHscolour
                  (getBuildConfig hooks verbosity distPref)
                  hooks flags' args
 
@@ -311,7 +340,7 @@ doctestAction hooks flags args = do
              (doctestProgramArgs  flags')
              (withPrograms lbi)
 
-  hookedAction preDoctest doctestHook postDoctest
+  hookedAction verbosity preDoctest doctestHook postDoctest
                (return lbi { withPrograms = progs })
                hooks flags' args
 
@@ -328,7 +357,7 @@ haddockAction hooks flags args = do
              (haddockProgramArgs flags')
              (withPrograms lbi)
 
-  hookedAction preHaddock haddockHook postHaddock
+  hookedAction verbosity preHaddock haddockHook postHaddock
                (return lbi { withPrograms = progs })
                hooks flags' { haddockArgs = args } args
 
@@ -354,7 +383,7 @@ cleanAction hooks flags args = do
     let pkg_descr0 = flattenPackageDescription ppd
     -- We don't sanity check for clean as an error
     -- here would prevent cleaning:
-    --sanityCheckHookedBuildInfo pkg_descr0 pbi
+    --sanityCheckHookedBuildInfo verbosity pkg_descr0 pbi
     let pkg_descr = updatePackageDescription pbi pkg_descr0
 
     cleanHook hooks pkg_descr () hooks flags'
@@ -369,7 +398,7 @@ copyAction hooks flags args = do
     lbi <- getBuildConfig hooks verbosity distPref
     let flags' = flags { copyDistPref = toFlag distPref
                        , copyCabalFilePath = maybeToFlag (cabalFilePath lbi)}
-    hookedAction preCopy copyHook postCopy
+    hookedAction verbosity preCopy copyHook postCopy
                  (getBuildConfig hooks verbosity distPref)
                  hooks flags' { copyArgs = args } args
 
@@ -380,15 +409,14 @@ installAction hooks flags args = do
     lbi <- getBuildConfig hooks verbosity distPref
     let flags' = flags { installDistPref = toFlag distPref
                        , installCabalFilePath = maybeToFlag (cabalFilePath lbi)}
-    hookedAction preInst instHook postInst
+    hookedAction verbosity preInst instHook postInst
                  (getBuildConfig hooks verbosity distPref)
                  hooks flags' args
 
 sdistAction :: UserHooks -> SDistFlags -> Args -> IO ()
-sdistAction hooks flags args = do
+sdistAction hooks flags _args = do
     distPref <- findDistPrefOrDefault (sDistDistPref flags)
-    let flags' = flags { sDistDistPref = toFlag distPref }
-    pbi <- preSDist hooks args flags'
+    let pbi   = emptyHookedBuildInfo
 
     mlbi <- maybeGetPersistBuildConfig distPref
 
@@ -405,12 +433,11 @@ sdistAction hooks flags args = do
     (_, ppd) <- confPkgDescr hooks verbosity Nothing
 
     let pkg_descr0 = flattenPackageDescription ppd
-    sanityCheckHookedBuildInfo pkg_descr0 pbi
+    sanityCheckHookedBuildInfo verbosity pkg_descr0 pbi
     let pkg_descr = updatePackageDescription pbi pkg_descr0
         mlbi' = fmap (\lbi -> lbi { localPkgDescr = pkg_descr }) mlbi
 
-    sDistHook hooks pkg_descr mlbi' hooks flags'
-    postSDist hooks args flags' pkg_descr mlbi'
+    sdist pkg_descr mlbi' flags srcPref (allSuffixHandlers hooks)
   where
     verbosity = fromFlag (sDistVerbosity flags)
 
@@ -420,13 +447,7 @@ testAction hooks flags args = do
     let verbosity = fromFlag $ testVerbosity flags
         flags' = flags { testDistPref = toFlag distPref }
 
-    localBuildInfo <- getBuildConfig hooks verbosity distPref
-    let pkg_descr = localPkgDescr localBuildInfo
-    -- It is safe to do 'runTests' before the new test handler because the
-    -- default action is a no-op and if the package uses the old test interface
-    -- the new handler will find no tests.
-    runTests hooks args False pkg_descr localBuildInfo
-    hookedActionWithArgs preTest testHook postTest
+    hookedActionWithArgs verbosity preTest testHook postTest
             (getBuildConfig hooks verbosity distPref)
             hooks flags' args
 
@@ -435,7 +456,7 @@ benchAction hooks flags args = do
     distPref <- findDistPrefOrDefault (benchmarkDistPref flags)
     let verbosity = fromFlag $ benchmarkVerbosity flags
         flags' = flags { benchmarkDistPref = toFlag distPref }
-    hookedActionWithArgs preBench benchHook postBench
+    hookedActionWithArgs verbosity preBench benchHook postBench
             (getBuildConfig hooks verbosity distPref)
             hooks flags' args
 
@@ -446,7 +467,7 @@ registerAction hooks flags args = do
     lbi <- getBuildConfig hooks verbosity distPref
     let flags' = flags { regDistPref = toFlag distPref
                        , regCabalFilePath = maybeToFlag (cabalFilePath lbi)}
-    hookedAction preReg regHook postReg
+    hookedAction verbosity preReg regHook postReg
                  (getBuildConfig hooks verbosity distPref)
                  hooks flags' { regArgs = args } args
 
@@ -457,55 +478,62 @@ unregisterAction hooks flags args = do
     lbi <- getBuildConfig hooks verbosity distPref
     let flags' = flags { regDistPref = toFlag distPref
                        , regCabalFilePath = maybeToFlag (cabalFilePath lbi)}
-    hookedAction preUnreg unregHook postUnreg
+    hookedAction verbosity preUnreg unregHook postUnreg
                  (getBuildConfig hooks verbosity distPref)
                  hooks flags' args
 
-hookedAction :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
-        -> (UserHooks -> PackageDescription -> LocalBuildInfo
-                      -> UserHooks -> flags -> IO ())
-        -> (UserHooks -> Args -> flags -> PackageDescription
-                      -> LocalBuildInfo -> IO ())
-        -> IO LocalBuildInfo
-        -> UserHooks -> flags -> Args -> IO ()
-hookedAction pre_hook cmd_hook =
-    hookedActionWithArgs pre_hook (\h _ pd lbi uh flags ->
-                                     cmd_hook h pd lbi uh flags)
-
-hookedActionWithArgs :: (UserHooks -> Args -> flags -> IO HookedBuildInfo)
-        -> (UserHooks -> Args -> PackageDescription -> LocalBuildInfo
-                      -> UserHooks -> flags -> IO ())
-        -> (UserHooks -> Args -> flags -> PackageDescription
-                      -> LocalBuildInfo -> IO ())
-        -> IO LocalBuildInfo
-        -> UserHooks -> flags -> Args -> IO ()
-hookedActionWithArgs pre_hook cmd_hook post_hook
+hookedAction
+  :: Verbosity
+  -> (UserHooks -> Args -> flags -> IO HookedBuildInfo)
+  -> (UserHooks -> PackageDescription -> LocalBuildInfo
+                -> UserHooks -> flags -> IO ())
+  -> (UserHooks -> Args -> flags -> PackageDescription
+                -> LocalBuildInfo -> IO ())
+  -> IO LocalBuildInfo
+  -> UserHooks -> flags -> Args -> IO ()
+hookedAction verbosity pre_hook cmd_hook =
+    hookedActionWithArgs verbosity pre_hook
+    (\h _ pd lbi uh flags ->
+        cmd_hook h pd lbi uh flags)
+
+hookedActionWithArgs
+  :: Verbosity
+  -> (UserHooks -> Args -> flags -> IO HookedBuildInfo)
+  -> (UserHooks -> Args -> PackageDescription -> LocalBuildInfo
+                -> UserHooks -> flags -> IO ())
+  -> (UserHooks -> Args -> flags -> PackageDescription
+                -> LocalBuildInfo -> IO ())
+  -> IO LocalBuildInfo
+  -> UserHooks -> flags -> Args -> IO ()
+hookedActionWithArgs verbosity pre_hook cmd_hook post_hook
   get_build_config hooks flags args = do
    pbi <- pre_hook hooks args flags
    lbi0 <- get_build_config
    let pkg_descr0 = localPkgDescr lbi0
-   sanityCheckHookedBuildInfo pkg_descr0 pbi
+   sanityCheckHookedBuildInfo verbosity pkg_descr0 pbi
    let pkg_descr = updatePackageDescription pbi pkg_descr0
        lbi = lbi0 { localPkgDescr = pkg_descr }
    cmd_hook hooks args pkg_descr lbi hooks flags
    post_hook hooks args flags pkg_descr lbi
 
-sanityCheckHookedBuildInfo :: PackageDescription -> HookedBuildInfo -> IO ()
-sanityCheckHookedBuildInfo PackageDescription { library = Nothing } (Just _,_)
-    = die $ "The buildinfo contains info for a library, "
-         ++ "but the package does not have a library."
+sanityCheckHookedBuildInfo
+  :: Verbosity -> PackageDescription -> HookedBuildInfo -> IO ()
+sanityCheckHookedBuildInfo verbosity
+  (PackageDescription { library = Nothing }) (Just _,_)
+    = die' verbosity $ "The buildinfo contains info for a library, "
+      ++ "but the package does not have a library."
 
-sanityCheckHookedBuildInfo pkg_descr (_, hookExes)
+sanityCheckHookedBuildInfo verbosity pkg_descr (_, hookExes)
     | not (null nonExistant)
-    = die $ "The buildinfo contains info for an executable called '"
-         ++ prettyShow (head nonExistant) ++ "' but the package does not have a "
-         ++ "executable with that name."
+    = die' verbosity $ "The buildinfo contains info for an executable called '"
+      ++ prettyShow (head nonExistant) ++ "' but the package does not have a "
+      ++ "executable with that name."
   where
     pkgExeNames  = nub (map exeName (executables pkg_descr))
     hookExeNames = nub (map fst hookExes)
     nonExistant  = hookExeNames \\ pkgExeNames
 
-sanityCheckHookedBuildInfo _ _ = return ()
+sanityCheckHookedBuildInfo _ _ _ = return ()
 
 -- | Try to read the 'localBuildInfoFile'
 tryGetBuildConfig :: UserHooks -> Verbosity -> FilePath
@@ -543,8 +571,8 @@ getBuildConfig hooks verbosity distPref = do
             -- Since the list of unconfigured programs is not serialized,
             -- restore it to the same value as normally used at the beginning
             -- of a configure run:
-            configPrograms_ = restoreProgramDb
-                               (builtinPrograms ++ hookedPrograms hooks)
+            configPrograms_ = fmap (restoreProgramDb
+                                      (builtinPrograms ++ hookedPrograms hooks))
                                `fmap` configPrograms_ cFlags,
 
             -- Use the current, not saved verbosity level:
@@ -603,7 +631,6 @@ simpleUserHooks =
        testHook  = defaultTestHook,
        benchHook = defaultBenchHook,
        instHook  = defaultInstallHook,
-       sDistHook = \p l h f -> sdist p l f srcPref (allSuffixHandlers h),
        cleanHook = \p _ _ f -> clean p f,
        hscolourHook = \p l h f -> hscolour p l (allSuffixHandlers h) f,
        haddockHook  = \p l h f -> haddock  p l (allSuffixHandlers h) f,
@@ -628,37 +655,6 @@ simpleUserHooks =
 -- Thus @configure@ can use local system information to generate
 -- /package/@.buildinfo@ and possibly other files.
 
-{-# DEPRECATED defaultUserHooks
-     "Use simpleUserHooks or autoconfUserHooks, unless you need Cabal-1.2\n             compatibility in which case you must stick with defaultUserHooks" #-}
-defaultUserHooks :: UserHooks
-defaultUserHooks = autoconfUserHooks {
-          confHook = \pkg flags -> do
-                       let verbosity = fromFlag (configVerbosity flags)
-                       warn verbosity
-                         "defaultUserHooks in Setup script is deprecated."
-                       confHook autoconfUserHooks pkg flags,
-          postConf = oldCompatPostConf
-    }
-    -- This is the annoying old version that only runs configure if it exists.
-    -- It's here for compatibility with existing Setup.hs scripts. See:
-    -- https://github.com/haskell/cabal/issues/158
-    where oldCompatPostConf args flags pkg_descr lbi
-              = do let verbosity = fromFlag (configVerbosity flags)
-                       baseDir lbi' = fromMaybe "" (takeDirectory <$> cabalFilePath lbi')
-
-                   confExists <- doesFileExist $ (baseDir lbi) </> "configure"
-                   when confExists $
-                       runConfigureScript verbosity
-                         backwardsCompatHack flags lbi
-
-                   pbi <- getHookedBuildInfo (buildDir lbi) verbosity
-                   sanityCheckHookedBuildInfo pkg_descr pbi
-                   let pkg_descr' = updatePackageDescription pbi pkg_descr
-                       lbi' = lbi { localPkgDescr = pkg_descr' }
-                   postConf simpleUserHooks args flags pkg_descr' lbi'
-
-          backwardsCompatHack = True
-
 autoconfUserHooks :: UserHooks
 autoconfUserHooks
     = simpleUserHooks
@@ -677,15 +673,16 @@ autoconfUserHooks
                           -> LocalBuildInfo -> IO ()
           defaultPostConf args flags pkg_descr lbi
               = do let verbosity = fromFlag (configVerbosity flags)
-                       baseDir lbi' = fromMaybe "" (takeDirectory <$> cabalFilePath lbi')
+                       baseDir lbi' = fromMaybe ""
+                                      (takeDirectory <$> cabalFilePath lbi')
                    confExists <- doesFileExist $ (baseDir lbi) </> "configure"
                    if confExists
                      then runConfigureScript verbosity
                             backwardsCompatHack flags lbi
-                     else die "configure script not found."
+                     else die' verbosity "configure script not found."
 
-                   pbi <- getHookedBuildInfo (buildDir lbi) verbosity
-                   sanityCheckHookedBuildInfo pkg_descr pbi
+                   pbi <- getHookedBuildInfo verbosity (buildDir lbi)
+                   sanityCheckHookedBuildInfo verbosity pkg_descr pbi
                    let pkg_descr' = updatePackageDescription pbi pkg_descr
                        lbi' = lbi { localPkgDescr = pkg_descr' }
                    postConf simpleUserHooks args flags pkg_descr' lbi'
@@ -698,7 +695,7 @@ autoconfUserHooks
                            -> IO HookedBuildInfo
           readHookWithArgs get_verbosity get_dist_pref _ flags = do
               dist_dir <- findDistPrefOrDefault (get_dist_pref flags)
-              getHookedBuildInfo (dist_dir </> "build") verbosity
+              getHookedBuildInfo verbosity (dist_dir </> "build")
             where
               verbosity = fromFlag (get_verbosity flags)
 
@@ -708,7 +705,7 @@ autoconfUserHooks
           readHook get_verbosity get_dist_pref a flags = do
               noExtraFlags a
               dist_dir <- findDistPrefOrDefault (get_dist_pref flags)
-              getHookedBuildInfo (dist_dir </> "build") verbosity
+              getHookedBuildInfo verbosity (dist_dir </> "build")
             where
               verbosity = fromFlag (get_verbosity flags)
 
@@ -768,7 +765,7 @@ runConfigureScript verbosity backwardsCompatHack flags lbi = do
       Just sh -> runProgramInvocation verbosity $
                  (programInvocation (sh {programOverrideEnv = overEnv}) args')
                  { progInvokeCwd = Just (buildDir lbi) }
-      Nothing -> die notFoundMsg
+      Nothing -> die' verbosity notFoundMsg
 
   where
     args = configureArgs backwardsCompatHack flags
@@ -803,9 +800,9 @@ runConfigureScript verbosity backwardsCompatHack flags lbi = do
                ++ "If you are not on Windows, ensure that an 'sh' command "
                ++ "is discoverable in your path."
 
-getHookedBuildInfo :: FilePath -> Verbosity -> IO HookedBuildInfo
-getHookedBuildInfo build_dir verbosity = do
-  maybe_infoFile <- findHookedPackageDesc build_dir
+getHookedBuildInfo :: Verbosity -> FilePath -> IO HookedBuildInfo
+getHookedBuildInfo verbosity build_dir = do
+  maybe_infoFile <- findHookedPackageDesc verbosity build_dir
   case maybe_infoFile of
     Nothing       -> return emptyHookedBuildInfo
     Just infoFile -> do
diff --git a/Cabal/Distribution/Simple/Build.hs b/Cabal/Distribution/Simple/Build.hs
index 678100fe42794b7fca2ccc365a1549a185c7eadb..331c367d8ded53d8726f7b675f63ef0677a1c85d 100644
--- a/Cabal/Distribution/Simple/Build.hs
+++ b/Cabal/Distribution/Simple/Build.hs
@@ -19,7 +19,7 @@
 --
 
 module Distribution.Simple.Build (
-    build, repl,
+    build, showBuildInfo, repl,
     startInterpreter,
 
     initialBuildSteps,
@@ -52,8 +52,8 @@ import qualified Distribution.Simple.UHC   as UHC
 import qualified Distribution.Simple.HaskellSuite as HaskellSuite
 import qualified Distribution.Simple.PackageIndex as Index
 
-import qualified Distribution.Simple.Build.Macros      as Build.Macros
-import qualified Distribution.Simple.Build.PathsModule as Build.PathsModule
+import Distribution.Simple.Build.Macros      (generateCabalMacrosHeader)
+import Distribution.Simple.Build.PathsModule (generatePathsModule)
 import qualified Distribution.Simple.Program.HcPkg as HcPkg
 
 import Distribution.Simple.Compiler hiding (Flag)
@@ -69,11 +69,13 @@ import Distribution.Simple.PreProcess
 import Distribution.Simple.LocalBuildInfo
 import Distribution.Simple.Program.Types
 import Distribution.Simple.Program.Db
+import Distribution.Simple.ShowBuildInfo
 import Distribution.Simple.BuildPaths
 import Distribution.Simple.Configure
 import Distribution.Simple.Register
 import Distribution.Simple.Test.LibV09
 import Distribution.Simple.Utils
+import Distribution.Simple.Utils.Json
 
 import Distribution.System
 import Distribution.Pretty
@@ -128,6 +130,18 @@ build pkg_descr lbi flags suffixes = do
   verbosity = fromFlag (buildVerbosity flags)
 
 
+showBuildInfo :: PackageDescription  -- ^ Mostly information from the .cabal file
+  -> LocalBuildInfo      -- ^ Configuration information
+  -> BuildFlags          -- ^ Flags that the user passed to build
+  -> IO String
+showBuildInfo pkg_descr lbi flags = do
+  let verbosity = fromFlag (buildVerbosity flags)
+  targets <- readTargetInfos verbosity pkg_descr lbi (buildArgs flags)
+  let targetsToBuild = neededTargetsInBuildOrder' pkg_descr lbi (map nodeKey targets)
+      doc = mkBuildInfo pkg_descr lbi flags targetsToBuild
+  return $ renderJson doc ""
+
+
 repl     :: PackageDescription  -- ^ Mostly information from the .cabal file
          -> LocalBuildInfo      -- ^ Configuration information
          -> ReplFlags           -- ^ Flags that the user passed to build
@@ -662,7 +676,7 @@ writeAutogenFiles verbosity pkg lbi clbi = do
       pathsModuleDir = takeDirectory pathsModulePath
   -- Ensure that the directory exists!
   createDirectoryIfMissingVerbose verbosity True pathsModuleDir
-  rewriteFileEx verbosity pathsModulePath (Build.PathsModule.generate pkg lbi clbi)
+  rewriteFileEx verbosity pathsModulePath (generatePathsModule pkg lbi clbi)
 
   --TODO: document what we're doing here, and move it to its own function
   case clbi of
@@ -684,4 +698,4 @@ writeAutogenFiles verbosity pkg lbi clbi = do
     _ -> return ()
 
   let cppHeaderPath = autogenComponentModulesDir lbi clbi </> cppHeaderName
-  rewriteFileEx verbosity cppHeaderPath (Build.Macros.generate pkg lbi clbi)
+  rewriteFileEx verbosity cppHeaderPath (generateCabalMacrosHeader pkg lbi clbi)
diff --git a/Cabal/Distribution/Simple/Build/Macros.hs b/Cabal/Distribution/Simple/Build/Macros.hs
index 88040ea9cb29e4babe17bc5e245860080e350335..fa3ba3f5274b422d8243f689768a15defe668913 100644
--- a/Cabal/Distribution/Simple/Build/Macros.hs
+++ b/Cabal/Distribution/Simple/Build/Macros.hs
@@ -20,7 +20,7 @@
 -- TODO Figure out what to do about backpack and internal libraries. It is very
 -- suspecious that this stuff works with munged package identifiers
 module Distribution.Simple.Build.Macros (
-    generate,
+    generateCabalMacrosHeader,
     generatePackageVersionMacros,
   ) where
 
@@ -73,8 +73,8 @@ ifndefDefineStr macro str =
 
 -- | The contents of the @cabal_macros.h@ for the given configured package.
 --
-generate :: PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> String
-generate pkg_descr lbi clbi =
+generateCabalMacrosHeader :: PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> String
+generateCabalMacrosHeader pkg_descr lbi clbi =
   "/* DO NOT EDIT: This file is automatically generated by Cabal */\n\n" ++
   generatePackageVersionMacros
     (package pkg_descr : map getPid (componentPackageDeps clbi)) ++
diff --git a/Cabal/Distribution/Simple/Build/PathsModule.hs b/Cabal/Distribution/Simple/Build/PathsModule.hs
index f6a20387475cf00c10a31a6ebbdeb9bdd6a44ac5..5e660e8d655a73589fed27754d263a6d256232e3 100644
--- a/Cabal/Distribution/Simple/Build/PathsModule.hs
+++ b/Cabal/Distribution/Simple/Build/PathsModule.hs
@@ -15,7 +15,7 @@
 -- at runtime. This code should probably be split off into another module.
 --
 module Distribution.Simple.Build.PathsModule (
-    generate, pkgPathEnvVar
+    generatePathsModule, pkgPathEnvVar
   ) where
 
 import Prelude ()
@@ -37,8 +37,8 @@ import System.FilePath ( pathSeparator )
 -- * Building Paths_<pkg>.hs
 -- ------------------------------------------------------------
 
-generate :: PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> String
-generate pkg_descr lbi clbi =
+generatePathsModule :: PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> String
+generatePathsModule pkg_descr lbi clbi =
    let pragmas =
             cpp_pragma
          ++ no_rebindable_syntax_pragma
@@ -195,7 +195,8 @@ generate pkg_descr lbi clbi =
           datadir    = flat_datadir,
           libexecdir = flat_libexecdir,
           sysconfdir = flat_sysconfdir
-        } = absoluteComponentInstallDirs pkg_descr lbi cid NoCopyDest
+        } = absoluteInstallCommandDirs pkg_descr lbi cid NoCopyDest
+
         InstallDirs {
           bindir     = flat_bindirrel,
           libdir     = flat_libdirrel,
diff --git a/Cabal/Distribution/Simple/BuildPaths.hs b/Cabal/Distribution/Simple/BuildPaths.hs
index f43b29a7cc3637986a78f36b20a0c1de62c5427d..c8557c9999ac68add9407988b66028b0cc1ef1df 100644
--- a/Cabal/Distribution/Simple/BuildPaths.hs
+++ b/Cabal/Distribution/Simple/BuildPaths.hs
@@ -16,11 +16,9 @@
 module Distribution.Simple.BuildPaths (
     defaultDistPref, srcPref,
     haddockDirName, hscolourPref, haddockPref,
-    autogenModulesDir,
     autogenPackageModulesDir,
     autogenComponentModulesDir,
 
-    autogenModuleName,
     autogenPathsModuleName,
     cppHeaderName,
     haddockName,
@@ -81,12 +79,6 @@ haddockPref :: HaddockTarget -> FilePath -> PackageDescription -> FilePath
 haddockPref haddockTarget distPref pkg_descr
     = distPref </> "doc" </> "html" </> haddockDirName haddockTarget pkg_descr
 
--- | The directory in which we put auto-generated modules for EVERY
--- component in the package.  See deprecation notice.
-{-# DEPRECATED autogenModulesDir "If you can, use 'autogenComponentModulesDir' instead, but if you really wanted package-global generated modules, use 'autogenPackageModulesDir'.  In Cabal 2.0, we avoid using autogenerated files which apply to all components, because the information you often want in these files, e.g., dependency information, is best specified per component, so that reconfiguring a different component (e.g., enabling tests) doesn't force the entire to be rebuilt.  'autogenPackageModulesDir' still provides a place to put files you want to apply to the entire package, but most users of 'autogenModulesDir' should seriously consider 'autogenComponentModulesDir' if you really wanted the module to apply to one component." #-}
-autogenModulesDir :: LocalBuildInfo -> String
-autogenModulesDir = autogenPackageModulesDir
-
 -- | The directory in which we put auto-generated modules for EVERY
 -- component in the package.
 autogenPackageModulesDir :: LocalBuildInfo -> String
@@ -102,11 +94,6 @@ autogenComponentModulesDir lbi clbi = componentBuildDir lbi clbi </> "autogen"
 cppHeaderName :: String
 cppHeaderName = "cabal_macros.h"
 
-{-# DEPRECATED autogenModuleName "Use autogenPathsModuleName instead" #-}
--- |The name of the auto-generated module associated with a package
-autogenModuleName :: PackageDescription -> ModuleName
-autogenModuleName = autogenPathsModuleName
-
 -- | The name of the auto-generated Paths_* module associated with a package
 autogenPathsModuleName :: PackageDescription -> ModuleName
 autogenPathsModuleName pkg_descr =
@@ -141,7 +128,7 @@ getExeSourceFiles :: Verbosity
                      -> IO [(ModuleName.ModuleName, FilePath)]
 getExeSourceFiles verbosity lbi exe clbi = do
     moduleFiles <- getSourceFiles verbosity searchpaths modules
-    srcMainPath <- findFile (hsSourceDirs bi) (modulePath exe)
+    srcMainPath <- findFileEx verbosity (hsSourceDirs bi) (modulePath exe)
     return ((ModuleName.main, srcMainPath) : moduleFiles)
   where
     bi          = buildInfo exe
diff --git a/Cabal/Distribution/Simple/Command.hs b/Cabal/Distribution/Simple/Command.hs
index 2426982c189a29df2dc8ccd2a487d4eaf626af6c..b59ecb60cb1cb5cfc4ecaa21b52082d3662f99d3 100644
--- a/Cabal/Distribution/Simple/Command.hs
+++ b/Cabal/Distribution/Simple/Command.hs
@@ -520,7 +520,7 @@ noExtraFlags extraFlags =
 
 -- | Helper function for creating globalCommand description
 getNormalCommandDescriptions :: [Command action] -> [(String, String)]
-getNormalCommandDescriptions cmds = 
+getNormalCommandDescriptions cmds =
   [ (name, description)
   | Command name description _ NormalCommand <- cmds ]
 
diff --git a/Cabal/Distribution/Simple/Configure.hs b/Cabal/Distribution/Simple/Configure.hs
index cb8e7297dd160b4ad8e30adac1a3400b014a5065..4039a078ff525637c90a1e5057219afa6b90e1f0 100644
--- a/Cabal/Distribution/Simple/Configure.hs
+++ b/Cabal/Distribution/Simple/Configure.hs
@@ -44,7 +44,6 @@ module Distribution.Simple.Configure
   , getInstalledPackages
   , getInstalledPackagesMonitorFiles
   , getPackageDBContents
-  , configCompiler, configCompilerAux
   , configCompilerEx, configCompilerAuxEx
   , computeEffectiveProfiling
   , ccLdOptionsBuildInfo
@@ -84,6 +83,7 @@ import Distribution.Types.PkgconfigDependency
 import Distribution.Types.PkgconfigVersionRange
 import Distribution.Types.LocalBuildInfo
 import Distribution.Types.LibraryName
+import Distribution.Types.LibraryVisibility
 import Distribution.Types.ComponentRequestedSpec
 import Distribution.Types.ForeignLib
 import Distribution.Types.ForeignLibType
@@ -477,6 +477,7 @@ configure (pkg_descr0, pbi) cfg = do
                 (dependencySatisfiable
                     use_external_internal_deps
                     (fromFlagOrDefault False (configExactConfiguration cfg))
+                    (fromFlagOrDefault False (configAllowDependingOnPrivateLibs cfg))
                     (packageName pkg_descr0)
                     installedPackageSet
                     internalPackageSet
@@ -705,6 +706,27 @@ configure (pkg_descr0, pbi) cfg = do
 
     setCoverageLBI <- configureCoverage verbosity cfg comp
 
+
+
+    -- Turn off library and executable stripping when `debug-info` is set
+    -- to anything other than zero.
+    let
+        strip_libexe s f =
+          let defaultStrip = fromFlagOrDefault True (f cfg)
+          in case fromFlag (configDebugInfo cfg) of
+                      NoDebugInfo -> return defaultStrip
+                      _ -> case f cfg of
+                             Flag True -> do
+                              warn verbosity $ "Setting debug-info implies "
+                                                ++ s ++ "-stripping: False"
+                              return False
+
+                             _ -> return False
+
+    strip_lib <- strip_libexe "library" configStripLibs
+    strip_exe <- strip_libexe "executable" configStripExes
+
+
     let reloc = fromFlagOrDefault False $ configRelocatable cfg
 
     let buildComponentsMap =
@@ -746,8 +768,8 @@ configure (pkg_descr0, pbi) cfg = do
                                       configGHCiLib cfg,
                 splitSections       = split_sections,
                 splitObjs           = split_objs,
-                stripExes           = fromFlag $ configStripExes cfg,
-                stripLibs           = fromFlag $ configStripLibs cfg,
+                stripExes           = strip_exe,
+                stripLibs           = strip_lib,
                 exeCoverage         = False,
                 libCoverage         = False,
                 withPackageDB       = packageDbs,
@@ -882,6 +904,7 @@ getInternalPackages pkg_descr0 =
 dependencySatisfiable
     :: Bool -- ^ use external internal deps?
     -> Bool -- ^ exact configuration?
+    -> Bool -- ^ allow depending on private libs?
     -> PackageName
     -> InstalledPackageIndex -- ^ installed set
     -> Map PackageName (Maybe UnqualComponentName) -- ^ internal set
@@ -890,7 +913,9 @@ dependencySatisfiable
     -> (Dependency -> Bool)
 dependencySatisfiable
   use_external_internal_deps
-  exact_config pn installedPackageSet internalPackageSet requiredDepsMap
+  exact_config
+  allow_private_deps
+  pn installedPackageSet internalPackageSet requiredDepsMap
   (Dependency depName vr sublibs)
 
     | exact_config
@@ -914,12 +939,7 @@ dependencySatisfiable
                       packageNameToUnqualComponentName depName)
                  requiredDepsMap)
 
-          || all
-               (\lib ->
-                 (depName, CLibName lib)
-                 `Map.member`
-                 requiredDepsMap)
-               sublibs
+          || all visible sublibs
 
     | isInternalDep
     = if use_external_internal_deps
@@ -950,6 +970,23 @@ dependencySatisfiable
            -- Reinterpret the "package name" as an unqualified component
            -- name
            = LSubLibName $ packageNameToUnqualComponentName depName
+    -- Check whether a libray exists and is visible.
+    -- We don't disambiguate between dependency on non-existent or private
+    -- library yet, so we just return a bool and later report a generic error.
+    visible lib = maybe
+                    False -- Does not even exist (wasn't in the depsMap)
+                    (\ipi -> Installed.libVisibility ipi == LibraryVisibilityPublic
+                          -- If the override is enabled, the visibility does
+                          -- not matter (it's handled externally)
+                          || allow_private_deps
+                          -- If it's a library of the same package then it's
+                          -- always visible.
+                          -- This is only triggered when passing a component
+                          -- of the same package as --dependency, such as in:
+                          -- cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit.test.hs
+                          || pkgName (Installed.sourcePackageId ipi) == pn)
+                    maybeIPI
+      where maybeIPI = Map.lookup (depName, CLibName lib) requiredDepsMap
 
 -- | Finalize a generic package description.  The workhorse is
 -- 'finalizePD' but there's a bit of other nattering
@@ -982,7 +1019,7 @@ configureFinalizedPackage verbosity cfg enabled
                    pkg_descr0
             of Right r -> return r
                Left missing ->
-                   die' verbosity $ "Encountered missing dependencies:\n"
+                   die' verbosity $ "Encountered missing or private dependencies:\n"
                      ++ (render . nest 4 . sep . punctuate comma
                                 . map (pretty . simplifyDependency)
                                 $ missing)
@@ -1677,25 +1714,6 @@ configCompilerEx (Just hcFlavor) hcPath hcPkg progdb verbosity = do
     _    -> die' verbosity "Unknown compiler"
   return (comp, fromMaybe buildPlatform maybePlatform, programDb)
 
--- Ideally we would like to not have separate configCompiler* and
--- configCompiler*Ex sets of functions, but there are many custom setup scripts
--- in the wild that are using them, so the versions with old types are kept for
--- backwards compatibility. Platform was added to the return triple in 1.18.
-
-{-# DEPRECATED configCompiler
-    "'configCompiler' is deprecated. Use 'configCompilerEx' instead." #-}
-configCompiler :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
-               -> ProgramDb -> Verbosity
-               -> IO (Compiler, ProgramDb)
-configCompiler mFlavor hcPath hcPkg progdb verbosity =
-  fmap (\(a,_,b) -> (a,b)) $ configCompilerEx mFlavor hcPath hcPkg progdb verbosity
-
-{-# DEPRECATED configCompilerAux
-    "configCompilerAux is deprecated. Use 'configCompilerAuxEx' instead." #-}
-configCompilerAux :: ConfigFlags
-                  -> IO (Compiler, ProgramDb)
-configCompilerAux = fmap (\(a,_,b) -> (a,b)) . configCompilerAuxEx
-
 -- -----------------------------------------------------------------------------
 -- Testing C lib and header dependencies
 
diff --git a/Cabal/Distribution/Simple/GHC.hs b/Cabal/Distribution/Simple/GHC.hs
index 2bceac7fbe0a71f351bb3a3707d14208842de9c3..6d9f15e1c641e57bd9fb971ece0e5910bd1354cb 100644
--- a/Cabal/Distribution/Simple/GHC.hs
+++ b/Cabal/Distribution/Simple/GHC.hs
@@ -577,7 +577,11 @@ buildOrReplLib mReplFlags verbosity numJobs pkg_descr lbi lib clbi = do
       linkerOpts = mempty {
                       ghcOptLinkOptions       = PD.ldOptions libBi
                                                 ++ [ "-static"
-                                                   | withFullyStaticExe lbi ],
+                                                   | withFullyStaticExe lbi ]
+                                                -- Pass extra `ld-options` given
+                                                -- through to GHC's linker.
+                                                ++ maybe [] programOverrideArgs
+                                                     (lookupProgram ldProgram (withPrograms lbi)),
                       ghcOptLinkLibs          = extraLibs libBi,
                       ghcOptLinkLibPath       = toNubListR $ extraLibDirs libBi,
                       ghcOptLinkFrameworks    = toNubListR $ PD.frameworks libBi,
@@ -1117,7 +1121,7 @@ gbuildSources verbosity specVer tmpDir bm =
   where
     exeSources :: Executable -> IO BuildSources
     exeSources exe@Executable{buildInfo = bnfo, modulePath = modPath} = do
-      main <- findFile (tmpDir : hsSourceDirs bnfo) modPath
+      main <- findFileEx verbosity (tmpDir : hsSourceDirs bnfo) modPath
       let mainModName = fromMaybe ModuleName.main $ exeMainModuleName exe
           otherModNames = exeModules exe
 
@@ -1274,7 +1278,11 @@ gbuild verbosity numJobs pkg_descr lbi bm clbi = do
       linkerOpts = mempty {
                       ghcOptLinkOptions       = PD.ldOptions bnfo
                                                 ++ [ "-static"
-                                                   | withFullyStaticExe lbi ],
+                                                   | withFullyStaticExe lbi ]
+                                                -- Pass extra `ld-options` given
+                                                -- through to GHC's linker.
+                                                ++ maybe [] programOverrideArgs
+                                                     (lookupProgram ldProgram (withPrograms lbi)),
                       ghcOptLinkLibs          = extraLibs bnfo,
                       ghcOptLinkLibPath       = toNubListR $ extraLibDirs bnfo,
                       ghcOptLinkFrameworks    = toNubListR $
@@ -1919,7 +1927,7 @@ installLib verbosity lbi targetDir dynlibTargetDir _builtDir pkg lib clbi = do
     installShared   = install True
 
     copyModuleFiles ext =
-      findModuleFiles [builtDir] [ext] (allLibModules lib clbi)
+      findModuleFilesEx verbosity [builtDir] [ext] (allLibModules lib clbi)
       >>= installOrdinaryFiles verbosity targetDir
 
     compiler_id = compilerId (compiler lbi)
diff --git a/Cabal/Distribution/Simple/GHCJS.hs b/Cabal/Distribution/Simple/GHCJS.hs
index 5624ddcb31efe231a65286f2bd0407027664e3ae..46896c3a0320e1c3fab4312b6c2417b8e7642777 100644
--- a/Cabal/Distribution/Simple/GHCJS.hs
+++ b/Cabal/Distribution/Simple/GHCJS.hs
@@ -1,70 +1,115 @@
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE RankNTypes #-}
+{-# LANGUAGE TupleSections #-}
+{-# LANGUAGE CPP #-}
 
 module Distribution.Simple.GHCJS (
-        configure, getInstalledPackages, getPackageDBContents,
-        buildLib, buildExe,
-        replLib, replExe,
+        getGhcInfo,
+        configure,
+        getInstalledPackages,
+        getInstalledPackagesMonitorFiles,
+        getPackageDBContents,
+        buildLib, buildFLib, buildExe,
+        replLib, replFLib, replExe,
         startInterpreter,
-        installLib, installExe,
+        installLib, installFLib, installExe,
         libAbiHash,
         hcPkgInfo,
         registerPackage,
         componentGhcOptions,
+        componentCcGhcOptions,
         getLibDir,
         isDynamic,
         getGlobalPackageDB,
-        runCmd
-  ) where
+        pkgRoot,
+        runCmd,
+        -- * Constructing and deconstructing GHC environment files
+        Internal.GhcEnvironmentFileEntry(..),
+        Internal.simpleGhcEnvironmentFile,
+        Internal.renderGhcEnvironmentFile,
+        Internal.writeGhcEnvironmentFile,
+        Internal.ghcPlatformAndVersionString,
+        readGhcEnvironmentFile,
+        parseGhcEnvironmentFile,
+        ParseErrorExc(..),
+        -- * Version-specific implementation quirks
+        getImplInfo,
+        GhcImplInfo(..)
+ ) where
 
 import Prelude ()
 import Distribution.Compat.Prelude
 
-import Distribution.Types.UnqualComponentName
-import Distribution.Simple.GHC.ImplInfo
 import qualified Distribution.Simple.GHC.Internal as Internal
+import Distribution.Simple.GHC.ImplInfo
+import Distribution.Simple.GHC.EnvironmentParser
+import Distribution.PackageDescription.Utils (cabalBug)
 import Distribution.PackageDescription as PD
-import Distribution.InstalledPackageInfo
-import Distribution.Simple.PackageIndex ( InstalledPackageIndex )
+import Distribution.InstalledPackageInfo (InstalledPackageInfo)
+import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
+import Distribution.Simple.PackageIndex (InstalledPackageIndex)
 import qualified Distribution.Simple.PackageIndex as PackageIndex
 import Distribution.Simple.LocalBuildInfo
+import Distribution.Types.ComponentLocalBuildInfo
 import qualified Distribution.Simple.Hpc as Hpc
 import Distribution.Simple.BuildPaths
 import Distribution.Simple.Utils
+import Distribution.Package
+import qualified Distribution.ModuleName as ModuleName
+import Distribution.ModuleName (ModuleName)
 import Distribution.Simple.Program
 import qualified Distribution.Simple.Program.HcPkg as HcPkg
-import qualified Distribution.Simple.Program.Ar    as Ar
-import qualified Distribution.Simple.Program.Ld    as Ld
 import qualified Distribution.Simple.Program.Strip as Strip
 import Distribution.Simple.Program.GHC
-import Distribution.Simple.Setup hiding ( Flag )
+import Distribution.Simple.Setup
 import qualified Distribution.Simple.Setup as Cabal
-import Distribution.Simple.Compiler hiding ( Flag )
+import Distribution.Simple.Compiler hiding (Flag)
 import Distribution.Version
 import Distribution.System
 import Distribution.Verbosity
-import Distribution.Utils.NubList
 import Distribution.Pretty
-import Distribution.Types.UnitId
+import Distribution.Types.ForeignLib
+import Distribution.Types.ForeignLibType
+import Distribution.Types.ForeignLibOption
+import Distribution.Types.UnqualComponentName
+import Distribution.Utils.NubList
 
+import Control.Monad (msum)
+import Data.Char (isLower)
 import qualified Data.Map as Map
-import System.Directory         ( doesFileExist )
+import System.Directory
+         ( doesFileExist, getAppUserDataDirectory, createDirectoryIfMissing
+         , canonicalizePath, removeFile, renameFile )
 import System.FilePath          ( (</>), (<.>), takeExtension
-                                , takeDirectory, replaceExtension )
+                                , takeDirectory, replaceExtension
+                                ,isRelative )
+import qualified System.Info
+
+-- -----------------------------------------------------------------------------
+-- Configuring
 
 configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
           -> ProgramDb
           -> IO (Compiler, Maybe Platform, ProgramDb)
-configure verbosity hcPath hcPkgPath progdb0 = do
+configure verbosity hcPath hcPkgPath conf0 = do
+
   (ghcjsProg, ghcjsVersion, progdb1) <-
     requireProgramVersion verbosity ghcjsProgram
       (orLaterVersion (mkVersion [0,1]))
-      (userMaybeSpecifyPath "ghcjs" hcPath progdb0)
+      (userMaybeSpecifyPath "ghcjs" hcPath conf0)
+
   Just ghcjsGhcVersion <- findGhcjsGhcVersion verbosity (programPath ghcjsProg)
+  unless (ghcjsGhcVersion < mkVersion [8,8]) $
+    warn verbosity $
+         "Unknown/unsupported 'ghc' version detected "
+      ++ "(Cabal " ++ prettyShow cabalVersion ++ " supports 'ghc' version < 8.8): "
+      ++ programPath ghcjsProg ++ " is is based on GHC version " ++
+      prettyShow ghcjsGhcVersion
+
   let implInfo = ghcjsVersionImplInfo ghcjsVersion ghcjsGhcVersion
 
-  -- This is slightly tricky, we have to configure ghcjs first, then we use the
-  -- location of ghcjs to help find ghcjs-pkg in the case that the user did not
+  -- This is slightly tricky, we have to configure ghc first, then we use the
+  -- location of ghc to help find ghc-pkg in the case that the user did not
   -- specify the location of ghc-pkg directly:
   (ghcjsPkgProg, ghcjsPkgVersion, progdb2) <-
     requireProgramVersion verbosity ghcjsPkgProgram {
@@ -87,24 +132,33 @@ configure verbosity hcPath hcPkgPath progdb0 = do
     ++ programPath ghcjsPkgProg
     ++ " was built with GHC version " ++ prettyShow ghcjsPkgVersion
 
-  -- be sure to use our versions of hsc2hs, c2hs, haddock and ghc
-  let hsc2hsProgram' =
-        hsc2hsProgram { programFindLocation =
-                          guessHsc2hsFromGhcjsPath ghcjsProg }
-      c2hsProgram' =
-        c2hsProgram { programFindLocation =
-                          guessC2hsFromGhcjsPath ghcjsProg }
-
-      haddockProgram' =
-        haddockProgram { programFindLocation =
-                          guessHaddockFromGhcjsPath ghcjsProg }
-      progdb3 = addKnownPrograms [ hsc2hsProgram', c2hsProgram', haddockProgram' ] progdb2
 
-  languages  <- Internal.getLanguages  verbosity implInfo ghcjsProg
+  -- Likewise we try to find the matching hsc2hs and haddock programs.
+  let hsc2hsProgram' = hsc2hsProgram {
+                           programFindLocation =
+                             guessHsc2hsFromGhcjsPath ghcjsProg
+                       }
+      haddockProgram' = haddockProgram {
+                           programFindLocation =
+                             guessHaddockFromGhcjsPath ghcjsProg
+                       }
+      hpcProgram' = hpcProgram {
+                        programFindLocation = guessHpcFromGhcjsPath ghcjsProg
+                    }
+                    {-
+      runghcProgram' = runghcProgram {
+                        programFindLocation = guessRunghcFromGhcjsPath ghcjsProg
+                    } -}
+      progdb3 = addKnownProgram haddockProgram' $
+              addKnownProgram hsc2hsProgram' $
+              addKnownProgram hpcProgram' $
+              {- addKnownProgram runghcProgram' -} progdb2
+
+  languages  <- Internal.getLanguages verbosity implInfo ghcjsProg
   extensions <- Internal.getExtensions verbosity implInfo ghcjsProg
 
-  ghcInfo <- Internal.getGhcInfo verbosity implInfo ghcjsProg
-  let ghcInfoMap = Map.fromList ghcInfo
+  ghcjsInfo <- Internal.getGhcInfo verbosity implInfo ghcjsProg
+  let ghcInfoMap = Map.fromList ghcjsInfo
 
   let comp = Compiler {
         compilerId         = CompilerId GHCJS ghcjsVersion,
@@ -115,16 +169,8 @@ configure verbosity hcPath hcPkgPath progdb0 = do
         compilerExtensions = extensions,
         compilerProperties = ghcInfoMap
       }
-      compPlatform = Internal.targetPlatform ghcInfo
-  -- configure gcc and ld
-  let progdb4 = if ghcjsNativeToo comp
-                     then Internal.configureToolchain implInfo
-                            ghcjsProg ghcInfoMap progdb3
-                     else progdb3
-  return (comp, compPlatform, progdb4)
-
-ghcjsNativeToo :: Compiler -> Bool
-ghcjsNativeToo = Internal.ghcLookupProperty "Native Too"
+      compPlatform = Internal.targetPlatform ghcjsInfo
+  return (comp, compPlatform, progdb3)
 
 guessGhcjsPkgFromGhcjsPath :: ConfiguredProgram -> Verbosity
                            -> ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))
@@ -134,35 +180,47 @@ guessHsc2hsFromGhcjsPath :: ConfiguredProgram -> Verbosity
                          -> ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))
 guessHsc2hsFromGhcjsPath = guessToolFromGhcjsPath hsc2hsProgram
 
-guessC2hsFromGhcjsPath :: ConfiguredProgram -> Verbosity
-                       -> ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))
-guessC2hsFromGhcjsPath = guessToolFromGhcjsPath c2hsProgram
-
 guessHaddockFromGhcjsPath :: ConfiguredProgram -> Verbosity
                           -> ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))
 guessHaddockFromGhcjsPath = guessToolFromGhcjsPath haddockProgram
 
-guessToolFromGhcjsPath :: Program -> ConfiguredProgram
+guessHpcFromGhcjsPath :: ConfiguredProgram
                        -> Verbosity -> ProgramSearchPath
                        -> IO (Maybe (FilePath, [FilePath]))
+guessHpcFromGhcjsPath = guessToolFromGhcjsPath hpcProgram
+
+
+guessToolFromGhcjsPath :: Program -> ConfiguredProgram
+                     -> Verbosity -> ProgramSearchPath
+                     -> IO (Maybe (FilePath, [FilePath]))
 guessToolFromGhcjsPath tool ghcjsProg verbosity searchpath
   = do let toolname          = programName tool
-           path              = programPath ghcjsProg
-           dir               = takeDirectory path
-           versionSuffix     = takeVersionSuffix (dropExeExtension path)
-           guessNormal       = dir </> toolname <.> exeExtension buildPlatform
-           guessGhcjsVersioned = dir </> (toolname ++ "-ghcjs" ++ versionSuffix)
-                                 <.> exeExtension buildPlatform
-           guessGhcjs        = dir </> (toolname ++ "-ghcjs")
-                               <.> exeExtension buildPlatform
-           guessVersioned    = dir </> (toolname ++ versionSuffix) <.> exeExtension buildPlatform
-           guesses | null versionSuffix = [guessGhcjs, guessNormal]
-                   | otherwise          = [guessGhcjsVersioned,
-                                           guessGhcjs,
-                                           guessVersioned,
-                                           guessNormal]
+           given_path        = programPath ghcjsProg
+           given_dir         = takeDirectory given_path
+       real_path <- canonicalizePath given_path
+       let real_dir           = takeDirectory real_path
+           versionSuffix path = takeVersionSuffix (dropExeExtension path)
+           given_suf = versionSuffix given_path
+           real_suf  = versionSuffix real_path
+           guessNormal         dir = dir </> toolname <.> exeExtension buildPlatform
+           guessGhcjs          dir = dir </> (toolname ++ "-ghcjs")
+                                         <.> exeExtension buildPlatform
+           guessGhcjsVersioned dir suf = dir </> (toolname ++ "-ghcjs" ++ suf)
+                                             <.> exeExtension buildPlatform
+           guessVersioned      dir suf = dir </> (toolname ++ suf)
+                                             <.> exeExtension buildPlatform
+           mkGuesses dir suf | null suf  = [guessGhcjs dir, guessNormal dir]
+                             | otherwise = [guessGhcjsVersioned dir suf,
+                                            guessVersioned dir suf,
+                                            guessGhcjs dir,
+                                            guessNormal dir]
+           guesses = mkGuesses given_dir given_suf ++
+                            if real_path == given_path
+                                then []
+                                else mkGuesses real_dir real_suf
        info verbosity $ "looking for tool " ++ toolname
-         ++ " near compiler in " ++ dir
+         ++ " near compiler in " ++ given_dir
+       debug verbosity $ "candidate locations: " ++ show guesses
        exists <- traverse doesFileExist guesses
        case [ file | (file, True) <- zip guesses exists ] of
                    -- If we can't find it near ghc, fall back to the usual
@@ -175,8 +233,16 @@ guessToolFromGhcjsPath tool ghcjsProg verbosity searchpath
                       return (Just (fp, lookedAt))
 
   where takeVersionSuffix :: FilePath -> String
-        takeVersionSuffix = reverse . takeWhile (`elem ` "0123456789.-") .
-                            reverse
+        takeVersionSuffix = takeWhileEndLE isSuffixChar
+
+        isSuffixChar :: Char -> Bool
+        isSuffixChar c = isDigit c || c == '.' || c == '-'
+
+getGhcInfo :: Verbosity -> ConfiguredProgram -> IO [(String, String)]
+getGhcInfo verbosity ghcjsProg = Internal.getGhcInfo verbosity implInfo ghcjsProg
+  where
+    Just version = programVersion ghcjsProg
+    implInfo = ghcVersionImplInfo version
 
 -- | Given a single package DB, return all installed packages.
 getPackageDBContents :: Verbosity -> PackageDB -> ProgramDb
@@ -211,6 +277,38 @@ toPackageIndex verbosity pkgss progdb = do
   where
     Just ghcjsProg = lookupProgram ghcjsProgram progdb
 
+getLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath
+getLibDir verbosity lbi =
+    dropWhileEndLE isSpace `fmap`
+     getDbProgramOutput verbosity ghcjsProgram
+     (withPrograms lbi) ["--print-libdir"]
+
+getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath
+getLibDir' verbosity ghcjsProg =
+    dropWhileEndLE isSpace `fmap`
+     getProgramOutput verbosity ghcjsProg ["--print-libdir"]
+
+
+-- | Return the 'FilePath' to the global GHC package database.
+getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath
+getGlobalPackageDB verbosity ghcProg =
+    dropWhileEndLE isSpace `fmap`
+     getProgramOutput verbosity ghcProg ["--print-global-package-db"]
+
+-- | Return the 'FilePath' to the per-user GHC package database.
+getUserPackageDB :: Verbosity -> ConfiguredProgram -> Platform -> NoCallStackIO FilePath
+getUserPackageDB _verbosity ghcjsProg platform = do
+    -- It's rather annoying that we have to reconstruct this, because ghc
+    -- hides this information from us otherwise. But for certain use cases
+    -- like change monitoring it really can't remain hidden.
+    appdir <- getAppUserDataDirectory "ghcjs"
+    return (appdir </> platformAndVersion </> packageConfFileName)
+  where
+    platformAndVersion = Internal.ghcPlatformAndVersionString
+                           platform ghcjsVersion
+    packageConfFileName = "package.conf.d"
+    Just ghcjsVersion = programVersion ghcjsProg
+
 checkPackageDbEnvVar :: Verbosity -> IO ()
 checkPackageDbEnvVar verbosity =
     Internal.checkPackageDbEnvVar verbosity "GHCJS" "GHCJS_PACKAGE_PATH"
@@ -235,22 +333,35 @@ getInstalledPackages' verbosity packagedbs progdb =
          return (packagedb, pkgs)
     | packagedb <- packagedbs ]
 
-getLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath
-getLibDir verbosity lbi =
-    (reverse . dropWhile isSpace . reverse) `fmap`
-     getDbProgramOutput verbosity ghcjsProgram
-     (withPrograms lbi) ["--print-libdir"]
+-- | Get the packages from specific PackageDBs, not cumulative.
+--
+getInstalledPackagesMonitorFiles :: Verbosity -> Platform
+                                 -> ProgramDb
+                                 -> [PackageDB]
+                                 -> IO [FilePath]
+getInstalledPackagesMonitorFiles verbosity platform progdb =
+    traverse getPackageDBPath
+  where
+    getPackageDBPath :: PackageDB -> IO FilePath
+    getPackageDBPath GlobalPackageDB =
+      selectMonitorFile =<< getGlobalPackageDB verbosity ghcjsProg
 
-getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath
-getLibDir' verbosity ghcjsProg =
-    (reverse . dropWhile isSpace . reverse) `fmap`
-     getProgramOutput verbosity ghcjsProg ["--print-libdir"]
+    getPackageDBPath UserPackageDB =
+      selectMonitorFile =<< getUserPackageDB verbosity ghcjsProg platform
+
+    getPackageDBPath (SpecificPackageDB path) = selectMonitorFile path
+
+    -- GHC has old style file dbs, and new style directory dbs.
+    -- Note that for dir style dbs, we only need to monitor the cache file, not
+    -- the whole directory. The ghc program itself only reads the cache file
+    -- so it's safe to only monitor this one file.
+    selectMonitorFile path = do
+      isFileStyle <- doesFileExist path
+      if isFileStyle then return path
+                     else return (path </> "package.cache")
+
+    Just ghcjsProg = lookupProgram ghcjsProgram progdb
 
--- | Return the 'FilePath' to the global GHC package database.
-getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath
-getGlobalPackageDB verbosity ghcjsProg =
-    (reverse . dropWhile isSpace . reverse) `fmap`
-     getProgramOutput verbosity ghcjsProg ["--print-global-package-db"]
 
 toJSLibName :: String -> String
 toJSLibName lib
@@ -259,6 +370,9 @@ toJSLibName lib
   | takeExtension lib == ".a" = replaceExtension lib "js_a"
   | otherwise                 = lib <.> "js_a"
 
+-- -----------------------------------------------------------------------------
+-- Building a library
+
 buildLib :: Verbosity -> Cabal.Flag (Maybe Int) -> PackageDescription
          -> LocalBuildInfo -> Library -> ComponentLocalBuildInfo
          -> IO ()
@@ -271,30 +385,34 @@ replLib :: [String]                -> Verbosity
 replLib = buildOrReplLib . Just
 
 buildOrReplLib :: Maybe [String] -> Verbosity
-               -> Cabal.Flag (Maybe Int)  -> PackageDescription
-               -> LocalBuildInfo          -> Library
+               -> Cabal.Flag (Maybe Int) -> PackageDescription
+               -> LocalBuildInfo -> Library
                -> ComponentLocalBuildInfo -> IO ()
 buildOrReplLib mReplFlags verbosity numJobs pkg_descr lbi lib clbi = do
   let uid = componentUnitId clbi
-      libTargetDir = buildDir lbi
+      libTargetDir = componentBuildDir lbi clbi
       whenVanillaLib forceVanilla =
-        when (not forRepl && (forceVanilla || withVanillaLib lbi))
-      whenProfLib = when (not forRepl && withProfLib lbi)
+        when (forceVanilla || withVanillaLib lbi)
+      whenProfLib = when (withProfLib lbi)
       whenSharedLib forceShared =
-        when (not forRepl &&  (forceShared || withSharedLib lbi))
-      whenGHCiLib = when (not forRepl && withGHCiLib lbi)
+        when (forceShared || withSharedLib lbi)
+      whenStaticLib forceStatic =
+        when (forceStatic || withStaticLib lbi)
+      -- whenGHCiLib = when (withGHCiLib lbi)
       forRepl = maybe False (const True) mReplFlags
-      ifReplLib = when forRepl
-      replFlags = fromMaybe mempty mReplFlags
-      comp      = compiler lbi
-      platform  = hostPlatform lbi
+      -- ifReplLib = when forRepl
+      comp = compiler lbi
       implInfo  = getImplInfo comp
-      nativeToo = ghcjsNativeToo comp
+      platform@(Platform _hostArch _hostOS) = hostPlatform lbi
+      has_code = not (componentIsIndefinite clbi)
 
   (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi)
-  let runGhcjsProg        = runGHC verbosity ghcjsProg comp platform
-      libBi               = libBuildInfo lib
-      isGhcjsDynamic      = isDynamic comp
+  let runGhcjsProg = runGHC verbosity ghcjsProg comp platform
+
+  let libBi = libBuildInfo lib
+
+  -- fixme flags shouldn't depend on ghcjs being dynamic or not
+  let isGhcjsDynamic        = isDynamic comp
       dynamicTooSupported = supportsDynamicToo comp
       doingTH = usesTemplateHaskellOrQQ libBi
       forceVanillaLib = doingTH && not isGhcjsDynamic
@@ -304,17 +422,23 @@ buildOrReplLib mReplFlags verbosity numJobs pkg_descr lbi lib clbi = do
   -- Determine if program coverage should be enabled and if so, what
   -- '-hpcdir' should be.
   let isCoverageEnabled = libCoverage lbi
-      pkg_name = prettyShow $ PD.package pkg_descr
+      -- TODO: Historically HPC files have been put into a directory which
+      -- has the package name.  I'm going to avoid changing this for
+      -- now, but it would probably be better for this to be the
+      -- component ID instead...
+      pkg_name = prettyShow (PD.package pkg_descr)
       distPref = fromFlag $ configDistPref $ configFlags lbi
       hpcdir way
+        | forRepl = mempty  -- HPC is not supported in ghci
         | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way pkg_name
         | otherwise = mempty
 
   createDirectoryIfMissingVerbose verbosity True libTargetDir
   -- TODO: do we need to put hs-boot files into place for mutually recursive
   -- modules?
-  let cObjs       = map (`replaceExtension` objExtension) (cSources libBi)
+  let cLikeFiles  = fromNubListR $ toNubListR (cSources libBi) <> toNubListR (cxxSources libBi)
       jsSrcs      = jsSources libBi
+      cObjs       = map (`replaceExtension` objExtension) cLikeFiles
       baseOpts    = componentGhcOptions verbosity lbi libBi clbi libTargetDir
       linkJsLibOpts = mempty {
                         ghcOptExtra =
@@ -331,56 +455,46 @@ buildOrReplLib mReplFlags verbosity numJobs pkg_descr lbi lib clbi = do
       vanillaOpts = vanillaOptsNoJsLib `mappend` linkJsLibOpts
 
       profOpts    = adjustExts "p_hi" "p_o" vanillaOpts `mappend` mempty {
-                        ghcOptProfilingMode = toFlag True,
-                        ghcOptExtra         = ghcjsProfOptions libBi,
-                        ghcOptHPCDir        = hpcdir Hpc.Prof
-                      }
-      sharedOpts  = adjustExts "dyn_hi" "dyn_o" vanillaOpts `mappend` mempty {
-                        ghcOptDynLinkMode = toFlag GhcDynamicOnly,
-                        ghcOptFPic        = toFlag True,
-                        ghcOptExtra       = ghcjsSharedOptions libBi,
-                        ghcOptHPCDir      = hpcdir Hpc.Dyn
-                      }
-      linkerOpts = mempty {
-                      ghcOptLinkOptions    = PD.ldOptions libBi,
-                      ghcOptLinkLibs       = extraLibs libBi,
-                      ghcOptLinkLibPath    = toNubListR $ extraLibDirs libBi,
-                      ghcOptLinkFrameworks = toNubListR $ PD.frameworks libBi,
-                      ghcOptInputFiles     =
-                        toNubListR $ [libTargetDir </> x | x <- cObjs] ++ jsSrcs
-                   }
-      replOpts    = vanillaOptsNoJsLib {
-                      ghcOptExtra        = Internal.filterGhciFlags
-                                           (ghcOptExtra vanillaOpts)
-                                           <> replFlags,
-                      ghcOptNumJobs      = mempty
+                      ghcOptProfilingMode = toFlag True,
+                      ghcOptProfilingAuto = Internal.profDetailLevelFlag True
+                                              (withProfLibDetail lbi),
+                    --  ghcOptHiSuffix      = toFlag "p_hi",
+                    --  ghcOptObjSuffix     = toFlag "p_o",
+                      ghcOptExtra         = hcProfOptions GHC libBi,
+                      ghcOptHPCDir        = hpcdir Hpc.Prof
                     }
-                    `mappend` linkerOpts
-                    `mappend` mempty {
-                      ghcOptMode         = toFlag GhcModeInteractive,
-                      ghcOptOptimisation = toFlag GhcNoOptimisation
+
+      sharedOpts  = adjustExts "dyn_hi" "dyn_o" vanillaOpts `mappend` mempty {
+                      ghcOptDynLinkMode = toFlag GhcDynamicOnly,
+                      ghcOptFPic        = toFlag True,
+                    --  ghcOptHiSuffix    = toFlag "dyn_hi",
+                    --  ghcOptObjSuffix   = toFlag "dyn_o",
+                      ghcOptExtra       = hcSharedOptions GHC libBi,
+                      ghcOptHPCDir      = hpcdir Hpc.Dyn
                     }
 
-      vanillaSharedOpts = vanillaOpts `mappend`
-                            mempty {
-                              ghcOptDynLinkMode  = toFlag GhcStaticAndDynamic,
-                              ghcOptDynHiSuffix  = toFlag "dyn_hi",
-                              ghcOptDynObjSuffix = toFlag "dyn_o",
-                              ghcOptHPCDir       = hpcdir Hpc.Dyn
-                            }
+      vanillaSharedOpts = vanillaOpts `mappend` mempty {
+                      ghcOptDynLinkMode  = toFlag GhcStaticAndDynamic,
+                      ghcOptDynHiSuffix  = toFlag "js_dyn_hi",
+                      ghcOptDynObjSuffix = toFlag "js_dyn_o",
+                      ghcOptHPCDir       = hpcdir Hpc.Dyn
+                    }
 
-  unless (forRepl || (null (allLibModules lib clbi) && null jsSrcs && null cObjs)) $
+  unless (forRepl || null (allLibModules lib clbi) && null jsSrcs && null cObjs) $
     do let vanilla = whenVanillaLib forceVanillaLib (runGhcjsProg vanillaOpts)
            shared  = whenSharedLib  forceSharedLib  (runGhcjsProg sharedOpts)
            useDynToo = dynamicTooSupported &&
                        (forceVanillaLib || withVanillaLib lbi) &&
                        (forceSharedLib  || withSharedLib  lbi) &&
-                       null (ghcjsSharedOptions libBi)
-       if useDynToo
+                       null (hcSharedOptions GHC libBi)
+       if not has_code
+        then vanilla
+        else
+         if useDynToo
           then do
               runGhcjsProg vanillaSharedOpts
               case (hpcdir Hpc.Dyn, hpcdir Hpc.Vanilla) of
-                (Cabal.Flag dynDir, Cabal.Flag vanillaDir) -> do
+                (Cabal.Flag dynDir, Cabal.Flag vanillaDir) ->
                     -- When the vanilla and shared library builds are done
                     -- in one pass, only one set of HPC module interfaces
                     -- are generated. This set should suffice for both
@@ -394,73 +508,126 @@ buildOrReplLib mReplFlags verbosity numJobs pkg_descr lbi lib clbi = do
             else do vanilla; shared
        whenProfLib (runGhcjsProg profOpts)
 
-  -- build any C sources
-  unless (null (cSources libBi) || not nativeToo) $ do
-     info verbosity "Building C Sources..."
-     sequence_
-       [ do let vanillaCcOpts =
-                  (Internal.componentCcGhcOptions verbosity implInfo
-                     lbi libBi clbi libTargetDir filename)
-                profCcOpts    = vanillaCcOpts `mappend` mempty {
+  -- Build any C++ sources separately.
+  {-
+  unless (not has_code || null (cxxSources libBi) || not nativeToo) $ do
+    info verbosity "Building C++ Sources..."
+    sequence_
+      [ do let baseCxxOpts    = Internal.componentCxxGhcOptions verbosity implInfo
+                                lbi libBi clbi libTargetDir filename
+               vanillaCxxOpts = if isGhcjsDynamic
+                                then baseCxxOpts { ghcOptFPic = toFlag True }
+                                else baseCxxOpts
+               profCxxOpts    = vanillaCxxOpts `mappend` mempty {
                                   ghcOptProfilingMode = toFlag True,
                                   ghcOptObjSuffix     = toFlag "p_o"
                                 }
-                sharedCcOpts  = vanillaCcOpts `mappend` mempty {
-                                  ghcOptFPic        = toFlag True,
-                                  ghcOptDynLinkMode = toFlag GhcDynamicOnly,
-                                  ghcOptObjSuffix   = toFlag "dyn_o"
-                                }
-                odir          = fromFlag (ghcOptObjDir vanillaCcOpts)
-            createDirectoryIfMissingVerbose verbosity True odir
-            runGhcjsProg vanillaCcOpts
-            whenSharedLib forceSharedLib (runGhcjsProg sharedCcOpts)
-            whenProfLib (runGhcjsProg profCcOpts)
-       | filename <- cSources libBi]
-
+               sharedCxxOpts  = vanillaCxxOpts `mappend` mempty {
+                                 ghcOptFPic        = toFlag True,
+                                 ghcOptDynLinkMode = toFlag GhcDynamicOnly,
+                                 ghcOptObjSuffix   = toFlag "dyn_o"
+                               }
+               odir           = fromFlag (ghcOptObjDir vanillaCxxOpts)
+           createDirectoryIfMissingVerbose verbosity True odir
+           let runGhcProgIfNeeded cxxOpts = do
+                 needsRecomp <- checkNeedsRecompilation filename cxxOpts
+                 when needsRecomp $ runGhcjsProg cxxOpts
+           runGhcProgIfNeeded vanillaCxxOpts
+           unless forRepl $
+             whenSharedLib forceSharedLib (runGhcProgIfNeeded sharedCxxOpts)
+           unless forRepl $ whenProfLib   (runGhcProgIfNeeded   profCxxOpts)
+      | filename <- cxxSources libBi]
+
+  ifReplLib $ do
+    when (null (allLibModules lib clbi)) $ warn verbosity "No exposed modules"
+    ifReplLib (runGhcjsProg replOpts)
+-}
+  -- build any C sources
+  -- TODO: Add support for S and CMM files.
+  {-
+  unless (not has_code || null (cSources libBi) || not nativeToo) $ do
+    info verbosity "Building C Sources..."
+    sequence_
+      [ do let baseCcOpts    = Internal.componentCcGhcOptions verbosity implInfo
+                               lbi libBi clbi libTargetDir filename
+               vanillaCcOpts = if isGhcjsDynamic
+                               -- Dynamic GHC requires C sources to be built
+                               -- with -fPIC for REPL to work. See #2207.
+                               then baseCcOpts { ghcOptFPic = toFlag True }
+                               else baseCcOpts
+               profCcOpts    = vanillaCcOpts `mappend` mempty {
+                                 ghcOptProfilingMode = toFlag True,
+                                 ghcOptObjSuffix     = toFlag "p_o"
+                               }
+               sharedCcOpts  = vanillaCcOpts `mappend` mempty {
+                                 ghcOptFPic        = toFlag True,
+                                 ghcOptDynLinkMode = toFlag GhcDynamicOnly,
+                                 ghcOptObjSuffix   = toFlag "dyn_o"
+                               }
+               odir          = fromFlag (ghcOptObjDir vanillaCcOpts)
+           createDirectoryIfMissingVerbose verbosity True odir
+           let runGhcProgIfNeeded ccOpts = do
+                 needsRecomp <- checkNeedsRecompilation filename ccOpts
+                 when needsRecomp $ runGhcjsProg ccOpts
+           runGhcProgIfNeeded vanillaCcOpts
+           unless forRepl $
+             whenSharedLib forceSharedLib (runGhcProgIfNeeded sharedCcOpts)
+           unless forRepl $ whenProfLib (runGhcProgIfNeeded profCcOpts)
+      | filename <- cSources libBi]
+-}
   -- TODO: problem here is we need the .c files built first, so we can load them
   -- with ghci, but .c files can depend on .h files generated by ghc by ffi
   -- exports.
-  unless (null (allLibModules lib clbi)) $
-     ifReplLib (runGhcjsProg replOpts)
 
   -- link:
-  when (nativeToo && not forRepl) $ do
+
+  when has_code . when False {- fixme nativeToo -} . unless forRepl $ do
     info verbosity "Linking..."
-    let cProfObjs   = map (`replaceExtension` ("p_" ++ objExtension))
-                      (cSources libBi)
-        cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension))
-                      (cSources libBi)
+    let cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension))
+                      (cSources libBi ++ cxxSources libBi)
         compiler_id = compilerId (compiler lbi)
-        vanillaLibFilePath = libTargetDir </> mkLibName            uid
-        profileLibFilePath = libTargetDir </> mkProfLibName        uid
-        sharedLibFilePath  = libTargetDir </> mkSharedLibName (hostPlatform lbi) compiler_id uid
-        ghciLibFilePath    = libTargetDir </> Internal.mkGHCiLibName uid
-        ghciProfLibFilePath = libTargetDir </> Internal.mkGHCiProfLibName uid
-
-    hObjs     <- Internal.getHaskellObjects implInfo lib lbi clbi
-                      libTargetDir objExtension True
-    hProfObjs <-
-      if (withProfLib lbi)
-              then Internal.getHaskellObjects implInfo lib lbi clbi
-                      libTargetDir ("p_" ++ objExtension) True
-              else return []
+        sharedLibFilePath = libTargetDir </> mkSharedLibName (hostPlatform lbi) compiler_id uid
+        staticLibFilePath = libTargetDir </> mkStaticLibName (hostPlatform lbi) compiler_id uid
+
+    let stubObjs = []
+        stubSharedObjs = []
+
+{-
+    stubObjs <- catMaybes <$> sequenceA
+      [ findFileWithExtension [objExtension] [libTargetDir]
+          (ModuleName.toFilePath x ++"_stub")
+      | ghcVersion < mkVersion [7,2] -- ghc-7.2+ does not make _stub.o files
+      , x <- allLibModules lib clbi ]
+    stubProfObjs <- catMaybes <$> sequenceA
+      [ findFileWithExtension ["p_" ++ objExtension] [libTargetDir]
+          (ModuleName.toFilePath x ++"_stub")
+      | ghcVersion < mkVersion [7,2] -- ghc-7.2+ does not make _stub.o files
+      , x <- allLibModules lib clbi ]
+    stubSharedObjs <- catMaybes <$> sequenceA
+      [ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir]
+          (ModuleName.toFilePath x ++"_stub")
+      | ghcVersion < mkVersion [7,2] -- ghc-7.2+ does not make _stub.o files
+      , x <- allLibModules lib clbi ]
+-}
+    hObjs <- Internal.getHaskellObjects implInfo lib lbi clbi
+               libTargetDir objExtension True
     hSharedObjs <-
-      if (withSharedLib lbi)
+      if withSharedLib lbi
               then Internal.getHaskellObjects implInfo lib lbi clbi
                       libTargetDir ("dyn_" ++ objExtension) False
               else return []
 
-    unless (null hObjs && null cObjs) $ do
+    unless (null hObjs && null cObjs && null stubObjs) $ do
+      rpaths <- getRPaths lbi clbi
 
       let staticObjectFiles =
                  hObjs
               ++ map (libTargetDir </>) cObjs
-          profObjectFiles =
-                 hProfObjs
-              ++ map (libTargetDir </>) cProfObjs
+              ++ stubObjs
           dynamicObjectFiles =
                  hSharedObjs
               ++ map (libTargetDir </>) cSharedObjs
+              ++ stubSharedObjs
           -- After the relocation lib is created we invoke ghc -shared
           -- with the dependencies spelled out as -package arguments
           -- and ghc invokes the linker with the proper library paths
@@ -470,32 +637,93 @@ buildOrReplLib mReplFlags verbosity numJobs pkg_descr lbi lib clbi = do
                 ghcOptDynLinkMode        = toFlag GhcDynamicOnly,
                 ghcOptInputFiles         = toNubListR dynamicObjectFiles,
                 ghcOptOutputFile         = toFlag sharedLibFilePath,
-                ghcOptExtra              = ghcjsSharedOptions libBi,
+                ghcOptExtra              = hcSharedOptions GHC libBi,
+                -- For dynamic libs, Mac OS/X needs to know the install location
+                -- at build time. This only applies to GHC < 7.8 - see the
+                -- discussion in #1660.
+            {-
+                ghcOptDylibName          = if hostOS == OSX
+                                              && ghcVersion < mkVersion [7,8]
+                                            then toFlag sharedLibInstallPath
+                                            else mempty, -}
+                ghcOptHideAllPackages    = toFlag True,
+                ghcOptNoAutoLinkPackages = toFlag True,
+                ghcOptPackageDBs         = withPackageDB lbi,
+                ghcOptThisUnitId = case clbi of
+                    LibComponentLocalBuildInfo { componentCompatPackageKey = pk }
+                      -> toFlag pk
+                    _ -> mempty,
+                ghcOptThisComponentId = case clbi of
+                    LibComponentLocalBuildInfo { componentInstantiatedWith = insts } ->
+                        if null insts
+                            then mempty
+                            else toFlag (componentComponentId clbi)
+                    _ -> mempty,
+                ghcOptInstantiatedWith = case clbi of
+                    LibComponentLocalBuildInfo { componentInstantiatedWith = insts }
+                      -> insts
+                    _ -> [],
+                ghcOptPackages           = toNubListR $
+                                           Internal.mkGhcOptPackages clbi ,
+                ghcOptLinkLibs           = extraLibs libBi,
+                ghcOptLinkLibPath        = toNubListR $ extraLibDirs libBi,
+                ghcOptLinkFrameworks     = toNubListR $ PD.frameworks libBi,
+                ghcOptLinkFrameworkDirs  =
+                  toNubListR $ PD.extraFrameworkDirs libBi,
+                ghcOptRPaths             = rpaths
+              }
+          ghcStaticLinkArgs =
+              mempty {
+                ghcOptStaticLib          = toFlag True,
+                ghcOptInputFiles         = toNubListR staticObjectFiles,
+                ghcOptOutputFile         = toFlag staticLibFilePath,
+                ghcOptExtra              = hcStaticOptions GHC libBi,
+                ghcOptHideAllPackages    = toFlag True,
                 ghcOptNoAutoLinkPackages = toFlag True,
                 ghcOptPackageDBs         = withPackageDB lbi,
+                ghcOptThisUnitId = case clbi of
+                    LibComponentLocalBuildInfo { componentCompatPackageKey = pk }
+                      -> toFlag pk
+                    _ -> mempty,
+                ghcOptThisComponentId = case clbi of
+                    LibComponentLocalBuildInfo { componentInstantiatedWith = insts } ->
+                        if null insts
+                            then mempty
+                            else toFlag (componentComponentId clbi)
+                    _ -> mempty,
+                ghcOptInstantiatedWith = case clbi of
+                    LibComponentLocalBuildInfo { componentInstantiatedWith = insts }
+                      -> insts
+                    _ -> [],
                 ghcOptPackages           = toNubListR $
-                                           Internal.mkGhcOptPackages clbi,
+                                           Internal.mkGhcOptPackages clbi ,
                 ghcOptLinkLibs           = extraLibs libBi,
                 ghcOptLinkLibPath        = toNubListR $ extraLibDirs libBi
               }
 
+      info verbosity (show (ghcOptPackages ghcSharedLinkArgs))
+{-
       whenVanillaLib False $ do
         Ar.createArLibArchive verbosity lbi vanillaLibFilePath staticObjectFiles
         whenGHCiLib $ do
           (ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi)
           Ld.combineObjectFiles verbosity lbi ldProg
             ghciLibFilePath staticObjectFiles
-
+            -}
+{-
       whenProfLib $ do
         Ar.createArLibArchive verbosity lbi profileLibFilePath profObjectFiles
         whenGHCiLib $ do
           (ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi)
           Ld.combineObjectFiles verbosity lbi ldProg
             ghciProfLibFilePath profObjectFiles
-
+-}
       whenSharedLib False $
         runGhcjsProg ghcSharedLinkArgs
 
+      whenStaticLib False $
+        runGhcjsProg ghcStaticLinkArgs
+
 -- | Start a REPL without loading any source files.
 startInterpreter :: Verbosity -> ProgramDb -> Compiler -> Platform
                  -> PackageDBStack -> IO ()
@@ -508,44 +736,335 @@ startInterpreter verbosity progdb comp platform packageDBs = do
   (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram progdb
   runGHC verbosity ghcjsProg comp platform replOpts
 
-buildExe :: Verbosity          -> Cabal.Flag (Maybe Int)
-         -> PackageDescription -> LocalBuildInfo
-         -> Executable         -> ComponentLocalBuildInfo -> IO ()
-buildExe = buildOrReplExe Nothing
+-- -----------------------------------------------------------------------------
+-- Building an executable or foreign library
+
+-- | Build a foreign library
+buildFLib
+  :: Verbosity          -> Cabal.Flag (Maybe Int)
+  -> PackageDescription -> LocalBuildInfo
+  -> ForeignLib         -> ComponentLocalBuildInfo -> IO ()
+buildFLib v njobs pkg lbi = gbuild v njobs pkg lbi . GBuildFLib
+
+replFLib
+  :: [String]                -> Verbosity
+  -> Cabal.Flag (Maybe Int)  -> PackageDescription
+  -> LocalBuildInfo          -> ForeignLib
+  -> ComponentLocalBuildInfo -> IO ()
+replFLib replFlags  v njobs pkg lbi =
+  gbuild v njobs pkg lbi . GReplFLib replFlags
+
+-- | Build an executable with GHC.
+--
+buildExe
+  :: Verbosity          -> Cabal.Flag (Maybe Int)
+  -> PackageDescription -> LocalBuildInfo
+  -> Executable         -> ComponentLocalBuildInfo -> IO ()
+buildExe v njobs pkg lbi = gbuild v njobs pkg lbi . GBuildExe
+
+replExe
+  :: [String]                -> Verbosity
+  -> Cabal.Flag (Maybe Int)  -> PackageDescription
+  -> LocalBuildInfo          -> Executable
+  -> ComponentLocalBuildInfo -> IO ()
+replExe replFlags v njobs pkg lbi =
+  gbuild v njobs pkg lbi . GReplExe replFlags
+
+-- | Building an executable, starting the REPL, and building foreign
+-- libraries are all very similar and implemented in 'gbuild'. The
+-- 'GBuildMode' distinguishes between the various kinds of operation.
+data GBuildMode =
+    GBuildExe  Executable
+  | GReplExe   [String] Executable
+  | GBuildFLib ForeignLib
+  | GReplFLib  [String] ForeignLib
+
+gbuildInfo :: GBuildMode -> BuildInfo
+gbuildInfo (GBuildExe  exe)  = buildInfo exe
+gbuildInfo (GReplExe   _ exe)  = buildInfo exe
+gbuildInfo (GBuildFLib flib) = foreignLibBuildInfo flib
+gbuildInfo (GReplFLib  _ flib) = foreignLibBuildInfo flib
+
+gbuildName :: GBuildMode -> String
+gbuildName (GBuildExe  exe)  = unUnqualComponentName $ exeName exe
+gbuildName (GReplExe   _ exe)  = unUnqualComponentName $ exeName exe
+gbuildName (GBuildFLib flib) = unUnqualComponentName $ foreignLibName flib
+gbuildName (GReplFLib  _ flib) = unUnqualComponentName $ foreignLibName flib
+
+gbuildTargetName :: LocalBuildInfo -> GBuildMode -> String
+gbuildTargetName lbi (GBuildExe  exe)  = exeTargetName (hostPlatform lbi) exe
+gbuildTargetName lbi (GReplExe   _ exe)  = exeTargetName (hostPlatform lbi) exe
+gbuildTargetName lbi (GBuildFLib flib) = flibTargetName lbi flib
+gbuildTargetName lbi (GReplFLib  _ flib) = flibTargetName lbi flib
+
+exeTargetName :: Platform -> Executable -> String
+exeTargetName platform exe = unUnqualComponentName (exeName exe) `withExt` exeExtension platform
+
+-- | Target name for a foreign library (the actual file name)
+--
+-- We do not use mkLibName and co here because the naming for foreign libraries
+-- is slightly different (we don't use "_p" or compiler version suffices, and we
+-- don't want the "lib" prefix on Windows).
+--
+-- TODO: We do use `dllExtension` and co here, but really that's wrong: they
+-- use the OS used to build cabal to determine which extension to use, rather
+-- than the target OS (but this is wrong elsewhere in Cabal as well).
+flibTargetName :: LocalBuildInfo -> ForeignLib -> String
+flibTargetName lbi flib =
+    case (os, foreignLibType flib) of
+      (Windows, ForeignLibNativeShared) -> nm <.> "dll"
+      (Windows, ForeignLibNativeStatic) -> nm <.> "lib"
+      (Linux,   ForeignLibNativeShared) -> "lib" ++ nm <.> versionedExt
+      (_other,  ForeignLibNativeShared) -> "lib" ++ nm <.> dllExtension (hostPlatform lbi)
+      (_other,  ForeignLibNativeStatic) -> "lib" ++ nm <.> staticLibExtension (hostPlatform lbi)
+      (_any,    ForeignLibTypeUnknown)  -> cabalBug "unknown foreign lib type"
+  where
+    nm :: String
+    nm = unUnqualComponentName $ foreignLibName flib
+
+    os :: OS
+    os = let (Platform _ os') = hostPlatform lbi
+         in os'
+
+    -- If a foreign lib foo has lib-version-info 5:1:2 or
+    -- lib-version-linux 3.2.1, it should be built as libfoo.so.3.2.1
+    -- Libtool's version-info data is translated into library versions in a
+    -- nontrivial way: so refer to libtool documentation.
+    versionedExt :: String
+    versionedExt =
+      let nums = foreignLibVersion flib os
+      in foldl (<.>) "so" (map show nums)
+
+-- | Name for the library when building.
+--
+-- If the `lib-version-info` field or the `lib-version-linux` field of
+-- a foreign library target is set, we need to incorporate that
+-- version into the SONAME field.
+--
+-- If a foreign library foo has lib-version-info 5:1:2, it should be
+-- built as libfoo.so.3.2.1.  We want it to get soname libfoo.so.3.
+-- However, GHC does not allow overriding soname by setting linker
+-- options, as it sets a soname of its own (namely the output
+-- filename), after the user-supplied linker options.  Hence, we have
+-- to compile the library with the soname as its filename.  We rename
+-- the compiled binary afterwards.
+--
+-- This method allows to adjust the name of the library at build time
+-- such that the correct soname can be set.
+flibBuildName :: LocalBuildInfo -> ForeignLib -> String
+flibBuildName lbi flib
+  -- On linux, if a foreign-library has version data, the first digit is used
+  -- to produce the SONAME.
+  | (os, foreignLibType flib) ==
+    (Linux, ForeignLibNativeShared)
+  = let nums = foreignLibVersion flib os
+    in "lib" ++ nm <.> foldl (<.>) "so" (map show (take 1 nums))
+  | otherwise = flibTargetName lbi flib
+  where
+    os :: OS
+    os = let (Platform _ os') = hostPlatform lbi
+         in os'
+
+    nm :: String
+    nm = unUnqualComponentName $ foreignLibName flib
+
+gbuildIsRepl :: GBuildMode -> Bool
+gbuildIsRepl (GBuildExe  _) = False
+gbuildIsRepl (GReplExe _ _) = True
+gbuildIsRepl (GBuildFLib _) = False
+gbuildIsRepl (GReplFLib _ _) = True
+
+gbuildNeedDynamic :: LocalBuildInfo -> GBuildMode -> Bool
+gbuildNeedDynamic lbi bm =
+    case bm of
+      GBuildExe  _    -> withDynExe lbi
+      GReplExe   _ _  -> withDynExe lbi
+      GBuildFLib flib -> withDynFLib flib
+      GReplFLib  _ flib -> withDynFLib flib
+  where
+    withDynFLib flib =
+      case foreignLibType flib of
+        ForeignLibNativeShared ->
+          ForeignLibStandalone `notElem` foreignLibOptions flib
+        ForeignLibNativeStatic ->
+          False
+        ForeignLibTypeUnknown  ->
+          cabalBug "unknown foreign lib type"
+
+gbuildModDefFiles :: GBuildMode -> [FilePath]
+gbuildModDefFiles (GBuildExe _)     = []
+gbuildModDefFiles (GReplExe  _ _)     = []
+gbuildModDefFiles (GBuildFLib flib) = foreignLibModDefFile flib
+gbuildModDefFiles (GReplFLib _ flib) = foreignLibModDefFile flib
+
+-- | "Main" module name when overridden by @ghc-options: -main-is ...@
+-- or 'Nothing' if no @-main-is@ flag could be found.
+--
+-- In case of 'Nothing', 'Distribution.ModuleName.main' can be assumed.
+exeMainModuleName :: Executable -> Maybe ModuleName
+exeMainModuleName Executable{buildInfo = bnfo} =
+    -- GHC honors the last occurence of a module name updated via -main-is
+    --
+    -- Moreover, -main-is when parsed left-to-right can update either
+    -- the "Main" module name, or the "main" function name, or both,
+    -- see also 'decodeMainIsArg'.
+    msum $ reverse $ map decodeMainIsArg $ findIsMainArgs ghcopts
+  where
+    ghcopts = hcOptions GHC bnfo
+
+    findIsMainArgs [] = []
+    findIsMainArgs ("-main-is":arg:rest) = arg : findIsMainArgs rest
+    findIsMainArgs (_:rest) = findIsMainArgs rest
+
+-- | Decode argument to '-main-is'
+--
+-- Returns 'Nothing' if argument set only the function name.
+--
+-- This code has been stolen/refactored from GHC's DynFlags.setMainIs
+-- function. The logic here is deliberately imperfect as it is
+-- intended to be bug-compatible with GHC's parser. See discussion in
+-- https://github.com/haskell/cabal/pull/4539#discussion_r118981753.
+decodeMainIsArg :: String -> Maybe ModuleName
+decodeMainIsArg arg
+  | not (null main_fn) && isLower (head main_fn)
+                        -- The arg looked like "Foo.Bar.baz"
+  = Just (ModuleName.fromString main_mod)
+  | isUpper (head arg)  -- The arg looked like "Foo" or "Foo.Bar"
+  = Just (ModuleName.fromString arg)
+  | otherwise           -- The arg looked like "baz"
+  = Nothing
+  where
+    (main_mod, main_fn) = splitLongestPrefix arg (== '.')
+
+    splitLongestPrefix :: String -> (Char -> Bool) -> (String,String)
+    splitLongestPrefix str pred'
+      | null r_pre = (str,           [])
+      | otherwise  = (reverse (tail r_pre), reverse r_suf)
+                           -- 'tail' drops the char satisfying 'pred'
+      where (r_suf, r_pre) = break pred' (reverse str)
+
+
+-- | A collection of:
+--    * C input files
+--    * C++ input files
+--    * GHC input files
+--    * GHC input modules
+--
+-- Used to correctly build and link sources.
+data BuildSources = BuildSources {
+        cSourcesFiles      :: [FilePath],
+        cxxSourceFiles     :: [FilePath],
+        inputSourceFiles   :: [FilePath],
+        inputSourceModules :: [ModuleName]
+    }
 
-replExe :: [String]                -> Verbosity
-        -> Cabal.Flag (Maybe Int)  -> PackageDescription
-        -> LocalBuildInfo          -> Executable
-        -> ComponentLocalBuildInfo -> IO ()
-replExe = buildOrReplExe . Just
+-- | Locate and return the 'BuildSources' required to build and link.
+gbuildSources :: Verbosity
+              -> Version -- ^ specVersion
+              -> FilePath
+              -> GBuildMode
+              -> IO BuildSources
+gbuildSources verbosity specVer tmpDir bm =
+    case bm of
+      GBuildExe  exe  -> exeSources exe
+      GReplExe   _ exe  -> exeSources exe
+      GBuildFLib flib -> return $ flibSources flib
+      GReplFLib  _ flib -> return $ flibSources flib
+  where
+    exeSources :: Executable -> IO BuildSources
+    exeSources exe@Executable{buildInfo = bnfo, modulePath = modPath} = do
+      main <- findFileEx verbosity (tmpDir : hsSourceDirs bnfo) modPath
+      let mainModName = fromMaybe ModuleName.main $ exeMainModuleName exe
+          otherModNames = exeModules exe
+
+      if isHaskell main
+        then
+          if specVer < mkVersion [2] && (mainModName `elem` otherModNames)
+          then do
+             -- The cabal manual clearly states that `other-modules` is
+             -- intended for non-main modules.  However, there's at least one
+             -- important package on Hackage (happy-1.19.5) which
+             -- violates this. We workaround this here so that we don't
+             -- invoke GHC with e.g.  'ghc --make Main src/Main.hs' which
+             -- would result in GHC complaining about duplicate Main
+             -- modules.
+             --
+             -- Finally, we only enable this workaround for
+             -- specVersion < 2, as 'cabal-version:>=2.0' cabal files
+             -- have no excuse anymore to keep doing it wrong... ;-)
+             warn verbosity $ "Enabling workaround for Main module '"
+                            ++ prettyShow mainModName
+                            ++ "' listed in 'other-modules' illegally!"
+
+             return BuildSources {
+                        cSourcesFiles      = cSources bnfo,
+                        cxxSourceFiles     = cxxSources bnfo,
+                        inputSourceFiles   = [main],
+                        inputSourceModules = filter (/= mainModName) $ exeModules exe
+                    }
 
-buildOrReplExe :: Maybe [String] -> Verbosity
-               -> Cabal.Flag (Maybe Int) -> PackageDescription
-               -> LocalBuildInfo -> Executable
-               -> ComponentLocalBuildInfo -> IO ()
-buildOrReplExe mReplFlags verbosity numJobs _pkg_descr lbi
-  exe@Executable { exeName = exeName', modulePath = modPath } clbi = do
+          else return BuildSources {
+                          cSourcesFiles      = cSources bnfo,
+                          cxxSourceFiles     = cxxSources bnfo,
+                          inputSourceFiles   = [main],
+                          inputSourceModules = exeModules exe
+                      }
+        else let (csf, cxxsf)
+                   | isCxx main = (       cSources bnfo, main : cxxSources bnfo)
+                   -- if main is not a Haskell source
+                   -- and main is not a C++ source
+                   -- then we assume that it is a C source
+                   | otherwise  = (main : cSources bnfo,        cxxSources bnfo)
+
+             in  return BuildSources {
+                            cSourcesFiles      = csf,
+                            cxxSourceFiles     = cxxsf,
+                            inputSourceFiles   = [],
+                            inputSourceModules = exeModules exe
+                        }
+
+    flibSources :: ForeignLib -> BuildSources
+    flibSources flib@ForeignLib{foreignLibBuildInfo = bnfo} =
+        BuildSources {
+            cSourcesFiles      = cSources bnfo,
+            cxxSourceFiles     = cxxSources bnfo,
+            inputSourceFiles   = [],
+            inputSourceModules = foreignLibModules flib
+        }
+
+    isHaskell :: FilePath -> Bool
+    isHaskell fp = elem (takeExtension fp) [".hs", ".lhs"]
 
+    isCxx :: FilePath -> Bool
+    isCxx fp = elem (takeExtension fp) [".cpp", ".cxx", ".c++"]
+
+-- | Generic build function. See comment for 'GBuildMode'.
+gbuild :: Verbosity          -> Cabal.Flag (Maybe Int)
+       -> PackageDescription -> LocalBuildInfo
+       -> GBuildMode         -> ComponentLocalBuildInfo -> IO ()
+gbuild verbosity numJobs pkg_descr lbi bm clbi = do
   (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi)
-  let forRepl = maybe False (const True) mReplFlags
-      replFlags = fromMaybe mempty mReplFlags
-      comp         = compiler lbi
-      platform     = hostPlatform lbi
-      implInfo     = getImplInfo comp
-      runGhcjsProg = runGHC verbosity ghcjsProg comp platform
-      exeBi        = buildInfo exe
-
-  let exeName'' = unUnqualComponentName exeName'
-  -- exeNameReal, the name that GHC really uses (with .exe on Windows)
-  let exeNameReal = exeName'' <.>
-                    (if takeExtension exeName'' /= ('.':exeExtension buildPlatform)
-                       then exeExtension buildPlatform
-                       else "")
-
-  let targetDir = (buildDir lbi) </> exeName''
-  let exeDir    = targetDir </> (exeName'' ++ "-tmp")
+  let replFlags = case bm of
+          GReplExe flags _  -> flags
+          GReplFLib flags _ -> flags
+          GBuildExe{}       -> mempty
+          GBuildFLib{}      -> mempty
+      comp       = compiler lbi
+      platform   = hostPlatform lbi
+      implInfo   = getImplInfo comp
+      runGhcProg = runGHC verbosity ghcjsProg comp platform
+
+  let (bnfo, threaded) = case bm of
+        GBuildFLib _ -> popThreadedFlag (gbuildInfo bm)
+        _            -> (gbuildInfo bm, False)
+
+  -- the name that GHC really uses (e.g., with .exe on Windows for executables)
+  let targetName = gbuildTargetName lbi bm
+  let targetDir  = buildDir lbi </> (gbuildName bm)
+  let tmpDir     = targetDir    </> (gbuildName bm ++ "-tmp")
   createDirectoryIfMissingVerbose verbosity True targetDir
-  createDirectoryIfMissingVerbose verbosity True exeDir
+  createDirectoryIfMissingVerbose verbosity True tmpDir
+
   -- TODO: do we need to put hs-boot files into place for mutually recursive
   -- modules?  FIX: what about exeName.hi-boot?
 
@@ -554,64 +1073,75 @@ buildOrReplExe mReplFlags verbosity numJobs _pkg_descr lbi
   let isCoverageEnabled = exeCoverage lbi
       distPref = fromFlag $ configDistPref $ configFlags lbi
       hpcdir way
-        | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way exeName''
-        | otherwise = mempty
+        | gbuildIsRepl bm   = mempty  -- HPC is not supported in ghci
+        | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way (gbuildName bm)
+        | otherwise         = mempty
+
+  rpaths <- getRPaths lbi clbi
+  buildSources <- gbuildSources verbosity (specVersion pkg_descr) tmpDir bm
+
+  let cSrcs               = cSourcesFiles buildSources
+      cxxSrcs             = cxxSourceFiles buildSources
+      inputFiles          = inputSourceFiles buildSources
+      inputModules        = inputSourceModules buildSources
+      isGhcDynamic        = isDynamic comp
+      dynamicTooSupported = supportsDynamicToo comp
+      cObjs               = map (`replaceExtension` objExtension) cSrcs
+      cxxObjs             = map (`replaceExtension` objExtension) cxxSrcs
+      needDynamic         = gbuildNeedDynamic lbi bm
+      needProfiling       = withProfExe lbi
 
   -- build executables
-
-  srcMainFile         <- findFile (exeDir : hsSourceDirs exeBi) modPath
-  let isGhcjsDynamic      = isDynamic comp
-      dynamicTooSupported = supportsDynamicToo comp
-      buildRunner = case clbi of
-                      LibComponentLocalBuildInfo   {} -> False
-                      FLibComponentLocalBuildInfo  {} -> False
-                      ExeComponentLocalBuildInfo   {} -> True
-                      TestComponentLocalBuildInfo  {} -> True
-                      BenchComponentLocalBuildInfo {} -> True
-      isHaskellMain = elem (takeExtension srcMainFile) [".hs", ".lhs"]
-      jsSrcs        = jsSources exeBi
-      cSrcs         = cSources exeBi ++ [srcMainFile | not isHaskellMain]
-      cObjs         = map (`replaceExtension` objExtension) cSrcs
-      nativeToo     = ghcjsNativeToo comp
-      baseOpts   = (componentGhcOptions verbosity lbi exeBi clbi exeDir)
+      baseOpts   = (componentGhcOptions verbosity lbi bnfo clbi tmpDir)
                     `mappend` mempty {
                       ghcOptMode         = toFlag GhcModeMake,
-                      ghcOptInputFiles   = toNubListR $
-                        [ srcMainFile | isHaskellMain],
-                      ghcOptInputModules = toNubListR $
-                        [ m | not isHaskellMain, m <- exeModules exe],
-                      ghcOptExtra =
-                        if buildRunner then ["-build-runner"]
-                                       else mempty
+                      ghcOptInputFiles   = toNubListR inputFiles,
+                      ghcOptInputModules = toNubListR inputModules
                     }
       staticOpts = baseOpts `mappend` mempty {
                       ghcOptDynLinkMode    = toFlag GhcStaticOnly,
                       ghcOptHPCDir         = hpcdir Hpc.Vanilla
                    }
-      profOpts   = adjustExts "p_hi" "p_o" baseOpts `mappend` mempty {
+      profOpts   = baseOpts `mappend` mempty {
                       ghcOptProfilingMode  = toFlag True,
-                      ghcOptExtra          = ghcjsProfOptions exeBi,
+                      ghcOptProfilingAuto  = Internal.profDetailLevelFlag False
+                                             (withProfExeDetail lbi),
+                      ghcOptHiSuffix       = toFlag "p_hi",
+                      ghcOptObjSuffix      = toFlag "p_o",
+                      ghcOptExtra          = hcProfOptions GHC bnfo,
                       ghcOptHPCDir         = hpcdir Hpc.Prof
                     }
-      dynOpts    = adjustExts "dyn_hi" "dyn_o" baseOpts `mappend` mempty {
+      dynOpts    = baseOpts `mappend` mempty {
                       ghcOptDynLinkMode    = toFlag GhcDynamicOnly,
-                      ghcOptExtra          = ghcjsSharedOptions exeBi,
+                      -- TODO: Does it hurt to set -fPIC for executables?
+                      ghcOptFPic           = toFlag True,
+                      ghcOptHiSuffix       = toFlag "dyn_hi",
+                      ghcOptObjSuffix      = toFlag "dyn_o",
+                      ghcOptExtra          = hcSharedOptions GHC bnfo,
                       ghcOptHPCDir         = hpcdir Hpc.Dyn
                     }
-      dynTooOpts = adjustExts "dyn_hi" "dyn_o" staticOpts `mappend` mempty {
+      dynTooOpts = staticOpts `mappend` mempty {
                       ghcOptDynLinkMode    = toFlag GhcStaticAndDynamic,
+                      ghcOptDynHiSuffix    = toFlag "dyn_hi",
+                      ghcOptDynObjSuffix   = toFlag "dyn_o",
                       ghcOptHPCDir         = hpcdir Hpc.Dyn
                     }
       linkerOpts = mempty {
-                      ghcOptLinkOptions    = PD.ldOptions exeBi,
-                      ghcOptLinkLibs       = extraLibs exeBi,
-                      ghcOptLinkLibPath    = toNubListR $ extraLibDirs exeBi,
-                      ghcOptLinkFrameworks = toNubListR $ PD.frameworks exeBi,
-                      ghcOptInputFiles     = toNubListR $
-                                             [exeDir </> x | x <- cObjs] ++ jsSrcs
+                      ghcOptLinkOptions       = PD.ldOptions bnfo,
+                      ghcOptLinkLibs          = extraLibs bnfo,
+                      ghcOptLinkLibPath       = toNubListR $ extraLibDirs bnfo,
+                      ghcOptLinkFrameworks    = toNubListR $
+                                                PD.frameworks bnfo,
+                      ghcOptLinkFrameworkDirs = toNubListR $
+                                                PD.extraFrameworkDirs bnfo,
+                      ghcOptInputFiles     = toNubListR
+                                             [tmpDir </> x | x <- cObjs ++ cxxObjs]
+                    }
+      dynLinkerOpts = mempty {
+                      ghcOptRPaths         = rpaths
                    }
       replOpts   = baseOpts {
-                      ghcOptExtra          = Internal.filterGhciFlags
+                    ghcOptExtra            = Internal.filterGhciFlags
                                              (ghcOptExtra baseOpts)
                                              <> replFlags
                    }
@@ -622,15 +1152,15 @@ buildOrReplExe mReplFlags verbosity numJobs _pkg_descr lbi
                    -- files etc.
                    `mappend` linkerOpts
                    `mappend` mempty {
-                      ghcOptMode           = toFlag GhcModeInteractive,
-                      ghcOptOptimisation   = toFlag GhcNoOptimisation
-                   }
-      commonOpts  | withProfExe lbi = profOpts
-                  | withDynExe  lbi = dynOpts
-                  | otherwise       = staticOpts
+                      ghcOptMode         = toFlag GhcModeInteractive,
+                      ghcOptOptimisation = toFlag GhcNoOptimisation
+                     }
+      commonOpts  | needProfiling = profOpts
+                  | needDynamic   = dynOpts
+                  | otherwise     = staticOpts
       compileOpts | useDynToo = dynTooOpts
                   | otherwise = commonOpts
-      withStaticExe = (not $ withProfExe lbi) && (not $ withDynExe lbi)
+      withStaticExe = not needProfiling && not needDynamic
 
       -- For building exe's that use TH with -prof or -dynamic we actually have
       -- to build twice, once without -prof/-dynamic and then again with
@@ -639,57 +1169,498 @@ buildOrReplExe mReplFlags verbosity numJobs _pkg_descr lbi
       -- by the compiler.
       -- With dynamic-by-default GHC the TH object files loaded at compile-time
       -- need to be .dyn_o instead of .o.
-      doingTH = usesTemplateHaskellOrQQ exeBi
+      doingTH = usesTemplateHaskellOrQQ bnfo
       -- Should we use -dynamic-too instead of compiling twice?
-      useDynToo = dynamicTooSupported && isGhcjsDynamic
-                  && doingTH && withStaticExe && null (ghcjsSharedOptions exeBi)
-      compileTHOpts | isGhcjsDynamic = dynOpts
-                    | otherwise      = staticOpts
+      useDynToo = dynamicTooSupported && isGhcDynamic
+                  && doingTH && withStaticExe
+                  && null (hcSharedOptions GHC bnfo)
+      compileTHOpts | isGhcDynamic = dynOpts
+                    | otherwise    = staticOpts
       compileForTH
-        | forRepl      = False
-        | useDynToo    = False
-        | isGhcjsDynamic = doingTH && (withProfExe lbi || withStaticExe)
-        | otherwise      = doingTH && (withProfExe lbi || withDynExe lbi)
-
-      linkOpts = commonOpts `mappend`
-                 linkerOpts `mappend` mempty {
-                      ghcOptLinkNoHsMain   = toFlag (not isHaskellMain)
-                 }
+        | gbuildIsRepl bm = False
+        | useDynToo       = False
+        | isGhcDynamic    = doingTH && (needProfiling || withStaticExe)
+        | otherwise       = doingTH && (needProfiling || needDynamic)
 
-  -- Build static/dynamic object files for TH, if needed.
+   -- Build static/dynamic object files for TH, if needed.
   when compileForTH $
-    runGhcjsProg compileTHOpts { ghcOptNoLink  = toFlag True
-                               , ghcOptNumJobs = numJobs }
-
-  unless forRepl $
-    runGhcjsProg compileOpts { ghcOptNoLink  = toFlag True
+    runGhcProg compileTHOpts { ghcOptNoLink  = toFlag True
                              , ghcOptNumJobs = numJobs }
 
+  -- Do not try to build anything if there are no input files.
+  -- This can happen if the cabal file ends up with only cSrcs
+  -- but no Haskell modules.
+  unless ((null inputFiles && null inputModules)
+          || gbuildIsRepl bm) $
+    runGhcProg compileOpts { ghcOptNoLink  = toFlag True
+                           , ghcOptNumJobs = numJobs }
+
+  -- build any C++ sources
+  unless (null cxxSrcs) $ do
+   info verbosity "Building C++ Sources..."
+   sequence_
+     [ do let baseCxxOpts    = Internal.componentCxxGhcOptions verbosity implInfo
+                               lbi bnfo clbi tmpDir filename
+              vanillaCxxOpts = if isGhcDynamic
+                                -- Dynamic GHC requires C++ sources to be built
+                                -- with -fPIC for REPL to work. See #2207.
+                               then baseCxxOpts { ghcOptFPic = toFlag True }
+                               else baseCxxOpts
+              profCxxOpts    = vanillaCxxOpts `mappend` mempty {
+                                 ghcOptProfilingMode = toFlag True
+                               }
+              sharedCxxOpts  = vanillaCxxOpts `mappend` mempty {
+                                 ghcOptFPic        = toFlag True,
+                                 ghcOptDynLinkMode = toFlag GhcDynamicOnly
+                               }
+              opts | needProfiling = profCxxOpts
+                   | needDynamic   = sharedCxxOpts
+                   | otherwise     = vanillaCxxOpts
+              -- TODO: Placing all Haskell, C, & C++ objects in a single directory
+              --       Has the potential for file collisions. In general we would
+              --       consider this a user error. However, we should strive to
+              --       add a warning if this occurs.
+              odir = fromFlag (ghcOptObjDir opts)
+          createDirectoryIfMissingVerbose verbosity True odir
+          needsRecomp <- checkNeedsRecompilation filename opts
+          when needsRecomp $
+            runGhcProg opts
+     | filename <- cxxSrcs ]
+
   -- build any C sources
-  unless (null cSrcs || not nativeToo) $ do
+  unless (null cSrcs) $ do
    info verbosity "Building C Sources..."
    sequence_
-     [ do let opts = (Internal.componentCcGhcOptions verbosity implInfo lbi exeBi
-                         clbi exeDir filename) `mappend` mempty {
-                       ghcOptDynLinkMode   = toFlag (if withDynExe lbi
-                                                       then GhcDynamicOnly
-                                                       else GhcStaticOnly),
-                       ghcOptProfilingMode = toFlag (withProfExe lbi)
-                     }
+     [ do let baseCcOpts    = Internal.componentCcGhcOptions verbosity implInfo
+                              lbi bnfo clbi tmpDir filename
+              vanillaCcOpts = if isGhcDynamic
+                              -- Dynamic GHC requires C sources to be built
+                              -- with -fPIC for REPL to work. See #2207.
+                              then baseCcOpts { ghcOptFPic = toFlag True }
+                              else baseCcOpts
+              profCcOpts    = vanillaCcOpts `mappend` mempty {
+                                ghcOptProfilingMode = toFlag True
+                              }
+              sharedCcOpts  = vanillaCcOpts `mappend` mempty {
+                                ghcOptFPic        = toFlag True,
+                                ghcOptDynLinkMode = toFlag GhcDynamicOnly
+                              }
+              opts | needProfiling = profCcOpts
+                   | needDynamic   = sharedCcOpts
+                   | otherwise     = vanillaCcOpts
               odir = fromFlag (ghcOptObjDir opts)
           createDirectoryIfMissingVerbose verbosity True odir
-          runGhcjsProg opts
+          needsRecomp <- checkNeedsRecompilation filename opts
+          when needsRecomp $
+            runGhcProg opts
      | filename <- cSrcs ]
 
   -- TODO: problem here is we need the .c files built first, so we can load them
   -- with ghci, but .c files can depend on .h files generated by ghc by ffi
   -- exports.
-  when forRepl $ runGhcjsProg replOpts
+  case bm of
+    GReplExe  _ _ -> runGhcProg replOpts
+    GReplFLib _ _ -> runGhcProg replOpts
+    GBuildExe _ -> do
+      let linkOpts = commonOpts
+                   `mappend` linkerOpts
+                   `mappend` mempty {
+                      ghcOptLinkNoHsMain = toFlag (null inputFiles)
+                     }
+                   `mappend` (if withDynExe lbi then dynLinkerOpts else mempty)
+
+      info verbosity "Linking..."
+      -- Work around old GHCs not relinking in this
+      -- situation, see #3294
+      let target = targetDir </> targetName
+      when (compilerVersion comp < mkVersion [7,7]) $ do
+        e <- doesFileExist target
+        when e (removeFile target)
+      runGhcProg linkOpts { ghcOptOutputFile = toFlag target }
+    GBuildFLib flib -> do
+      let rtsInfo  = extractRtsInfo lbi
+          rtsOptLinkLibs = [
+              if needDynamic
+                  then if threaded
+                            then dynRtsThreadedLib (rtsDynamicInfo rtsInfo)
+                            else dynRtsVanillaLib (rtsDynamicInfo rtsInfo)
+                  else if threaded
+                           then statRtsThreadedLib (rtsStaticInfo rtsInfo)
+                           else statRtsVanillaLib (rtsStaticInfo rtsInfo)
+              ]
+          linkOpts = case foreignLibType flib of
+            ForeignLibNativeShared ->
+                        commonOpts
+              `mappend` linkerOpts
+              `mappend` dynLinkerOpts
+              `mappend` mempty {
+                 ghcOptLinkNoHsMain    = toFlag True,
+                 ghcOptShared          = toFlag True,
+                 ghcOptLinkLibs        = rtsOptLinkLibs,
+                 ghcOptLinkLibPath     = toNubListR $ rtsLibPaths rtsInfo,
+                 ghcOptFPic            = toFlag True,
+                 ghcOptLinkModDefFiles = toNubListR $ gbuildModDefFiles bm
+                }
+              -- See Note [RPATH]
+              `mappend` ifNeedsRPathWorkaround lbi mempty {
+                  ghcOptLinkOptions = ["-Wl,--no-as-needed"]
+                , ghcOptLinkLibs    = ["ffi"]
+                }
+            ForeignLibNativeStatic ->
+              -- this should be caught by buildFLib
+              -- (and if we do implement tihs, we probably don't even want to call
+              -- ghc here, but rather Ar.createArLibArchive or something)
+              cabalBug "static libraries not yet implemented"
+            ForeignLibTypeUnknown ->
+              cabalBug "unknown foreign lib type"
+      -- We build under a (potentially) different filename to set a
+      -- soname on supported platforms.  See also the note for
+      -- @flibBuildName@.
+      info verbosity "Linking..."
+      let buildName = flibBuildName lbi flib
+      runGhcProg linkOpts { ghcOptOutputFile = toFlag (targetDir </> buildName) }
+      renameFile (targetDir </> buildName) (targetDir </> targetName)
+
+{-
+Note [RPATH]
+~~~~~~~~~~~~
+
+Suppose that the dynamic library depends on `base`, but not (directly) on
+`integer-gmp` (which, however, is a dependency of `base`). We will link the
+library as
+
+    gcc ... -lHSbase-4.7.0.2-ghc7.8.4 -lHSinteger-gmp-0.5.1.0-ghc7.8.4 ...
+
+However, on systems (like Ubuntu) where the linker gets called with `-as-needed`
+by default, the linker will notice that `integer-gmp` isn't actually a direct
+dependency and hence omit the link.
+
+Then when we attempt to link a C program against this dynamic library, the
+_static_ linker will attempt to verify that all symbols can be resolved.  The
+dynamic library itself does not require any symbols from `integer-gmp`, but
+`base` does. In order to verify that the symbols used by `base` can be
+resolved, the static linker needs to be able to _find_ integer-gmp.
+
+Finding the `base` dependency is simple, because the dynamic elf header
+(`readelf -d`) for the library that we have created looks something like
+
+    (NEEDED) Shared library: [libHSbase-4.7.0.2-ghc7.8.4.so]
+    (RPATH)  Library rpath: [/path/to/base-4.7.0.2:...]
+
+However, when it comes to resolving the dependency on `integer-gmp`, it needs
+to look at the dynamic header for `base`. On modern ghc (7.8 and higher) this
+looks something like
+
+    (NEEDED) Shared library: [libHSinteger-gmp-0.5.1.0-ghc7.8.4.so]
+    (RPATH)  Library rpath: [$ORIGIN/../integer-gmp-0.5.1.0:...]
+
+This specifies the location of `integer-gmp` _in terms of_ the location of base
+(using the `$ORIGIN`) variable. But here's the crux: when the static linker
+attempts to verify that all symbols can be resolved, [**IT DOES NOT RESOLVE
+`$ORIGIN`**](http://stackoverflow.com/questions/6323603/ld-using-rpath-origin-inside-a-shared-library-recursive).
+As a consequence, it will not be able to resolve the symbols and report the
+missing symbols as errors, _even though the dynamic linker **would** be able to
+resolve these symbols_. We can tell the static linker not to report these
+errors by using `--unresolved-symbols=ignore-all` and all will be fine when we
+run the program ([(indeed, this is what the gold linker
+does)](https://sourceware.org/ml/binutils/2013-05/msg00038.html), but it makes
+the resulting library more difficult to use.
+
+Instead what we can do is make sure that the generated dynamic library has
+explicit top-level dependencies on these libraries. This means that the static
+linker knows where to find them, and when we have transitive dependencies on
+the same libraries the linker will only load them once, so we avoid needing to
+look at the `RPATH` of our dependencies. We can do this by passing
+`--no-as-needed` to the linker, so that it doesn't omit any libraries.
+
+Note that on older ghc (7.6 and before) the Haskell libraries don't have an
+RPATH set at all, which makes it even more important that we make these
+top-level dependencies.
+
+Finally, we have to explicitly link against `libffi` for the same reason. For
+newer ghc this _happens_ to be unnecessary on many systems because `libffi` is
+a library which is not specific to GHC, and when the static linker verifies
+that all symbols can be resolved it will find the `libffi` that is globally
+installed (completely independent from ghc). Of course, this may well be the
+_wrong_ version of `libffi`, but it's quite possible that symbol resolution
+happens to work. This is of course the wrong approach, which is why we link
+explicitly against `libffi` so that we will find the _right_ version of
+`libffi`.
+-}
+
+-- | Do we need the RPATH workaround?
+--
+-- See Note [RPATH].
+ifNeedsRPathWorkaround :: Monoid a => LocalBuildInfo -> a -> a
+ifNeedsRPathWorkaround lbi a =
+  case hostPlatform lbi of
+    Platform _ Linux -> a
+    _otherwise       -> mempty
+
+data DynamicRtsInfo = DynamicRtsInfo {
+    dynRtsVanillaLib          :: FilePath
+  , dynRtsThreadedLib         :: FilePath
+  , dynRtsDebugLib            :: FilePath
+  , dynRtsEventlogLib         :: FilePath
+  , dynRtsThreadedDebugLib    :: FilePath
+  , dynRtsThreadedEventlogLib :: FilePath
+  }
+
+data StaticRtsInfo = StaticRtsInfo {
+    statRtsVanillaLib           :: FilePath
+  , statRtsThreadedLib          :: FilePath
+  , statRtsDebugLib             :: FilePath
+  , statRtsEventlogLib          :: FilePath
+  , statRtsThreadedDebugLib     :: FilePath
+  , statRtsThreadedEventlogLib  :: FilePath
+  , statRtsProfilingLib         :: FilePath
+  , statRtsThreadedProfilingLib :: FilePath
+  }
+
+data RtsInfo = RtsInfo {
+    rtsDynamicInfo :: DynamicRtsInfo
+  , rtsStaticInfo  :: StaticRtsInfo
+  , rtsLibPaths    :: [FilePath]
+  }
+
+-- | Extract (and compute) information about the RTS library
+--
+-- TODO: This hardcodes the name as @HSrts-ghc<version>@. I don't know if we can
+-- find this information somewhere. We can lookup the 'hsLibraries' field of
+-- 'InstalledPackageInfo' but it will tell us @["HSrts", "Cffi"]@, which
+-- doesn't really help.
+extractRtsInfo :: LocalBuildInfo -> RtsInfo
+extractRtsInfo lbi =
+    case PackageIndex.lookupPackageName (installedPkgs lbi) (mkPackageName "rts") of
+      [(_, [rts])] -> aux rts
+      _otherwise   -> error "No (or multiple) ghc rts package is registered"
+  where
+    aux :: InstalledPackageInfo -> RtsInfo
+    aux rts = RtsInfo {
+        rtsDynamicInfo = DynamicRtsInfo {
+            dynRtsVanillaLib          = withGhcVersion "HSrts"
+          , dynRtsThreadedLib         = withGhcVersion "HSrts_thr"
+          , dynRtsDebugLib            = withGhcVersion "HSrts_debug"
+          , dynRtsEventlogLib         = withGhcVersion "HSrts_l"
+          , dynRtsThreadedDebugLib    = withGhcVersion "HSrts_thr_debug"
+          , dynRtsThreadedEventlogLib = withGhcVersion "HSrts_thr_l"
+          }
+      , rtsStaticInfo = StaticRtsInfo {
+            statRtsVanillaLib           = "HSrts"
+          , statRtsThreadedLib          = "HSrts_thr"
+          , statRtsDebugLib             = "HSrts_debug"
+          , statRtsEventlogLib          = "HSrts_l"
+          , statRtsThreadedDebugLib     = "HSrts_thr_debug"
+          , statRtsThreadedEventlogLib  = "HSrts_thr_l"
+          , statRtsProfilingLib         = "HSrts_p"
+          , statRtsThreadedProfilingLib = "HSrts_thr_p"
+          }
+      , rtsLibPaths   = InstalledPackageInfo.libraryDirs rts
+      }
+    withGhcVersion = (++ ("-ghc" ++ prettyShow (compilerVersion (compiler lbi))))
+
+-- | Returns True if the modification date of the given source file is newer than
+-- the object file we last compiled for it, or if no object file exists yet.
+checkNeedsRecompilation :: FilePath -> GhcOptions -> NoCallStackIO Bool
+checkNeedsRecompilation filename opts = filename `moreRecentFile` oname
+    where oname = getObjectFileName filename opts
+
+-- | Finds the object file name of the given source file
+getObjectFileName :: FilePath -> GhcOptions -> FilePath
+getObjectFileName filename opts = oname
+    where odir  = fromFlag (ghcOptObjDir opts)
+          oext  = fromFlagOrDefault "o" (ghcOptObjSuffix opts)
+          oname = odir </> replaceExtension filename oext
+
+-- | Calculate the RPATHs for the component we are building.
+--
+-- Calculates relative RPATHs when 'relocatable' is set.
+getRPaths :: LocalBuildInfo
+          -> ComponentLocalBuildInfo -- ^ Component we are building
+          -> NoCallStackIO (NubListR FilePath)
+getRPaths lbi clbi | supportRPaths hostOS = do
+    libraryPaths <- depLibraryPaths False (relocatable lbi) lbi clbi
+    let hostPref = case hostOS of
+                     OSX -> "@loader_path"
+                     _   -> "$ORIGIN"
+        relPath p = if isRelative p then hostPref </> p else p
+        rpaths    = toNubListR (map relPath libraryPaths)
+    return rpaths
+  where
+    (Platform _ hostOS) = hostPlatform lbi
+    compid              = compilerId . compiler $ lbi
+
+    -- The list of RPath-supported operating systems below reflects the
+    -- platforms on which Cabal's RPATH handling is tested. It does _NOT_
+    -- reflect whether the OS supports RPATH.
+
+    -- E.g. when this comment was written, the *BSD operating systems were
+    -- untested with regards to Cabal RPATH handling, and were hence set to
+    -- 'False', while those operating systems themselves do support RPATH.
+    supportRPaths Linux       = True
+    supportRPaths Windows     = False
+    supportRPaths OSX         = True
+    supportRPaths FreeBSD     =
+      case compid of
+        CompilerId GHC ver | ver >= mkVersion [7,10,2] -> True
+        _                                              -> False
+    supportRPaths OpenBSD     = False
+    supportRPaths NetBSD      = False
+    supportRPaths DragonFly   = False
+    supportRPaths Solaris     = False
+    supportRPaths AIX         = False
+    supportRPaths HPUX        = False
+    supportRPaths IRIX        = False
+    supportRPaths HaLVM       = False
+    supportRPaths IOS         = False
+    supportRPaths Android     = False
+    supportRPaths Ghcjs       = False
+    supportRPaths Hurd        = False
+    supportRPaths (OtherOS _) = False
+    -- Do _not_ add a default case so that we get a warning here when a new OS
+    -- is added.
+
+getRPaths _ _ = return mempty
+
+-- | Remove the "-threaded" flag when building a foreign library, as it has no
+--   effect when used with "-shared". Returns the updated 'BuildInfo', along
+--   with whether or not the flag was present, so we can use it to link against
+--   the appropriate RTS on our own.
+popThreadedFlag :: BuildInfo -> (BuildInfo, Bool)
+popThreadedFlag bi =
+  ( bi { options = filterHcOptions (/= "-threaded") (options bi) }
+  , hasThreaded (options bi))
+
+  where
+    filterHcOptions :: (String -> Bool)
+                    -> PerCompilerFlavor [String]
+                    -> PerCompilerFlavor [String]
+    filterHcOptions p (PerCompilerFlavor ghc ghcjs) =
+        PerCompilerFlavor (filter p ghc) ghcjs
+
+    hasThreaded :: PerCompilerFlavor [String] -> Bool
+    hasThreaded (PerCompilerFlavor ghc _) = elem "-threaded" ghc
+
+-- | Extracts a String representing a hash of the ABI of a built
+-- library.  It can fail if the library has not yet been built.
+--
+libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo
+           -> Library -> ComponentLocalBuildInfo -> IO String
+libAbiHash verbosity _pkg_descr lbi lib clbi = do
+  let
+      libBi = libBuildInfo lib
+      comp        = compiler lbi
+      platform    = hostPlatform lbi
+      vanillaArgs0 =
+        (componentGhcOptions verbosity lbi libBi clbi (componentBuildDir lbi clbi))
+        `mappend` mempty {
+          ghcOptMode         = toFlag GhcModeAbiHash,
+          ghcOptInputModules = toNubListR $ exposedModules lib
+        }
+      vanillaArgs =
+          -- Package DBs unnecessary, and break ghc-cabal. See #3633
+          -- BUT, put at least the global database so that 7.4 doesn't
+          -- break.
+          vanillaArgs0 { ghcOptPackageDBs = [GlobalPackageDB]
+                       , ghcOptPackages = mempty }
+      sharedArgs = vanillaArgs `mappend` mempty {
+                       ghcOptDynLinkMode = toFlag GhcDynamicOnly,
+                       ghcOptFPic        = toFlag True,
+                       ghcOptHiSuffix    = toFlag "js_dyn_hi",
+                       ghcOptObjSuffix   = toFlag "js_dyn_o",
+                       ghcOptExtra       = hcSharedOptions GHC libBi
+                   }
+      profArgs   = vanillaArgs `mappend` mempty {
+                     ghcOptProfilingMode = toFlag True,
+                     ghcOptProfilingAuto = Internal.profDetailLevelFlag True
+                                             (withProfLibDetail lbi),
+                     ghcOptHiSuffix      = toFlag "js_p_hi",
+                     ghcOptObjSuffix     = toFlag "js_p_o",
+                     ghcOptExtra         = hcProfOptions GHC libBi
+                   }
+      ghcArgs
+        | withVanillaLib lbi = vanillaArgs
+        | withSharedLib lbi = sharedArgs
+        | withProfLib lbi = profArgs
+        | otherwise = error "libAbiHash: Can't find an enabled library way"
+
+  (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi)
+  hash <- getProgramInvocationOutput verbosity
+          (ghcInvocation ghcjsProg comp platform ghcArgs)
+  return (takeWhile (not . isSpace) hash)
+
+componentGhcOptions :: Verbosity -> LocalBuildInfo
+                    -> BuildInfo -> ComponentLocalBuildInfo -> FilePath
+                    -> GhcOptions
+componentGhcOptions verbosity lbi bi clbi odir =
+  let opts = Internal.componentGhcOptions verbosity implInfo lbi bi clbi odir
+      comp = compiler lbi
+      implInfo = getImplInfo comp
+  in  opts { ghcOptExtra = ghcOptExtra opts `mappend` hcOptions GHCJS bi
+           }
+
+
+componentCcGhcOptions :: Verbosity -> LocalBuildInfo
+                      -> BuildInfo -> ComponentLocalBuildInfo
+                      -> FilePath -> FilePath
+                      -> GhcOptions
+componentCcGhcOptions verbosity lbi =
+    Internal.componentCcGhcOptions verbosity implInfo lbi
+  where
+    comp     = compiler lbi
+    implInfo = getImplInfo comp
+
+
+-- -----------------------------------------------------------------------------
+-- Installing
+
+-- |Install executables for GHCJS.
+installExe :: Verbosity
+           -> LocalBuildInfo
+           -> FilePath -- ^Where to copy the files to
+           -> FilePath  -- ^Build location
+           -> (FilePath, FilePath)  -- ^Executable (prefix,suffix)
+           -> PackageDescription
+           -> Executable
+           -> IO ()
+installExe verbosity lbi binDir buildPref
+           (progprefix, progsuffix) _pkg exe = do
+  createDirectoryIfMissingVerbose verbosity True binDir
+  let exeName' = unUnqualComponentName $ exeName exe
+      exeFileName = exeName'
+      fixedExeBaseName = progprefix ++ exeName' ++ progsuffix
+      installBinary dest = do
+        runDbProgram verbosity ghcjsProgram (withPrograms lbi) $
+          [ "--install-executable"
+          , buildPref </> exeName' </> exeFileName
+          , "-o", dest
+          ] ++
+          case (stripExes lbi, lookupProgram stripProgram $ withPrograms lbi) of
+           (True, Just strip) -> ["-strip-program", programPath strip]
+           _                  -> []
+  installBinary (binDir </> fixedExeBaseName)
+
+
+-- |Install foreign library for GHC.
+installFLib :: Verbosity
+            -> LocalBuildInfo
+            -> FilePath  -- ^install location
+            -> FilePath  -- ^Build location
+            -> PackageDescription
+            -> ForeignLib
+            -> IO ()
+installFLib verbosity lbi targetDir builtDir _pkg flib =
+    install (foreignLibIsShared flib)
+            builtDir
+            targetDir
+            (flibTargetName lbi flib)
+  where
+    install _isShared srcDir dstDir name = do
+      let src = srcDir </> name
+          dst = dstDir </> name
+      createDirectoryIfMissingVerbose verbosity True targetDir
+      installOrdinaryFile   verbosity src dst
 
-  -- link:
-  unless forRepl $ do
-    info verbosity "Linking..."
-    runGhcjsProg linkOpts { ghcOptOutputFile = toFlag (targetDir </> exeNameReal) }
 
 -- |Install for ghc, .hi, .a and, if --with-ghci given, .o
 installLib    :: Verbosity
@@ -701,31 +1672,34 @@ installLib    :: Verbosity
               -> Library
               -> ComponentLocalBuildInfo
               -> IO ()
-installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do
+installLib verbosity lbi targetDir dynlibTargetDir _builtDir _pkg lib clbi = do
   whenVanilla $ copyModuleFiles "js_hi"
   whenProf    $ copyModuleFiles "js_p_hi"
   whenShared  $ copyModuleFiles "js_dyn_hi"
 
-  whenVanilla $ installOrdinary builtDir targetDir $ toJSLibName vanillaLibName
-  whenProf    $ installOrdinary builtDir targetDir $ toJSLibName profileLibName
-  whenShared  $ installShared   builtDir dynlibTargetDir $ toJSLibName sharedLibName
-
-  when (ghcjsNativeToo $ compiler lbi) $ do
-    -- copy .hi files over:
-    whenVanilla $ copyModuleFiles "hi"
-    whenProf    $ copyModuleFiles "p_hi"
-    whenShared  $ copyModuleFiles "dyn_hi"
-
-    -- copy the built library files over:
+  -- whenVanilla $ installOrdinary builtDir targetDir $ toJSLibName vanillaLibName
+  -- whenProf    $ installOrdinary builtDir targetDir $ toJSLibName profileLibName
+  -- whenShared  $ installShared   builtDir dynlibTargetDir $ toJSLibName sharedLibName
+  -- fixme do these make the correct lib names?
+  whenHasCode $ do
     whenVanilla $ do
-      installOrdinaryNative builtDir targetDir vanillaLibName
-      whenGHCi $ installOrdinaryNative builtDir targetDir ghciLibName
+      sequence_ [ installOrdinary builtDir' targetDir       (toJSLibName $ mkGenericStaticLibName (l ++ f))
+                | l <- getHSLibraryName (componentUnitId clbi):(extraBundledLibs (libBuildInfo lib))
+                , f <- "":extraLibFlavours (libBuildInfo lib)
+                ]
+      -- whenGHCi $ installOrdinary builtDir targetDir (toJSLibName ghciLibName)
     whenProf $ do
-      installOrdinaryNative builtDir targetDir profileLibName
-      whenGHCi $ installOrdinaryNative builtDir targetDir ghciProfLibName
-    whenShared $ installSharedNative builtDir dynlibTargetDir sharedLibName
-
+      installOrdinary builtDir' targetDir (toJSLibName profileLibName)
+      -- whenGHCi $ installOrdinary builtDir targetDir (toJSLibName ghciProfLibName)
+    whenShared  $
+      sequence_ [ installShared builtDir' dynlibTargetDir
+                    (toJSLibName $ mkGenericSharedLibName platform compiler_id (l ++ f))
+                | l <- getHSLibraryName uid : extraBundledLibs (libBuildInfo lib)
+                , f <- "":extraDynLibFlavours (libBuildInfo lib)
+                ]
   where
+    builtDir' = componentBuildDir lbi clbi
+
     install isShared isJS srcDir dstDir name = do
       let src = srcDir </> name
           dst = dstDir </> name
@@ -742,78 +1716,28 @@ installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do
     installOrdinary = install False True
     installShared   = install True  True
 
-    installOrdinaryNative = install False False
-    installSharedNative   = install True  False
-
     copyModuleFiles ext =
-      findModuleFiles [builtDir] [ext] (allLibModules lib clbi)
+      findModuleFilesEx verbosity [builtDir'] [ext] (allLibModules lib clbi)
       >>= installOrdinaryFiles verbosity targetDir
 
     compiler_id = compilerId (compiler lbi)
+    platform = hostPlatform lbi
     uid = componentUnitId clbi
-    vanillaLibName = mkLibName              uid
+    -- vanillaLibName = mkLibName              uid
     profileLibName = mkProfLibName          uid
-    ghciLibName    = Internal.mkGHCiLibName uid
-    ghciProfLibName = Internal.mkGHCiProfLibName uid
-    sharedLibName  = (mkSharedLibName (hostPlatform lbi) compiler_id)  uid
+    -- sharedLibName  = (mkSharedLibName (hostPlatform lbi) compiler_id)  uid
 
     hasLib    = not $ null (allLibModules lib clbi)
                    && null (cSources (libBuildInfo lib))
+                   && null (cxxSources (libBuildInfo lib))
+                   && null (jsSources (libBuildInfo lib))
+    has_code = not (componentIsIndefinite clbi)
+    whenHasCode = when has_code
     whenVanilla = when (hasLib && withVanillaLib lbi)
-    whenProf    = when (hasLib && withProfLib    lbi)
-    whenGHCi    = when (hasLib && withGHCiLib    lbi)
-    whenShared  = when (hasLib && withSharedLib  lbi)
-
-installExe :: Verbosity
-              -> LocalBuildInfo
-              -> FilePath -- ^Where to copy the files to
-              -> FilePath  -- ^Build location
-              -> (FilePath, FilePath)  -- ^Executable (prefix,suffix)
-              -> PackageDescription
-              -> Executable
-              -> IO ()
-installExe verbosity lbi binDir buildPref
-           (progprefix, progsuffix) _pkg exe = do
-  createDirectoryIfMissingVerbose verbosity True binDir
-  let exeName' = unUnqualComponentName $ exeName exe
-      exeFileName = exeName'
-      fixedExeBaseName = progprefix ++ exeName' ++ progsuffix
-      installBinary dest = do
-        runDbProgram verbosity ghcjsProgram (withPrograms lbi) $
-          [ "--install-executable"
-          , buildPref </> exeName' </> exeFileName
-          , "-o", dest
-          ] ++
-          case (stripExes lbi, lookupProgram stripProgram $ withPrograms lbi) of
-           (True, Just strip) -> ["-strip-program", programPath strip]
-           _                  -> []
-  installBinary (binDir </> fixedExeBaseName)
+    whenProf    = when (hasLib && withProfLib    lbi && has_code)
+    -- whenGHCi    = when (hasLib && withGHCiLib    lbi && has_code)
+    whenShared  = when (hasLib && withSharedLib  lbi && has_code)
 
-libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo
-           -> Library -> ComponentLocalBuildInfo -> IO String
-libAbiHash verbosity _pkg_descr lbi lib clbi = do
-  let
-      libBi       = libBuildInfo lib
-      comp        = compiler lbi
-      platform    = hostPlatform lbi
-      vanillaArgs =
-        (componentGhcOptions verbosity lbi libBi clbi (buildDir lbi))
-        `mappend` mempty {
-          ghcOptMode         = toFlag GhcModeAbiHash,
-          ghcOptInputModules = toNubListR $ PD.exposedModules lib
-        }
-      profArgs = adjustExts "js_p_hi" "js_p_o" vanillaArgs `mappend` mempty {
-                     ghcOptProfilingMode = toFlag True,
-                     ghcOptExtra         = ghcjsProfOptions libBi
-                 }
-      ghcArgs | withVanillaLib lbi = vanillaArgs
-              | withProfLib    lbi = profArgs
-              | otherwise = error "libAbiHash: Can't find an enabled library way"
-  --
-  (ghcjsProg, _) <- requireProgram verbosity ghcjsProgram (withPrograms lbi)
-  hash <- getProgramInvocationOutput verbosity
-          (ghcInvocation ghcjsProg comp platform ghcArgs)
-  return (takeWhile (not . isSpace) hash)
 
 adjustExts :: String -> String -> GhcOptions -> GhcOptions
 adjustExts hiSuf objSuf opts =
@@ -822,40 +1746,15 @@ adjustExts hiSuf objSuf opts =
     ghcOptObjSuffix = toFlag objSuf
   }
 
-registerPackage :: Verbosity
-                -> ProgramDb
-                -> PackageDBStack
-                -> InstalledPackageInfo
-                -> HcPkg.RegisterOptions
-                -> IO ()
-registerPackage verbosity progdb packageDbs installedPkgInfo registerOptions =
-    HcPkg.register (hcPkgInfo progdb) verbosity packageDbs
-                   installedPkgInfo registerOptions
-
-componentGhcOptions :: Verbosity -> LocalBuildInfo
-                    -> BuildInfo -> ComponentLocalBuildInfo -> FilePath
-                    -> GhcOptions
-componentGhcOptions verbosity lbi bi clbi odir =
-  let opts = Internal.componentGhcOptions verbosity implInfo lbi bi clbi odir
-      comp = compiler lbi
-      implInfo = getImplInfo comp
-  in  opts { ghcOptExtra = ghcOptExtra opts `mappend` hcOptions GHCJS bi
-           }
-
-ghcjsProfOptions :: BuildInfo -> [String]
-ghcjsProfOptions bi =
-  hcProfOptions GHC bi `mappend` hcProfOptions GHCJS bi
-
-ghcjsSharedOptions :: BuildInfo -> [String]
-ghcjsSharedOptions bi =
-  hcSharedOptions GHC bi `mappend` hcSharedOptions GHCJS bi
-
 isDynamic :: Compiler -> Bool
 isDynamic = Internal.ghcLookupProperty "GHC Dynamic"
 
 supportsDynamicToo :: Compiler -> Bool
 supportsDynamicToo = Internal.ghcLookupProperty "Support dynamic-too"
 
+withExt :: FilePath -> String -> FilePath
+withExt fp ext = fp <.> if takeExtension fp /= ('.':ext) then ext else ""
+
 findGhcjsGhcVersion :: Verbosity -> FilePath -> IO (Maybe Version)
 findGhcjsGhcVersion verbosity pgm =
   findProgramVersion "--numeric-ghc-version" id verbosity pgm
@@ -883,6 +1782,39 @@ hcPkgInfo progdb = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram    = ghcjsPkgProg
     Just ghcjsPkgProg = lookupProgram ghcjsPkgProgram progdb
     Just ver          = programVersion ghcjsPkgProg
 
+registerPackage
+  :: Verbosity
+  -> ProgramDb
+  -> PackageDBStack
+  -> InstalledPackageInfo
+  -> HcPkg.RegisterOptions
+  -> IO ()
+registerPackage verbosity progdb packageDbs installedPkgInfo registerOptions =
+    HcPkg.register (hcPkgInfo progdb) verbosity packageDbs
+                   installedPkgInfo registerOptions
+
+pkgRoot :: Verbosity -> LocalBuildInfo -> PackageDB -> IO FilePath
+pkgRoot verbosity lbi = pkgRoot'
+   where
+    pkgRoot' GlobalPackageDB =
+      let Just ghcjsProg = lookupProgram ghcjsProgram (withPrograms lbi)
+      in  fmap takeDirectory (getGlobalPackageDB verbosity ghcjsProg)
+    pkgRoot' UserPackageDB = do
+      appDir <- getAppUserDataDirectory "ghcjs"
+      -- fixme correct this version
+      let ver      = compilerVersion (compiler lbi)
+          subdir   = System.Info.arch ++ '-':System.Info.os
+                     ++ '-':prettyShow ver
+          rootDir  = appDir </> subdir
+      -- We must create the root directory for the user package database if it
+      -- does not yet exists. Otherwise '${pkgroot}' will resolve to a
+      -- directory at the time of 'ghc-pkg register', and registration will
+      -- fail.
+      createDirectoryIfMissing True rootDir
+      return rootDir
+    pkgRoot' (SpecificPackageDB fp) = return (takeDirectory fp)
+
+
 -- | Get the JavaScript file name and command and arguments to run a
 --   program compiled by GHCJS
 --   the exe should be the base program name without exe extension
diff --git a/Cabal/Distribution/Simple/Haddock.hs b/Cabal/Distribution/Simple/Haddock.hs
index 6fdcb1650c066f60bd43701e8c6c61d2dfb00b8e..8d1fe9bd7dee8b7f270de479154af19dfb024fbf 100644
--- a/Cabal/Distribution/Simple/Haddock.hs
+++ b/Cabal/Distribution/Simple/Haddock.hs
@@ -32,12 +32,14 @@ import qualified Distribution.Simple.GHCJS as GHCJS
 
 -- local
 import Distribution.Backpack.DescribeUnitId
+import Distribution.Backpack (OpenModule)
 import Distribution.Types.ForeignLib
 import Distribution.Types.UnqualComponentName
 import Distribution.Types.ComponentLocalBuildInfo
 import Distribution.Types.ExecutableScope
 import Distribution.Types.LocalBuildInfo
 import Distribution.Types.TargetInfo
+import Distribution.Types.ExposedModule
 import Distribution.Package
 import qualified Distribution.ModuleName as ModuleName
 import Distribution.PackageDescription as PD hiding (Flag)
@@ -64,6 +66,7 @@ import Distribution.Pretty
 import Distribution.Parsec (simpleParsec)
 import Distribution.Utils.NubList
 import Distribution.Version
+
 import Distribution.Verbosity
 import Language.Haskell.Extension
 
@@ -115,6 +118,8 @@ data HaddockArgs = HaddockArgs {
  -- ^ Additional flags to pass to GHC.
  argGhcLibDir :: Flag FilePath,
  -- ^ To find the correct GHC, required.
+ argReexports :: [OpenModule],
+ -- ^ Re-exported modules
  argTargets :: [FilePath]
  -- ^ Modules to process.
 } deriving Generic
@@ -409,10 +414,11 @@ mkHaddockArgs verbosity tmp lbi clbi htmlTemplate haddockVersion inFiles bi = do
             else die' verbosity $ "Must have vanilla or shared libraries "
                        ++ "enabled in order to run haddock"
 
-    return ifaceArgs {
-      argGhcOptions  = opts,
-      argTargets     = inFiles
-    }
+    return ifaceArgs
+      { argGhcOptions  = opts
+      , argTargets     = inFiles
+      , argReexports   = getReexports clbi
+      }
 
 fromLibrary :: Verbosity
             -> FilePath
@@ -496,6 +502,11 @@ getInterfaces verbosity lbi clbi htmlTemplate = do
                  argInterfaces = packageFlags
                }
 
+getReexports :: ComponentLocalBuildInfo -> [OpenModule]
+getReexports LibComponentLocalBuildInfo {componentExposedModules = mods } =
+    mapMaybe exposedReexport mods
+getReexports _ = []
+
 getGhcCppOpts :: Version
               -> BuildInfo
               -> GhcOptions
@@ -646,6 +657,12 @@ renderPureArgs version comp platform args = concat
     , maybe [] (\l -> ["-B"++l]) $
       flagToMaybe (argGhcLibDir args) -- error if Nothing?
 
+      -- https://github.com/haskell/haddock/pull/547
+    , [ "--reexport=" ++ prettyShow r
+      | r <- argReexports args
+      , isVersion 2 19
+      ]
+
     , argTargets $ args
     ]
     where
diff --git a/Cabal/Distribution/Simple/HaskellSuite.hs b/Cabal/Distribution/Simple/HaskellSuite.hs
index 29da725b30a3b1fe65c24d3e8c22bb0ea3e5dc46..35831ead430a94c26b331384f54ed093b409418f 100644
--- a/Cabal/Distribution/Simple/HaskellSuite.hs
+++ b/Cabal/Distribution/Simple/HaskellSuite.hs
@@ -9,6 +9,7 @@ import Distribution.Compat.Prelude
 import Data.Either (partitionEithers)
 
 import qualified Data.Map as Map (empty)
+import qualified Data.List.NonEmpty as NE
 
 import Distribution.Simple.Program
 import Distribution.Simple.Compiler as Compiler
@@ -139,7 +140,7 @@ getInstalledPackages verbosity packagedbs progdb =
     parsePackages str =
         case partitionEithers $ map parseInstalledPackageInfo (splitPkgs str) of
             ([], ok)   -> Right [ pkg | (_, pkg) <- ok ]
-            (msgss, _) -> Left (concat msgss)
+            (msgss, _) -> Left (foldMap NE.toList msgss)
 
     splitPkgs :: String -> [String]
     splitPkgs = map unlines . splitWith ("---" ==) . lines
diff --git a/Cabal/Distribution/Simple/Install.hs b/Cabal/Distribution/Simple/Install.hs
index 264b26fba23261023d948017ed8e5a3ab3a39797..5dc45924d01e6fbf4d07d59edc167df8af860364 100644
--- a/Cabal/Distribution/Simple/Install.hs
+++ b/Cabal/Distribution/Simple/Install.hs
@@ -97,21 +97,10 @@ copyPackage verbosity pkg_descr lbi distPref copydest = do
       -- per-component (data files and Haddock files.)
       InstallDirs {
          datadir    = dataPref,
-         -- NB: The situation with Haddock is a bit delicate.  On the
-         -- one hand, the easiest to understand Haddock documentation
-         -- path is pkgname-0.1, which means it's per-package (not
-         -- per-component).  But this means that it's impossible to
-         -- install Haddock documentation for internal libraries.  We'll
-         -- keep this constraint for now; this means you can't use
-         -- Cabal to Haddock internal libraries.  This does not seem
-         -- like a big problem.
          docdir     = docPref,
          htmldir    = htmlPref,
-         haddockdir = interfacePref}
-             -- Notice use of 'absoluteInstallDirs' (not the
-             -- per-component variant).  This means for non-library
-             -- packages we'll just pick a nondescriptive foo-0.1
-             = absoluteInstallDirs pkg_descr lbi copydest
+         haddockdir = interfacePref
+      } = absoluteInstallCommandDirs pkg_descr lbi (localUnitId lbi) copydest
 
   -- Install (package-global) data files
   installDataFiles verbosity pkg_descr dataPref
@@ -161,7 +150,7 @@ copyComponent verbosity pkg_descr lbi (CLib lib) clbi copydest = do
             libdir = libPref,
             dynlibdir = dynlibPref,
             includedir = incPref
-            } = absoluteComponentInstallDirs pkg_descr lbi (componentUnitId clbi) copydest
+            } = absoluteInstallCommandDirs pkg_descr lbi (componentUnitId clbi) copydest
         buildPref = componentBuildDir lbi clbi
 
     case libName lib of
@@ -194,6 +183,7 @@ copyComponent verbosity pkg_descr lbi (CFLib flib) clbi copydest = do
 
     case compilerFlavor (compiler lbi) of
       GHC   -> GHC.installFLib   verbosity lbi flibPref buildPref pkg_descr flib
+      GHCJS -> GHCJS.installFLib verbosity lbi flibPref buildPref pkg_descr flib
       _ -> die' verbosity $ "installing foreign lib with "
               ++ prettyShow (compilerFlavor (compiler lbi))
               ++ " is not implemented"
@@ -233,17 +223,17 @@ copyComponent _ _ _ (CTest _) _ _ = return ()
 --
 installDataFiles :: Verbosity -> PackageDescription -> FilePath -> IO ()
 installDataFiles verbosity pkg_descr destDataDir =
-  flip traverse_ (dataFiles pkg_descr) $ \ file -> do
+  flip traverse_ (dataFiles pkg_descr) $ \ glob -> do
     let srcDataDirRaw = dataDir pkg_descr
         srcDataDir = if null srcDataDirRaw
           then "."
           else srcDataDirRaw
-    files <- matchDirFileGlob verbosity (specVersion pkg_descr) srcDataDir file
-    let dir = takeDirectory file
-    createDirectoryIfMissingVerbose verbosity True (destDataDir </> dir)
-    sequence_ [ installOrdinaryFile verbosity (srcDataDir  </> file')
-                                              (destDataDir </> file')
-              | file' <- files ]
+    files <- matchDirFileGlob verbosity (specVersion pkg_descr) srcDataDir glob
+    for_ files $ \ file' -> do
+      let src = srcDataDir </> file'
+          dst = destDataDir </> file'
+      createDirectoryIfMissingVerbose verbosity True (takeDirectory dst)
+      installOrdinaryFile verbosity src dst
 
 -- | Install the files listed in install-includes for a library
 --
diff --git a/Cabal/Distribution/Simple/InstallDirs.hs b/Cabal/Distribution/Simple/InstallDirs.hs
index 9d008df0cf9a258005231e0223c9a935e099deef..ab17442cda1f07fac2f1b1d87814e8b29e3a6a1d 100644
--- a/Cabal/Distribution/Simple/InstallDirs.hs
+++ b/Cabal/Distribution/Simple/InstallDirs.hs
@@ -56,6 +56,7 @@ import Distribution.Pretty
 import Distribution.Package
 import Distribution.System
 import Distribution.Compiler
+import Distribution.Simple.InstallDirs.Internal
 
 import System.Directory (getAppUserDataDirectory)
 import System.FilePath
@@ -355,41 +356,6 @@ newtype PathTemplate = PathTemplate [PathComponent]
 
 instance Binary PathTemplate
 
-data PathComponent =
-       Ordinary FilePath
-     | Variable PathTemplateVariable
-     deriving (Eq, Ord, Generic)
-
-instance Binary PathComponent
-
-data PathTemplateVariable =
-       PrefixVar     -- ^ The @$prefix@ path variable
-     | BindirVar     -- ^ The @$bindir@ path variable
-     | LibdirVar     -- ^ The @$libdir@ path variable
-     | LibsubdirVar  -- ^ The @$libsubdir@ path variable
-     | DynlibdirVar  -- ^ The @$dynlibdir@ path variable
-     | DatadirVar    -- ^ The @$datadir@ path variable
-     | DatasubdirVar -- ^ The @$datasubdir@ path variable
-     | DocdirVar     -- ^ The @$docdir@ path variable
-     | HtmldirVar    -- ^ The @$htmldir@ path variable
-     | PkgNameVar    -- ^ The @$pkg@ package name path variable
-     | PkgVerVar     -- ^ The @$version@ package version path variable
-     | PkgIdVar      -- ^ The @$pkgid@ package Id path variable, eg @foo-1.0@
-     | LibNameVar    -- ^ The @$libname@ path variable
-     | CompilerVar   -- ^ The compiler name and version, eg @ghc-6.6.1@
-     | OSVar         -- ^ The operating system name, eg @windows@ or @linux@
-     | ArchVar       -- ^ The CPU architecture name, eg @i386@ or @x86_64@
-     | AbiVar        -- ^ The Compiler's ABI identifier, $arch-$os-$compiler-$abitag
-     | AbiTagVar     -- ^ The optional ABI tag for the compiler
-     | ExecutableNameVar -- ^ The executable name; used in shell wrappers
-     | TestSuiteNameVar   -- ^ The name of the test suite being run
-     | TestSuiteResultVar -- ^ The result of the test suite being run, eg
-                          -- @pass@, @fail@, or @error@.
-     | BenchmarkNameVar   -- ^ The name of the benchmark being run
-  deriving (Eq, Ord, Generic)
-
-instance Binary PathTemplateVariable
-
 type PathTemplateEnv = [(PathTemplateVariable, PathTemplate)]
 
 -- | Convert a 'FilePath' to a 'PathTemplate' including any template vars.
@@ -485,86 +451,6 @@ installDirsTemplateEnv dirs =
 -- spans which are either strings or variables, eg:
 -- PathTemplate [Variable PrefixVar, Ordinary "/bin" ]
 
-instance Show PathTemplateVariable where
-  show PrefixVar     = "prefix"
-  show LibNameVar    = "libname"
-  show BindirVar     = "bindir"
-  show LibdirVar     = "libdir"
-  show LibsubdirVar  = "libsubdir"
-  show DynlibdirVar  = "dynlibdir"
-  show DatadirVar    = "datadir"
-  show DatasubdirVar = "datasubdir"
-  show DocdirVar     = "docdir"
-  show HtmldirVar    = "htmldir"
-  show PkgNameVar    = "pkg"
-  show PkgVerVar     = "version"
-  show PkgIdVar      = "pkgid"
-  show CompilerVar   = "compiler"
-  show OSVar         = "os"
-  show ArchVar       = "arch"
-  show AbiTagVar     = "abitag"
-  show AbiVar        = "abi"
-  show ExecutableNameVar = "executablename"
-  show TestSuiteNameVar   = "test-suite"
-  show TestSuiteResultVar = "result"
-  show BenchmarkNameVar   = "benchmark"
-
-instance Read PathTemplateVariable where
-  readsPrec _ s =
-    take 1
-    [ (var, drop (length varStr) s)
-    | (varStr, var) <- vars
-    , varStr `isPrefixOf` s ]
-    -- NB: order matters! Longer strings first
-    where vars = [("prefix",     PrefixVar)
-                 ,("bindir",     BindirVar)
-                 ,("libdir",     LibdirVar)
-                 ,("libsubdir",  LibsubdirVar)
-                 ,("dynlibdir",  DynlibdirVar)
-                 ,("datadir",    DatadirVar)
-                 ,("datasubdir", DatasubdirVar)
-                 ,("docdir",     DocdirVar)
-                 ,("htmldir",    HtmldirVar)
-                 ,("pkgid",      PkgIdVar)
-                 ,("libname",    LibNameVar)
-                 ,("pkgkey",     LibNameVar) -- backwards compatibility
-                 ,("pkg",        PkgNameVar)
-                 ,("version",    PkgVerVar)
-                 ,("compiler",   CompilerVar)
-                 ,("os",         OSVar)
-                 ,("arch",       ArchVar)
-                 ,("abitag",     AbiTagVar)
-                 ,("abi",        AbiVar)
-                 ,("executablename", ExecutableNameVar)
-                 ,("test-suite", TestSuiteNameVar)
-                 ,("result", TestSuiteResultVar)
-                 ,("benchmark", BenchmarkNameVar)]
-
-instance Show PathComponent where
-  show (Ordinary path) = path
-  show (Variable var)  = '$':show var
-  showList = foldr (\x -> (shows x .)) id
-
-instance Read PathComponent where
-  -- for some reason we collapse multiple $ symbols here
-  readsPrec _ = lex0
-    where lex0 [] = []
-          lex0 ('$':'$':s') = lex0 ('$':s')
-          lex0 ('$':s') = case [ (Variable var, s'')
-                               | (var, s'') <- reads s' ] of
-                            [] -> lex1 "$" s'
-                            ok -> ok
-          lex0 s' = lex1 [] s'
-          lex1 ""  ""      = []
-          lex1 acc ""      = [(Ordinary (reverse acc), "")]
-          lex1 acc ('$':'$':s) = lex1 acc ('$':s)
-          lex1 acc ('$':s) = [(Ordinary (reverse acc), '$':s)]
-          lex1 acc (c:s)   = lex1 (c:acc) s
-  readList [] = [([],"")]
-  readList s  = [ (component:components, s'')
-                | (component, s') <- reads s
-                , (components, s'') <- readList s' ]
-
 instance Show PathTemplate where
   show (PathTemplate template) = show (show template)
 
diff --git a/Cabal/Distribution/Simple/InstallDirs/Internal.hs b/Cabal/Distribution/Simple/InstallDirs/Internal.hs
new file mode 100644
index 0000000000000000000000000000000000000000..c87a6c079f87d69d3a838594651403c7503eacba
--- /dev/null
+++ b/Cabal/Distribution/Simple/InstallDirs/Internal.hs
@@ -0,0 +1,124 @@
+{-# LANGUAGE DeriveGeneric #-}
+module Distribution.Simple.InstallDirs.Internal
+  ( PathComponent(..)
+  , PathTemplateVariable(..)
+  ) where
+
+import Prelude ()
+import Distribution.Compat.Prelude
+
+data PathComponent =
+       Ordinary FilePath
+     | Variable PathTemplateVariable
+     deriving (Eq, Ord, Generic)
+
+instance Binary PathComponent
+
+data PathTemplateVariable =
+       PrefixVar     -- ^ The @$prefix@ path variable
+     | BindirVar     -- ^ The @$bindir@ path variable
+     | LibdirVar     -- ^ The @$libdir@ path variable
+     | LibsubdirVar  -- ^ The @$libsubdir@ path variable
+     | DynlibdirVar  -- ^ The @$dynlibdir@ path variable
+     | DatadirVar    -- ^ The @$datadir@ path variable
+     | DatasubdirVar -- ^ The @$datasubdir@ path variable
+     | DocdirVar     -- ^ The @$docdir@ path variable
+     | HtmldirVar    -- ^ The @$htmldir@ path variable
+     | PkgNameVar    -- ^ The @$pkg@ package name path variable
+     | PkgVerVar     -- ^ The @$version@ package version path variable
+     | PkgIdVar      -- ^ The @$pkgid@ package Id path variable, eg @foo-1.0@
+     | LibNameVar    -- ^ The @$libname@ path variable
+     | CompilerVar   -- ^ The compiler name and version, eg @ghc-6.6.1@
+     | OSVar         -- ^ The operating system name, eg @windows@ or @linux@
+     | ArchVar       -- ^ The CPU architecture name, eg @i386@ or @x86_64@
+     | AbiVar        -- ^ The compiler's ABI identifier,
+                     ---  $arch-$os-$compiler-$abitag
+     | AbiTagVar     -- ^ The optional ABI tag for the compiler
+     | ExecutableNameVar -- ^ The executable name; used in shell wrappers
+     | TestSuiteNameVar   -- ^ The name of the test suite being run
+     | TestSuiteResultVar -- ^ The result of the test suite being run, eg
+                          -- @pass@, @fail@, or @error@.
+     | BenchmarkNameVar   -- ^ The name of the benchmark being run
+  deriving (Eq, Ord, Generic)
+
+instance Binary PathTemplateVariable
+
+instance Show PathTemplateVariable where
+  show PrefixVar     = "prefix"
+  show LibNameVar    = "libname"
+  show BindirVar     = "bindir"
+  show LibdirVar     = "libdir"
+  show LibsubdirVar  = "libsubdir"
+  show DynlibdirVar  = "dynlibdir"
+  show DatadirVar    = "datadir"
+  show DatasubdirVar = "datasubdir"
+  show DocdirVar     = "docdir"
+  show HtmldirVar    = "htmldir"
+  show PkgNameVar    = "pkg"
+  show PkgVerVar     = "version"
+  show PkgIdVar      = "pkgid"
+  show CompilerVar   = "compiler"
+  show OSVar         = "os"
+  show ArchVar       = "arch"
+  show AbiTagVar     = "abitag"
+  show AbiVar        = "abi"
+  show ExecutableNameVar = "executablename"
+  show TestSuiteNameVar   = "test-suite"
+  show TestSuiteResultVar = "result"
+  show BenchmarkNameVar   = "benchmark"
+
+instance Read PathTemplateVariable where
+  readsPrec _ s =
+    take 1
+    [ (var, drop (length varStr) s)
+    | (varStr, var) <- vars
+    , varStr `isPrefixOf` s ]
+    -- NB: order matters! Longer strings first
+    where vars = [("prefix",     PrefixVar)
+                 ,("bindir",     BindirVar)
+                 ,("libdir",     LibdirVar)
+                 ,("libsubdir",  LibsubdirVar)
+                 ,("dynlibdir",  DynlibdirVar)
+                 ,("datadir",    DatadirVar)
+                 ,("datasubdir", DatasubdirVar)
+                 ,("docdir",     DocdirVar)
+                 ,("htmldir",    HtmldirVar)
+                 ,("pkgid",      PkgIdVar)
+                 ,("libname",    LibNameVar)
+                 ,("pkgkey",     LibNameVar) -- backwards compatibility
+                 ,("pkg",        PkgNameVar)
+                 ,("version",    PkgVerVar)
+                 ,("compiler",   CompilerVar)
+                 ,("os",         OSVar)
+                 ,("arch",       ArchVar)
+                 ,("abitag",     AbiTagVar)
+                 ,("abi",        AbiVar)
+                 ,("executablename", ExecutableNameVar)
+                 ,("test-suite", TestSuiteNameVar)
+                 ,("result", TestSuiteResultVar)
+                 ,("benchmark", BenchmarkNameVar)]
+
+instance Show PathComponent where
+  show (Ordinary path) = path
+  show (Variable var)  = '$':show var
+  showList = foldr (\x -> (shows x .)) id
+
+instance Read PathComponent where
+  -- for some reason we collapse multiple $ symbols here
+  readsPrec _ = lex0
+    where lex0 [] = []
+          lex0 ('$':'$':s') = lex0 ('$':s')
+          lex0 ('$':s') = case [ (Variable var, s'')
+                               | (var, s'') <- reads s' ] of
+                            [] -> lex1 "$" s'
+                            ok -> ok
+          lex0 s' = lex1 [] s'
+          lex1 ""  ""      = []
+          lex1 acc ""      = [(Ordinary (reverse acc), "")]
+          lex1 acc ('$':'$':s) = lex1 acc ('$':s)
+          lex1 acc ('$':s) = [(Ordinary (reverse acc), '$':s)]
+          lex1 acc (c:s)   = lex1 (c:acc) s
+  readList [] = [([],"")]
+  readList s  = [ (component:components, s'')
+                | (component, s') <- reads s
+                , (components, s'') <- readList s' ]
diff --git a/Cabal/Distribution/Simple/LocalBuildInfo.hs b/Cabal/Distribution/Simple/LocalBuildInfo.hs
index 52251d5ab92fbcafef02d5c8a1d1fb56fe6da528..9cc88e511401aa9ced8ac6e5aca4a823e9e33b07 100644
--- a/Cabal/Distribution/Simple/LocalBuildInfo.hs
+++ b/Cabal/Distribution/Simple/LocalBuildInfo.hs
@@ -21,7 +21,6 @@
 
 module Distribution.Simple.LocalBuildInfo (
         LocalBuildInfo(..),
-        externalPackageDeps,
         localComponentId,
         localUnitId,
         localCompatPackageKey,
@@ -43,15 +42,11 @@ module Distribution.Simple.LocalBuildInfo (
         pkgBuildableComponents,
         lookupComponent,
         getComponent,
-        getComponentLocalBuildInfo,
         allComponentsInBuildOrder,
-        componentsInBuildOrder,
         depLibraryPaths,
         allLibModules,
 
         withAllComponentsInBuildOrder,
-        withComponentsInBuildOrder,
-        withComponentsLBI,
         withLibLBI,
         withExeLBI,
         withBenchLBI,
@@ -62,6 +57,7 @@ module Distribution.Simple.LocalBuildInfo (
         -- * Installation directories
         module Distribution.Simple.InstallDirs,
         absoluteInstallDirs, prefixRelativeInstallDirs,
+        absoluteInstallCommandDirs,
         absoluteComponentInstallDirs, prefixRelativeComponentInstallDirs,
         substPathTemplate,
   ) where
@@ -95,7 +91,6 @@ import qualified Distribution.Compat.Graph as Graph
 
 import Data.List (stripPrefix)
 import System.FilePath
-import qualified Data.Map as Map
 
 import System.Directory (doesDirectoryExist, canonicalizePath)
 
@@ -122,19 +117,6 @@ componentBuildDir lbi clbi
             CTestName s  -> unUnqualComponentName s
             CBenchName s -> unUnqualComponentName s
 
-{-# DEPRECATED getComponentLocalBuildInfo "This function is not well-defined, because a 'ComponentName' does not uniquely identify a 'ComponentLocalBuildInfo'.  If you have a 'TargetInfo', you should use 'targetCLBI' to get the 'ComponentLocalBuildInfo'.  Otherwise, use 'componentNameTargets' to get all possible 'ComponentLocalBuildInfo's.  This will be removed in Cabal 2.2." #-}
-getComponentLocalBuildInfo :: LocalBuildInfo -> ComponentName -> ComponentLocalBuildInfo
-getComponentLocalBuildInfo lbi cname =
-    case componentNameCLBIs lbi cname of
-      [clbi] -> clbi
-      [] ->
-          error $ "internal error: there is no configuration data "
-               ++ "for component " ++ show cname
-      clbis ->
-          error $ "internal error: the component name " ++ show cname
-               ++ "is ambiguous.  Refers to: "
-               ++ intercalate ", " (map (prettyShow . componentUnitId) clbis)
-
 -- | Perform the action on each enabled 'library' in the package
 -- description with the 'ComponentLocalBuildInfo'.
 withLibLBI :: PackageDescription -> LocalBuildInfo
@@ -182,12 +164,6 @@ enabledBenchLBIs pkg lbi =
     | target <- allTargetsInBuildOrder' pkg lbi
     , CBench bench <- [targetComponent target] ]
 
-{-# DEPRECATED withComponentsLBI "Use withAllComponentsInBuildOrder" #-}
-withComponentsLBI :: PackageDescription -> LocalBuildInfo
-                  -> (Component -> ComponentLocalBuildInfo -> IO ())
-                  -> IO ()
-withComponentsLBI = withAllComponentsInBuildOrder
-
 -- | Perform the action on each buildable 'Library' or 'Executable' (Component)
 -- in the PackageDescription, subject to the build order specified by the
 -- 'compBuildOrder' field of the given 'LocalBuildInfo'
@@ -198,37 +174,11 @@ withAllComponentsInBuildOrder pkg lbi f =
     withAllTargetsInBuildOrder' pkg lbi $ \target ->
         f (targetComponent target) (targetCLBI target)
 
-{-# DEPRECATED withComponentsInBuildOrder "You have got a 'TargetInfo' right? Use 'withNeededTargetsInBuildOrder' on the 'UnitId's you can 'nodeKey' out." #-}
-withComponentsInBuildOrder :: PackageDescription -> LocalBuildInfo
-                           -> [ComponentName]
-                           -> (Component -> ComponentLocalBuildInfo -> IO ())
-                           -> IO ()
-withComponentsInBuildOrder pkg lbi cnames f =
-    withNeededTargetsInBuildOrder' pkg lbi uids $ \target ->
-        f (targetComponent target) (targetCLBI target)
-  where uids = concatMap (componentNameToUnitIds lbi) cnames
-
 allComponentsInBuildOrder :: LocalBuildInfo
                           -> [ComponentLocalBuildInfo]
 allComponentsInBuildOrder lbi =
     Graph.topSort (componentGraph lbi)
 
--- | Private helper function for some of the deprecated implementations.
-componentNameToUnitIds :: LocalBuildInfo -> ComponentName -> [UnitId]
-componentNameToUnitIds lbi cname =
-    case Map.lookup cname (componentNameMap lbi) of
-        Just clbis -> map componentUnitId clbis
-        Nothing -> error $ "componentNameToUnitIds " ++ prettyShow cname
-
-{-# DEPRECATED componentsInBuildOrder "You've got 'TargetInfo' right? Use 'neededTargetsInBuildOrder' on the 'UnitId's you can 'nodeKey' out." #-}
-componentsInBuildOrder :: LocalBuildInfo -> [ComponentName]
-                       -> [ComponentLocalBuildInfo]
-componentsInBuildOrder lbi cnames
-    -- NB: use of localPkgDescr here is safe because we throw out the
-    -- result immediately afterwards
-    = map targetCLBI (neededTargetsInBuildOrder' (localPkgDescr lbi) lbi uids)
-  where uids = concatMap (componentNameToUnitIds lbi) cnames
-
 -- -----------------------------------------------------------------------------
 -- A random function that has no business in this module
 
@@ -353,6 +303,34 @@ absoluteComponentInstallDirs pkg lbi uid copydest =
     (hostPlatform lbi)
     (installDirTemplates lbi)
 
+absoluteInstallCommandDirs :: PackageDescription -> LocalBuildInfo
+                           -> UnitId
+                           -> CopyDest
+                           -> InstallDirs FilePath
+absoluteInstallCommandDirs pkg lbi uid copydest =
+  dirs {
+    -- Handle files which are not
+    -- per-component (data files and Haddock files.)
+    datadir    = datadir    dirs',
+    -- NB: The situation with Haddock is a bit delicate.  On the
+    -- one hand, the easiest to understand Haddock documentation
+    -- path is pkgname-0.1, which means it's per-package (not
+    -- per-component).  But this means that it's impossible to
+    -- install Haddock documentation for internal libraries.  We'll
+    -- keep this constraint for now; this means you can't use
+    -- Cabal to Haddock internal libraries.  This does not seem
+    -- like a big problem.
+    docdir     = docdir     dirs',
+    htmldir    = htmldir    dirs',
+    haddockdir = haddockdir dirs'
+    }
+  where
+    dirs  = absoluteComponentInstallDirs pkg lbi uid copydest
+    -- Notice use of 'absoluteInstallDirs' (not the
+    -- per-component variant).  This means for non-library
+    -- packages we'll just pick a nondescriptive foo-0.1
+    dirs' = absoluteInstallDirs pkg lbi copydest
+
 -- | Backwards compatibility function which computes the InstallDirs
 -- assuming that @$libname@ points to the public library (or some fake
 -- package identifier if there is no public library.)  IF AT ALL
diff --git a/Cabal/Distribution/Simple/PackageIndex.hs b/Cabal/Distribution/Simple/PackageIndex.hs
index 4357d12928b274d0302c1f295034c0affeb25ffa..2c9b26e33fab8444da7cbea0a88a89e4d5e11fc7 100644
--- a/Cabal/Distribution/Simple/PackageIndex.hs
+++ b/Cabal/Distribution/Simple/PackageIndex.hs
@@ -92,11 +92,7 @@ module Distribution.Simple.PackageIndex (
   dependencyInconsistencies,
   dependencyCycles,
   dependencyGraph,
-  moduleNameIndex,
-
-  -- * Backwards compatibility
-  deleteInstalledPackageId,
-  lookupInstalledPackageId,
+  moduleNameIndex
   ) where
 
 import Prelude ()
@@ -120,6 +116,8 @@ import qualified Data.Tree  as Tree
 import Control.Monad
 import Distribution.Compat.Stack
 
+import qualified Prelude (foldr1)
+
 -- | The collection of information about packages from one or more 'PackageDB's.
 -- These packages generally should have an instance of 'PackageInstalled'
 --
@@ -158,7 +156,7 @@ instance Monoid (PackageIndex IPI.InstalledPackageInfo) where
   mappend = (<>)
   --save one mappend with empty in the common case:
   mconcat [] = mempty
-  mconcat xs = foldr1 mappend xs
+  mconcat xs = Prelude.foldr1 mappend xs
 
 instance Semigroup (PackageIndex IPI.InstalledPackageInfo) where
   (<>) = merge
@@ -302,12 +300,6 @@ deleteUnitId ipkgid original@(PackageIndex pids pnames) =
         (\xs -> if null xs then Nothing else Just xs)
       . List.deleteBy (\_ pkg -> installedUnitId pkg == ipkgid) undefined
 
--- | Backwards compatibility wrapper for Cabal pre-1.24.
-{-# DEPRECATED deleteInstalledPackageId "Use deleteUnitId instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-deleteInstalledPackageId :: UnitId -> InstalledPackageIndex
-                         -> InstalledPackageIndex
-deleteInstalledPackageId = deleteUnitId
-
 -- | Removes all packages with this source 'PackageId' from the index.
 --
 deleteSourcePackageId :: PackageId -> InstalledPackageIndex
@@ -418,13 +410,6 @@ lookupComponentId :: PackageIndex a -> ComponentId
 lookupComponentId index cid =
     Map.lookup (newSimpleUnitId cid) (unitIdIndex index)
 
--- | Backwards compatibility for Cabal pre-1.24.
-{-# DEPRECATED lookupInstalledPackageId "Use lookupUnitId instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-lookupInstalledPackageId :: PackageIndex a -> UnitId
-                         -> Maybe a
-lookupInstalledPackageId = lookupUnitId
-
-
 -- | Does a lookup by source package id (name & version).
 --
 -- There can be multiple installed packages with the same source 'PackageId'
diff --git a/Cabal/Distribution/Simple/PreProcess.hs b/Cabal/Distribution/Simple/PreProcess.hs
index 06922a05cf76781e944008f512160e5c15482b99..ec41a69e535ac7aff2e2fcd82fc5959e117d0439 100644
--- a/Cabal/Distribution/Simple/PreProcess.hs
+++ b/Cabal/Distribution/Simple/PreProcess.hs
@@ -727,8 +727,9 @@ preprocessExtras verbosity comp lbi = case comp of
           pp $ buildDir lbi </> nm' </> nm' ++ "-tmp"
       TestSuiteLibV09 _ _ ->
           pp $ buildDir lbi </> stubName test </> stubName test ++ "-tmp"
-      TestSuiteUnsupported tt -> die' verbosity $ "No support for preprocessing test "
-                                    ++ "suite type " ++ prettyShow tt
+      TestSuiteUnsupported tt ->
+        die' verbosity $ "No support for preprocessing test suite type " ++
+                         prettyShow tt
   CBench bm -> do
     let nm' = unUnqualComponentName $ benchmarkName bm
     case benchmarkInterface bm of
diff --git a/Cabal/Distribution/Simple/Program.hs b/Cabal/Distribution/Simple/Program.hs
index 1b1cfdbebf49e91fe2a153a591495666a4c5c312..f1428831cde7cd520c7518a79dbf4e1bc76b0ead 100644
--- a/Cabal/Distribution/Simple/Program.hs
+++ b/Cabal/Distribution/Simple/Program.hs
@@ -118,19 +118,6 @@ module Distribution.Simple.Program (
     , cppProgram
     , pkgConfigProgram
     , hpcProgram
-
-    -- * deprecated
-    , ProgramConfiguration
-    , emptyProgramConfiguration
-    , defaultProgramConfiguration
-    , restoreProgramConfiguration
-    , rawSystemProgram
-    , rawSystemProgramStdout
-    , rawSystemProgramConf
-    , rawSystemProgramStdoutConf
-    , findProgramOnPath
-    , findProgramLocation
-
     ) where
 
 import Prelude ()
@@ -192,48 +179,3 @@ getDbProgramOutput verbosity prog programDb args =
  where
    notFound = "The program '" ++ programName prog
            ++ "' is required but it could not be found"
-
-
----------------------
--- Deprecated aliases
---
-
-{-# DEPRECATED rawSystemProgram "use runProgram instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-rawSystemProgram :: Verbosity -> ConfiguredProgram
-                 -> [ProgArg] -> IO ()
-rawSystemProgram = runProgram
-
-{-# DEPRECATED rawSystemProgramStdout "use getProgramOutput instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-rawSystemProgramStdout :: Verbosity -> ConfiguredProgram
-                       -> [ProgArg] -> IO String
-rawSystemProgramStdout = getProgramOutput
-
-{-# DEPRECATED rawSystemProgramConf "use runDbProgram instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-rawSystemProgramConf :: Verbosity  -> Program -> ProgramConfiguration
-                     -> [ProgArg] -> IO ()
-rawSystemProgramConf = runDbProgram
-
-{-# DEPRECATED rawSystemProgramStdoutConf "use getDbProgramOutput instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-rawSystemProgramStdoutConf :: Verbosity -> Program -> ProgramConfiguration
-                           -> [ProgArg] -> IO String
-rawSystemProgramStdoutConf = getDbProgramOutput
-
-{-# DEPRECATED ProgramConfiguration "use ProgramDb instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-type ProgramConfiguration = ProgramDb
-
-{-# DEPRECATED emptyProgramConfiguration "use emptyProgramDb instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-{-# DEPRECATED defaultProgramConfiguration "use defaultProgramDb instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-emptyProgramConfiguration, defaultProgramConfiguration :: ProgramConfiguration
-emptyProgramConfiguration   = emptyProgramDb
-defaultProgramConfiguration = defaultProgramDb
-
-{-# DEPRECATED restoreProgramConfiguration "use restoreProgramDb instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-restoreProgramConfiguration :: [Program] -> ProgramConfiguration
-                                         -> ProgramConfiguration
-restoreProgramConfiguration = restoreProgramDb
-
-{-# DEPRECATED findProgramOnPath "use findProgramOnSearchPath instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-findProgramOnPath :: String -> Verbosity -> IO (Maybe FilePath)
-findProgramOnPath name verbosity =
-    fmap (fmap fst) $
-    findProgramOnSearchPath verbosity defaultProgramSearchPath name
diff --git a/Cabal/Distribution/Simple/Program/GHC.hs b/Cabal/Distribution/Simple/Program/GHC.hs
index 7ca8e6efa092ace3305281e8978987617b94fa4d..935224951839ce56058452bb61486c82201a1a0d 100644
--- a/Cabal/Distribution/Simple/Program/GHC.hs
+++ b/Cabal/Distribution/Simple/Program/GHC.hs
@@ -25,6 +25,7 @@ import Prelude ()
 import Distribution.Compat.Prelude
 
 import Distribution.Backpack
+import Distribution.Compat.Semigroup (First'(..), Last'(..), Option'(..))
 import Distribution.Simple.GHC.ImplInfo
 import Distribution.PackageDescription hiding (Flag)
 import Distribution.ModuleName
@@ -43,7 +44,7 @@ import Language.Haskell.Extension
 
 import Data.List (stripPrefix)
 import qualified Data.Map as Map
-import Data.Monoid (All(..), Any(..), Endo(..), First(..), Last(..))
+import Data.Monoid (All(..), Any(..), Endo(..))
 import Data.Set (Set)
 import qualified Data.Set as Set
 
@@ -127,15 +128,15 @@ normaliseGhcArgs (Just ghcVersion) PackageDescription{..} ghcArgs
     flagArgumentFilter :: [String] -> [String] -> [String]
     flagArgumentFilter flags = go
       where
-        makeFilter :: String -> String -> First ([String] -> [String])
-        makeFilter flag arg = First $ filterRest <$> stripPrefix flag arg
+        makeFilter :: String -> String -> Option' (First' ([String] -> [String]))
+        makeFilter flag arg = Option' $ First' . filterRest <$> stripPrefix flag arg
           where
             filterRest leftOver = case dropEq leftOver of
                 [] -> drop 1
                 _ -> id
 
         checkFilter :: String -> Maybe ([String] -> [String])
-        checkFilter = getFirst . mconcat (map makeFilter flags)
+        checkFilter = fmap getFirst' . getOption' . foldMap makeFilter flags
 
         go :: [String] -> [String]
         go [] = []
@@ -258,15 +259,13 @@ normaliseGhcArgs (Just ghcVersion) PackageDescription{..} ghcArgs
         ]
 
     safeToFilterHoles :: Bool
-    safeToFilterHoles = getAll . checkGhcFlags $ fromLast . foldMap notDeferred
+    safeToFilterHoles = getAll . checkGhcFlags $
+        All . fromMaybe True . fmap getLast' . getOption' . foldMap notDeferred
       where
-        fromLast :: Last All -> All
-        fromLast = fromMaybe (All True) . getLast
-
-        notDeferred :: String -> Last All
-        notDeferred "-fdefer-typed-holes" = Last . Just . All $ False
-        notDeferred "-fno-defer-typed-holes" = Last . Just . All $ True
-        notDeferred _ = Last Nothing
+        notDeferred :: String -> Option' (Last' Bool)
+        notDeferred "-fdefer-typed-holes" = Option' . Just . Last' $ False
+        notDeferred "-fno-defer-typed-holes" = Option' . Just . Last' $ True
+        notDeferred _ = Option' Nothing
 
     isTypedHoleFlag :: String -> Any
     isTypedHoleFlag = mconcat
diff --git a/Cabal/Distribution/Simple/Program/HcPkg.hs b/Cabal/Distribution/Simple/Program/HcPkg.hs
index 587dc38fe0331c7696bd1cf9f0c7c56c161cb44e..c278f6370be53eed22c7b7357e25cca836d5ddc4 100644
--- a/Cabal/Distribution/Simple/Program/HcPkg.hs
+++ b/Cabal/Distribution/Simple/Program/HcPkg.hs
@@ -46,6 +46,7 @@ import Prelude ()
 import Distribution.Compat.Prelude hiding (init)
 
 import Data.Either (partitionEithers)
+import qualified Data.List.NonEmpty as NE
 
 import Distribution.InstalledPackageInfo
 import Distribution.Simple.Compiler
@@ -263,7 +264,7 @@ parsePackages :: String -> Either [InstalledPackageInfo] [String]
 parsePackages str =
     case partitionEithers $ map parseInstalledPackageInfo (splitPkgs str) of
         ([], ok)   -> Left [ setUnitId . maybe id mungePackagePaths (pkgRoot pkg) $ pkg | (_, pkg) <- ok ]
-        (msgss, _) -> Right (concat msgss)
+        (msgss, _) -> Right (foldMap NE.toList msgss)
 
 --TODO: this could be a lot faster. We're doing normaliseLineEndings twice
 -- and converting back and forth with lines/unlines.
diff --git a/Cabal/Distribution/Simple/Register.hs b/Cabal/Distribution/Simple/Register.hs
index b63bd810579d55681d5e8532df8118fd9c714312..2c0bf61ac9e8021077a36f9f706c8a8f23be7fc1 100644
--- a/Cabal/Distribution/Simple/Register.hs
+++ b/Cabal/Distribution/Simple/Register.hs
@@ -500,7 +500,10 @@ inplaceInstalledPackageInfo inplaceDir distPref pkg abi_hash lib lbi clbi =
     generalInstalledPackageInfo adjustRelativeIncludeDirs
                                 pkg abi_hash lib lbi clbi installDirs
   where
-    adjustRelativeIncludeDirs = map (inplaceDir </>)
+    adjustRelativeIncludeDirs = concatMap $ \d ->
+      [ inplaceDir </> d                    -- local include-dir
+      , inplaceDir </> libTargetDir </> d   -- autogen include-dir
+      ]
     libTargetDir = componentBuildDir lbi clbi
     installDirs =
       (absoluteComponentInstallDirs pkg lbi (componentUnitId clbi) NoCopyDest) {
diff --git a/Cabal/Distribution/Simple/Setup.hs b/Cabal/Distribution/Simple/Setup.hs
index bc648395357a14f179d7690007fbd88975aa5328..3d1096b155fbe65267627f4f41790dd182c17ff9 100644
--- a/Cabal/Distribution/Simple/Setup.hs
+++ b/Cabal/Distribution/Simple/Setup.hs
@@ -45,7 +45,7 @@ module Distribution.Simple.Setup (
   HaddockFlags(..),  emptyHaddockFlags,  defaultHaddockFlags,  haddockCommand,
   HscolourFlags(..), emptyHscolourFlags, defaultHscolourFlags, hscolourCommand,
   BuildFlags(..),    emptyBuildFlags,    defaultBuildFlags,    buildCommand,
-  buildVerbose,
+  ShowBuildInfoFlags(..),                defaultShowBuildFlags, showBuildInfoCommand,
   ReplFlags(..),                         defaultReplFlags,     replCommand,
   CleanFlags(..),    emptyCleanFlags,    defaultCleanFlags,    cleanCommand,
   RegisterFlags(..), emptyRegisterFlags, defaultRegisterFlags, registerCommand,
@@ -59,7 +59,6 @@ module Distribution.Simple.Setup (
   configureArgs, configureOptions, configureCCompiler, configureLinker,
   buildOptions, haddockOptions, installDirsOptions, testOptions',
   programDbOptions, programDbPaths',
-  programConfigurationOptions, programConfigurationPaths',
   programFlagsDescription,
   replOptions,
   splitArgs,
@@ -105,7 +104,7 @@ import Distribution.Types.PackageName
 import Distribution.Types.UnqualComponentName (unUnqualComponentName)
 
 import Distribution.Compat.Stack
-import Distribution.Compat.Semigroup (Last' (..))
+import Distribution.Compat.Semigroup (Last' (..), Option' (..))
 
 import Data.Function (on)
 
@@ -202,8 +201,8 @@ data ConfigFlags = ConfigFlags {
     -- because the type of configure is constrained by the UserHooks.
     -- when we change UserHooks next we should pass the initial
     -- ProgramDb directly and not via ConfigFlags
-    configPrograms_     :: Last' ProgramDb, -- ^All programs that
-                                            -- @cabal@ may run
+    configPrograms_     :: Option' (Last' ProgramDb), -- ^All programs that
+                                                      -- @cabal@ may run
 
     configProgramPaths  :: [(String, FilePath)], -- ^user specified programs paths
     configProgramArgs   :: [(String, [String])], -- ^user specified programs args
@@ -275,9 +274,13 @@ data ConfigFlags = ConfigFlags {
       -- ^Halt and show an error message indicating an error in flag assignment
     configRelocatable :: Flag Bool, -- ^ Enable relocatable package built
     configDebugInfo :: Flag DebugInfoLevel,  -- ^ Emit debug info.
-    configUseResponseFiles :: Flag Bool
+    configUseResponseFiles :: Flag Bool,
       -- ^ Whether to use response files at all. They're used for such tools
       -- as haddock, or or ld.
+    configAllowDependingOnPrivateLibs :: Flag Bool
+      -- ^ Allow depending on private sublibraries. This is used by external
+      -- tools (like cabal-install) so they can add multiple-public-libraries
+      -- compatibility to older ghcs by checking visibility externally.
   }
   deriving (Generic, Read, Show)
 
@@ -286,7 +289,8 @@ instance Binary ConfigFlags
 -- | More convenient version of 'configPrograms'. Results in an
 -- 'error' if internal invariant is violated.
 configPrograms :: WithCallStack (ConfigFlags -> ProgramDb)
-configPrograms = maybe (error "FIXME: remove configPrograms") id . getLast' . configPrograms_
+configPrograms = fromMaybe (error "FIXME: remove configPrograms") . fmap getLast'
+               . getOption' . configPrograms_
 
 instance Eq ConfigFlags where
   (==) a b =
@@ -350,7 +354,7 @@ configAbsolutePaths f =
 defaultConfigFlags :: ProgramDb -> ConfigFlags
 defaultConfigFlags progDb = emptyConfigFlags {
     configArgs         = [],
-    configPrograms_    = pure progDb,
+    configPrograms_    = Option' (Just (Last' progDb)),
     configHcFlavor     = maybe NoFlag Flag defaultCompilerFlavor,
     configVanillaLib   = Flag True,
     configProfLib      = NoFlag,
@@ -377,8 +381,8 @@ defaultConfigFlags progDb = emptyConfigFlags {
 #endif
     configSplitSections = Flag False,
     configSplitObjs    = Flag False, -- takes longer, so turn off by default
-    configStripExes    = Flag True,
-    configStripLibs    = Flag True,
+    configStripExes    = NoFlag,
+    configStripLibs    = NoFlag,
     configTests        = Flag False,
     configBenchmarks   = Flag False,
     configCoverage     = Flag False,
@@ -704,6 +708,13 @@ configureOptions showOrParseArgs =
          configUseResponseFiles
          (\v flags -> flags { configUseResponseFiles = v })
          (boolOpt' ([], ["disable-response-files"]) ([], []))
+
+      ,option "" ["allow-depending-on-private-libs"]
+         (  "Allow depending on private libraries. "
+         ++ "If set, the library visibility check MUST be done externally." )
+         configAllowDependingOnPrivateLibs
+         (\v flags -> flags { configAllowDependingOnPrivateLibs = v })
+         trueArg
       ]
   where
     liftInstallDirs =
@@ -1639,10 +1650,6 @@ data BuildFlags = BuildFlags {
   }
   deriving (Read, Show, Generic)
 
-{-# DEPRECATED buildVerbose "Use buildVerbosity instead" #-}
-buildVerbose :: BuildFlags -> Verbosity
-buildVerbose = fromFlagOrDefault normal . buildVerbosity
-
 defaultBuildFlags :: BuildFlags
 defaultBuildFlags  = BuildFlags {
     buildProgramPaths = mempty,
@@ -1864,6 +1871,7 @@ data TestFlags = TestFlags {
     testMachineLog  :: Flag PathTemplate,
     testShowDetails :: Flag TestShowDetails,
     testKeepTix     :: Flag Bool,
+    testWrapper     :: Flag FilePath,
     testFailWhenNoTestSuites :: Flag Bool,
     -- TODO: think about if/how options are passed to test exes
     testOptions     :: [PathTemplate]
@@ -1877,6 +1885,7 @@ defaultTestFlags  = TestFlags {
     testMachineLog  = toFlag $ toPathTemplate $ "$pkgid.log",
     testShowDetails = toFlag Failures,
     testKeepTix     = toFlag False,
+    testWrapper     = NoFlag,
     testFailWhenNoTestSuites = toFlag False,
     testOptions     = []
   }
@@ -1942,6 +1951,11 @@ testOptions' showOrParseArgs =
         "keep .tix files for HPC between test runs"
         testKeepTix (\v flags -> flags { testKeepTix = v})
         trueArg
+  , option [] ["test-wrapper"]
+        "Run test through a wrapper."
+        testWrapper (\v flags -> flags { testWrapper = v })
+        (reqArg' "FILE" (toFlag :: FilePath -> Flag FilePath)
+            (flagToList :: Flag FilePath -> [FilePath]))
   , option [] ["fail-when-no-test-suites"]
         ("Exit with failure when no test suites are found.")
         testFailWhenNoTestSuites (\v flags -> flags { testFailWhenNoTestSuites = v})
@@ -2069,19 +2083,14 @@ programDbPaths
 programDbPaths progDb showOrParseArgs get set =
   programDbPaths' ("with-" ++) progDb showOrParseArgs get set
 
-{-# DEPRECATED programConfigurationPaths' "Use programDbPaths' instead" #-}
-
 -- | Like 'programDbPaths', but allows to customise the option name.
-programDbPaths', programConfigurationPaths'
+programDbPaths'
   :: (String -> String)
   -> ProgramDb
   -> ShowOrParseArgs
   -> (flags -> [(String, FilePath)])
   -> ([(String, FilePath)] -> (flags -> flags))
   -> [OptionField flags]
-
-programConfigurationPaths' = programDbPaths'
-
 programDbPaths' mkName progDb showOrParseArgs get set =
   case showOrParseArgs of
     -- we don't want a verbose help text list so we just show a generic one:
@@ -2120,19 +2129,15 @@ programDbOption progDb showOrParseArgs get set =
            (\progArgs -> concat [ args
                                 | (prog', args) <- progArgs, prog==prog' ]))
 
-{-# DEPRECATED programConfigurationOptions "Use programDbOptions instead" #-}
 
 -- | For each known program @PROG@ in 'progDb', produce a @PROG-options@
 -- 'OptionField'.
-programDbOptions, programConfigurationOptions
+programDbOptions
   :: ProgramDb
   -> ShowOrParseArgs
   -> (flags -> [(String, [String])])
   -> ([(String, [String])] -> (flags -> flags))
   -> [OptionField flags]
-
-programConfigurationOptions = programDbOptions
-
 programDbOptions progDb showOrParseArgs get set =
   case showOrParseArgs of
     -- we don't want a verbose help text list so we just show a generic one:
@@ -2212,6 +2217,81 @@ optionNumJobs get set =
             | otherwise -> Right (Just n)
           _             -> Left "The jobs value should be a number or '$ncpus'"
 
+
+-- ------------------------------------------------------------
+-- * show-build-info command flags
+-- ------------------------------------------------------------
+
+data ShowBuildInfoFlags = ShowBuildInfoFlags
+  { buildInfoBuildFlags :: BuildFlags
+  , buildInfoOutputFile :: Maybe FilePath
+  } deriving Show
+
+defaultShowBuildFlags  :: ShowBuildInfoFlags
+defaultShowBuildFlags =
+    ShowBuildInfoFlags
+      { buildInfoBuildFlags = defaultBuildFlags
+      , buildInfoOutputFile = Nothing
+      }
+
+showBuildInfoCommand :: ProgramDb -> CommandUI ShowBuildInfoFlags
+showBuildInfoCommand progDb = CommandUI
+  { commandName         = "show-build-info"
+  , commandSynopsis     = "Emit details about how a package would be built."
+  , commandDescription  = Just $ \_ -> wrapText $
+         "Components encompass executables, tests, and benchmarks.\n"
+      ++ "\n"
+      ++ "Affected by configuration options, see `configure`.\n"
+  , commandNotes        = Just $ \pname ->
+       "Examples:\n"
+        ++ "  " ++ pname ++ " show-build-info      "
+        ++ "    All the components in the package\n"
+        ++ "  " ++ pname ++ " show-build-info foo       "
+        ++ "    A component (i.e. lib, exe, test suite)\n\n"
+        ++ programFlagsDescription progDb
+--TODO: re-enable once we have support for module/file targets
+--        ++ "  " ++ pname ++ " show-build-info Foo.Bar   "
+--        ++ "    A module\n"
+--        ++ "  " ++ pname ++ " show-build-info Foo/Bar.hs"
+--        ++ "    A file\n\n"
+--        ++ "If a target is ambiguous it can be qualified with the component "
+--        ++ "name, e.g.\n"
+--        ++ "  " ++ pname ++ " show-build-info foo:Foo.Bar\n"
+--        ++ "  " ++ pname ++ " show-build-info testsuite1:Foo/Bar.hs\n"
+  , commandUsage        = usageAlternatives "show-build-info" $
+      [ "[FLAGS]"
+      , "COMPONENTS [FLAGS]"
+      ]
+  , commandDefaultFlags = defaultShowBuildFlags
+  , commandOptions      = \showOrParseArgs ->
+      parseBuildFlagsForShowBuildInfoFlags showOrParseArgs progDb
+      ++
+      [ option [] ["buildinfo-json-output"]
+                "Write the result to the given file instead of stdout"
+                buildInfoOutputFile (\pf flags -> flags { buildInfoOutputFile = pf })
+                (reqArg' "FILE" Just (maybe [] pure))
+      ]
+
+  }
+
+parseBuildFlagsForShowBuildInfoFlags :: ShowOrParseArgs -> ProgramDb -> [OptionField ShowBuildInfoFlags]
+parseBuildFlagsForShowBuildInfoFlags showOrParseArgs progDb =
+  map
+      (liftOption
+        buildInfoBuildFlags
+          (\bf flags -> flags { buildInfoBuildFlags = bf } )
+      )
+      buildFlags
+  where
+    buildFlags = buildOptions progDb showOrParseArgs
+      ++
+      [ optionVerbosity
+        buildVerbosity (\v flags -> flags { buildVerbosity = v })
+
+      , optionDistPref
+        buildDistPref (\d flags -> flags { buildDistPref = d }) showOrParseArgs
+      ]
+
 -- ------------------------------------------------------------
 -- * Other Utils
 -- ------------------------------------------------------------
diff --git a/Cabal/Distribution/Simple/ShowBuildInfo.hs b/Cabal/Distribution/Simple/ShowBuildInfo.hs
new file mode 100644
index 0000000000000000000000000000000000000000..2a41962fb6e97ded8a295a3fae2da889220388d0
--- /dev/null
+++ b/Cabal/Distribution/Simple/ShowBuildInfo.hs
@@ -0,0 +1,158 @@
+-- |
+-- This module defines a simple JSON-based format for exporting basic
+-- information about a Cabal package and the compiler configuration Cabal
+-- would use to build it. This can be produced with the
+-- @cabal new-show-build-info@ command.
+--
+--
+-- This format is intended for consumption by external tooling and should
+-- therefore be rather stable. Moreover, this allows tooling users to avoid
+-- linking against Cabal. This is an important advantage as direct API usage
+-- tends to be rather fragile in the presence of user-initiated upgrades of
+-- Cabal.
+--
+-- Below is an example of the output this module produces,
+--
+-- @
+-- { "cabal-version": "1.23.0.0",
+--   "compiler": {
+--     "flavour": "GHC",
+--     "compiler-id": "ghc-7.10.2",
+--     "path": "/usr/bin/ghc",
+--   },
+--   "components": [
+--     { "type": "lib",
+--       "name": "lib:Cabal",
+--       "compiler-args":
+--         ["-O", "-XHaskell98", "-Wall",
+--          "-package-id", "parallel-3.2.0.6-b79c38c5c25fff77f3ea7271851879eb"]
+--       "modules": ["Project.ModA", "Project.ModB", "Paths_project"],
+--       "src-files": [],
+--       "src-dirs": ["src"]
+--     }
+--   ]
+-- }
+-- @
+--
+-- The @cabal-version@ property provides the version of the Cabal library
+-- which generated the output. The @compiler@ property gives some basic
+-- information about the compiler Cabal would use to compile the package.
+--
+-- The @components@ property gives a list of the Cabal 'Component's defined by
+-- the package. Each has,
+--
+-- * @type@: the type of the component (one of @lib@, @exe@,
+--   @test@, @bench@, or @flib@)
+-- * @name@: a string serving to uniquely identify the component within the
+--   package.
+-- * @compiler-args@: the command-line arguments Cabal would pass to the
+--   compiler to compile the component
+-- * @modules@: the modules belonging to the component
+-- * @src-dirs@: a list of directories where the modules might be found
+-- * @src-files@: any other Haskell sources needed by the component
+--
+-- Note: At the moment this is only supported when using the GHC compiler.
+--
+
+module Distribution.Simple.ShowBuildInfo (mkBuildInfo) where
+
+import qualified Distribution.Simple.GHC   as GHC
+import qualified Distribution.Simple.Program.GHC as GHC
+
+import Distribution.PackageDescription
+import Distribution.Compiler
+import Distribution.Verbosity
+import Distribution.Simple.Compiler
+import Distribution.Simple.LocalBuildInfo
+import Distribution.Simple.Program
+import Distribution.Simple.Setup
+import Distribution.Simple.Utils (cabalVersion)
+import Distribution.Simple.Utils.Json
+import Distribution.Types.TargetInfo
+import Distribution.Text
+import Distribution.Pretty
+
+-- | Construct a JSON document describing the build information for a
+-- package.
+mkBuildInfo
+  :: PackageDescription  -- ^ Mostly information from the .cabal file
+  -> LocalBuildInfo      -- ^ Configuration information
+  -> BuildFlags          -- ^ Flags that the user passed to build
+  -> [TargetInfo]
+  -> Json
+mkBuildInfo pkg_descr lbi _flags targetsToBuild = info
+  where
+    targetToNameAndLBI target =
+      (componentLocalName $ targetCLBI target, targetCLBI target)
+    componentsToBuild = map targetToNameAndLBI targetsToBuild
+    (.=) :: String -> Json -> (String, Json)
+    k .= v = (k, v)
+
+    info = JsonObject
+      [ "cabal-version" .= JsonString (display cabalVersion)
+      , "compiler"      .= mkCompilerInfo
+      , "components"    .= JsonArray (map mkComponentInfo componentsToBuild)
+      ]
+
+    mkCompilerInfo = JsonObject
+      [ "flavour"     .= JsonString (prettyShow $ compilerFlavor $ compiler lbi)
+      , "compiler-id" .= JsonString (showCompilerId $ compiler lbi)
+      , "path"        .= path
+      ]
+      where
+        path = maybe JsonNull (JsonString . programPath)
+               $ (flavorToProgram . compilerFlavor $ compiler lbi)
+               >>= flip lookupProgram (withPrograms lbi)
+
+        flavorToProgram :: CompilerFlavor -> Maybe Program
+        flavorToProgram GHC   = Just ghcProgram
+        flavorToProgram GHCJS = Just ghcjsProgram
+        flavorToProgram UHC   = Just uhcProgram
+        flavorToProgram JHC   = Just jhcProgram
+        flavorToProgram _     = Nothing
+
+    mkComponentInfo (name, clbi) = JsonObject
+      [ "type"          .= JsonString compType
+      , "name"          .= JsonString (prettyShow name)
+      , "unit-id"       .= JsonString (prettyShow $ componentUnitId clbi)
+      , "compiler-args" .= JsonArray (map JsonString $ getCompilerArgs bi lbi clbi)
+      , "modules"       .= JsonArray (map (JsonString . display) modules)
+      , "src-files"     .= JsonArray (map JsonString sourceFiles)
+      , "src-dirs"      .= JsonArray (map JsonString $ hsSourceDirs bi)
+      ]
+      where
+        bi = componentBuildInfo comp
+        Just comp = lookupComponent pkg_descr name
+        compType = case comp of
+          CLib _   -> "lib"
+          CExe _   -> "exe"
+          CTest _  -> "test"
+          CBench _ -> "bench"
+          CFLib _  -> "flib"
+        modules = case comp of
+          CLib lib -> explicitLibModules lib
+          CExe exe -> exeModules exe
+          _        -> []
+        sourceFiles = case comp of
+          CLib _   -> []
+          CExe exe -> [modulePath exe]
+          _        -> []
+
+-- | Get the command-line arguments that would be passed
+-- to the compiler to build the given component.
+getCompilerArgs
+  :: BuildInfo
+  -> LocalBuildInfo
+  -> ComponentLocalBuildInfo
+  -> [String]
+getCompilerArgs bi lbi clbi =
+  case compilerFlavor $ compiler lbi of
+      GHC   -> ghc
+      GHCJS -> ghc
+      c     -> error $ "ShowBuildInfo.getCompilerArgs: Don't know how to get "++
+                       "build arguments for compiler "++show c
+  where
+    -- This is absolutely awful
+    ghc = GHC.renderGhcOptions (compiler lbi) (hostPlatform lbi) baseOpts
+      where
+        baseOpts = GHC.componentGhcOptions normal lbi bi clbi (buildDir lbi)
diff --git a/Cabal/Distribution/Simple/SrcDist.hs b/Cabal/Distribution/Simple/SrcDist.hs
index 0331dcd24fc7860b8209ad60cd468b81d842daa7..8e0cae09224b28beb793f86a35afc7994b316822 100644
--- a/Cabal/Distribution/Simple/SrcDist.hs
+++ b/Cabal/Distribution/Simple/SrcDist.hs
@@ -52,6 +52,7 @@ import Distribution.Package
 import Distribution.ModuleName
 import qualified Distribution.ModuleName as ModuleName
 import Distribution.Version
+import Distribution.Simple.Configure (findDistPrefOrDefault)
 import Distribution.Simple.Glob
 import Distribution.Simple.Utils
 import Distribution.Simple.Setup
@@ -78,7 +79,11 @@ sdist :: PackageDescription     -- ^information from the tarball
       -> (FilePath -> FilePath) -- ^build prefix (temp dir)
       -> [PPSuffixHandler]      -- ^ extra preprocessors (includes suffixes)
       -> IO ()
-sdist pkg mb_lbi flags mkTmpDir pps =
+sdist pkg mb_lbi flags mkTmpDir pps = do
+
+  distPref <- findDistPrefOrDefault $ sDistDistPref flags
+  let targetPref   = distPref
+      tmpTargetDir = mkTmpDir distPref
 
   -- When given --list-sources, just output the list of sources to a file.
   case (sDistListSources flags) of
@@ -123,10 +128,6 @@ sdist pkg mb_lbi flags mkTmpDir pps =
     verbosity = fromFlag (sDistVerbosity flags)
     snapshot  = fromFlag (sDistSnapshot flags)
 
-    distPref     = fromFlag $ sDistDistPref flags
-    targetPref   = distPref
-    tmpTargetDir = mkTmpDir distPref
-
 -- | List all source files of a package. Returns a tuple of lists: first
 -- component is a list of ordinary files, second one is a list of those files
 -- that may be executable.
@@ -171,14 +172,15 @@ listPackageSourcesOrdinary verbosity pkg_descr pps =
   , fmap concat
     . withAllExe $ \Executable { modulePath = mainPath, buildInfo = exeBi } -> do
        biSrcs  <- allSourcesBuildInfo verbosity exeBi pps []
-       mainSrc <- findMainExeFile exeBi pps mainPath
+       mainSrc <- findMainExeFile verbosity exeBi pps mainPath
        return (mainSrc:biSrcs)
 
     -- Foreign library sources
   , fmap concat
     . withAllFLib $ \flib@(ForeignLib { foreignLibBuildInfo = flibBi }) -> do
        biSrcs   <- allSourcesBuildInfo verbosity flibBi pps []
-       defFiles <- mapM (findModDefFile flibBi pps) (foreignLibModDefFile flib)
+       defFiles <- mapM (findModDefFile verbosity flibBi pps)
+         (foreignLibModDefFile flib)
        return (defFiles ++ biSrcs)
 
     -- Test suites sources.
@@ -188,12 +190,12 @@ listPackageSourcesOrdinary verbosity pkg_descr pps =
        case testInterface t of
          TestSuiteExeV10 _ mainPath -> do
            biSrcs <- allSourcesBuildInfo verbosity bi pps []
-           srcMainFile <- findMainExeFile bi pps mainPath
+           srcMainFile <- findMainExeFile verbosity bi pps mainPath
            return (srcMainFile:biSrcs)
          TestSuiteLibV09 _ m ->
            allSourcesBuildInfo verbosity bi pps [m]
-         TestSuiteUnsupported tp -> die' verbosity $ "Unsupported test suite type: "
-                                   ++ show tp
+         TestSuiteUnsupported tp ->
+           die' verbosity $ "Unsupported test suite type: " ++ show tp
 
     -- Benchmarks sources.
   , fmap concat
@@ -202,7 +204,7 @@ listPackageSourcesOrdinary verbosity pkg_descr pps =
        case benchmarkInterface bm of
          BenchmarkExeV10 _ mainPath -> do
            biSrcs <- allSourcesBuildInfo verbosity bi pps []
-           srcMainFile <- findMainExeFile bi pps mainPath
+           srcMainFile <- findMainExeFile verbosity bi pps mainPath
            return (srcMainFile:biSrcs)
          BenchmarkUnsupported tp -> die' verbosity $ "Unsupported benchmark type: "
                                     ++ show tp
@@ -225,12 +227,13 @@ listPackageSourcesOrdinary verbosity pkg_descr pps =
     -- License file(s).
   , return (licenseFiles pkg_descr)
 
-    -- Install-include files.
+    -- Install-include files, without autogen-include files
   , fmap concat
     . withAllLib $ \ l -> do
-       let lbi = libBuildInfo l
+       let lbi   = libBuildInfo l
+           incls = filter (`notElem` autogenIncludes lbi) (installIncludes lbi)
            relincdirs = "." : filter isRelative (includeDirs lbi)
-       traverse (fmap snd . findIncludeFile verbosity relincdirs) (installIncludes lbi)
+       traverse (fmap snd . findIncludeFile verbosity relincdirs) incls
 
     -- Setup script, if it exists.
   , fmap (maybe [] (\f -> [f])) $ findSetupFile ""
@@ -300,20 +303,22 @@ maybeCreateDefaultSetupScript targetDir = do
         "main = defaultMain"]
 
 -- | Find the main executable file.
-findMainExeFile :: BuildInfo -> [PPSuffixHandler] -> FilePath -> IO FilePath
-findMainExeFile exeBi pps mainPath = do
+findMainExeFile
+  :: Verbosity -> BuildInfo -> [PPSuffixHandler] -> FilePath -> IO FilePath
+findMainExeFile verbosity exeBi pps mainPath = do
   ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs exeBi)
             (dropExtension mainPath)
   case ppFile of
-    Nothing -> findFile (hsSourceDirs exeBi) mainPath
+    Nothing -> findFileEx verbosity (hsSourceDirs exeBi) mainPath
     Just pp -> return pp
 
 -- | Find a module definition file
 --
 -- TODO: I don't know if this is right
-findModDefFile :: BuildInfo -> [PPSuffixHandler] -> FilePath -> IO FilePath
-findModDefFile flibBi _pps modDefPath =
-    findFile (".":hsSourceDirs flibBi) modDefPath
+findModDefFile
+  :: Verbosity -> BuildInfo -> [PPSuffixHandler] -> FilePath -> IO FilePath
+findModDefFile verbosity flibBi _pps modDefPath =
+    findFileEx verbosity (".":hsSourceDirs flibBi) modDefPath
 
 -- | Given a list of include paths, try to find the include file named
 -- @f@. Return the name of the file and the full path, or exit with error if
diff --git a/Cabal/Distribution/Simple/Test/ExeV10.hs b/Cabal/Distribution/Simple/Test/ExeV10.hs
index e67c019783f7f49d386a08838ca94387334a03a3..a6861986a16658dc736b55959d2d1af2616f9b91 100644
--- a/Cabal/Distribution/Simple/Test/ExeV10.hs
+++ b/Cabal/Distribution/Simple/Test/ExeV10.hs
@@ -98,7 +98,12 @@ runTest pkg_descr lbi clbi flags suite = do
                             return (addLibraryPath os paths shellEnv)
                     else return shellEnv
 
-    exit <- rawSystemIOWithEnv verbosity cmd opts Nothing (Just shellEnv')
+    exit <- case testWrapper flags of
+      Flag path -> rawSystemIOWithEnv verbosity path (cmd:opts) Nothing (Just shellEnv')
+                               -- these handles are automatically closed
+                               Nothing (Just wOut) (Just wErr)
+
+      NoFlag -> rawSystemIOWithEnv verbosity cmd opts Nothing (Just shellEnv')
                                -- these handles are automatically closed
                                Nothing (Just wOut) (Just wErr)
 
diff --git a/Cabal/Distribution/Simple/Test/LibV09.hs b/Cabal/Distribution/Simple/Test/LibV09.hs
index c9bd24cc8a37483b26954476fd27f97b204d690a..8f4978bc8458ceb5c60579567780acd45bc8d40d 100644
--- a/Cabal/Distribution/Simple/Test/LibV09.hs
+++ b/Cabal/Distribution/Simple/Test/LibV09.hs
@@ -99,9 +99,14 @@ runTest pkg_descr lbi clbi flags suite = do
                     cpath <- canonicalizePath $ LBI.componentBuildDir lbi clbi
                     return (addLibraryPath os (cpath : paths) shellEnv)
                   else return shellEnv
-                createProcessWithEnv verbosity cmd opts Nothing (Just shellEnv')
-                                     -- these handles are closed automatically
-                                     CreatePipe (UseHandle wOut) (UseHandle wOut)
+                case testWrapper flags of
+                  Flag path -> createProcessWithEnv verbosity path (cmd:opts) Nothing (Just shellEnv')
+                               -- these handles are closed automatically
+                               CreatePipe (UseHandle wOut) (UseHandle wOut)
+
+                  NoFlag -> createProcessWithEnv verbosity cmd opts Nothing (Just shellEnv')
+                            -- these handles are closed automatically
+                            CreatePipe (UseHandle wOut) (UseHandle wOut)
 
         hPutStr wIn $ show (tempLog, PD.testName suite)
         hClose wIn
diff --git a/Cabal/Distribution/Simple/Test/Log.hs b/Cabal/Distribution/Simple/Test/Log.hs
index 359bbcedbce80450866d707a7dcefa97851b2c65..a8fa51771edee980dfa4bbc64ed06a42e247e57e 100644
--- a/Cabal/Distribution/Simple/Test/Log.hs
+++ b/Cabal/Distribution/Simple/Test/Log.hs
@@ -30,6 +30,8 @@ import Distribution.TestSuite
 import Distribution.Verbosity
 import Distribution.Pretty
 
+import qualified Prelude (foldl1)
+
 -- | Logs all test results for a package, broken down first by test suite and
 -- then by test case.
 data PackageLog = PackageLog
@@ -128,7 +130,7 @@ testSuiteLogPath template pkg_descr lbi test_name result =
 summarizePackage :: Verbosity -> PackageLog -> IO Bool
 summarizePackage verbosity packageLog = do
     let counts = map (countTestResults . testLogs) $ testSuites packageLog
-        (passed, failed, errors) = foldl1 addTriple counts
+        (passed, failed, errors) = Prelude.foldl1 addTriple counts
         totalCases = passed + failed + errors
         passedSuites = length
                        $ filter (suitePassed . testLogs)
diff --git a/Cabal/Distribution/Simple/UserHooks.hs b/Cabal/Distribution/Simple/UserHooks.hs
index 4eb239987adc18fac088bc970dd690eb7262cde3..306092186d1e7fcc9bcd94fc0906773c71f41303 100644
--- a/Cabal/Distribution/Simple/UserHooks.hs
+++ b/Cabal/Distribution/Simple/UserHooks.hs
@@ -51,8 +51,6 @@ type Args = [String]
 -- break in future releases.
 data UserHooks = UserHooks {
 
-    -- | Used for @.\/setup test@
-    runTests :: Args -> Bool -> PackageDescription -> LocalBuildInfo -> IO (),
     -- | Read the description file
     readDesc :: IO (Maybe GenericPackageDescription),
     -- | Custom preprocessors in addition to and overriding 'knownSuffixHandlers'.
@@ -107,13 +105,6 @@ data UserHooks = UserHooks {
     -- on the target, not on the build machine.
     postInst :: Args -> InstallFlags -> PackageDescription -> LocalBuildInfo -> IO (),
 
-    -- |Hook to run before sdist command.  Second arg indicates verbosity level.
-    preSDist  :: Args -> SDistFlags -> IO HookedBuildInfo,
-    -- |Over-ride this hook to get different behavior during sdist.
-    sDistHook :: PackageDescription -> Maybe LocalBuildInfo -> UserHooks -> SDistFlags -> IO (),
-    -- |Hook to run after sdist command.  Second arg indicates verbosity level.
-    postSDist :: Args -> SDistFlags -> PackageDescription -> Maybe LocalBuildInfo -> IO (),
-
     -- |Hook to run before register command
     preReg  :: Args -> RegisterFlags -> IO HookedBuildInfo,
     -- |Over-ride this hook to get different behavior during registration.
@@ -164,16 +155,10 @@ data UserHooks = UserHooks {
     postBench :: Args -> BenchmarkFlags -> PackageDescription -> LocalBuildInfo -> IO ()
   }
 
-{-# DEPRECATED runTests "Please use the new testing interface instead!" #-}
-{-# DEPRECATED preSDist  "SDist hooks violate the invariants of new-sdist. Use 'autogen-modules' and 'build-tool-depends' instead." #-}
-{-# DEPRECATED sDistHook "SDist hooks violate the invariants of new-sdist. Use 'autogen-modules' and 'build-tool-depends' instead." #-}
-{-# DEPRECATED postSDist "SDist hooks violate the invariants of new-sdist. Use 'autogen-modules' and 'build-tool-depends' instead." #-}
-
 -- |Empty 'UserHooks' which do nothing.
 emptyUserHooks :: UserHooks
 emptyUserHooks
   = UserHooks {
-      runTests  = ru,
       readDesc  = return Nothing,
       hookedPreProcessors = [],
       hookedPrograms      = [],
@@ -195,9 +180,6 @@ emptyUserHooks
       preInst   = rn,
       instHook  = ru,
       postInst  = ru,
-      preSDist  = rn,
-      sDistHook = ru,
-      postSDist = ru,
       preReg    = rn',
       regHook   = ru,
       postReg   = ru,
diff --git a/Cabal/Distribution/Simple/Utils.hs b/Cabal/Distribution/Simple/Utils.hs
index 17ed16e83fb83047da46172a12193c0f1d2dc971..8dbcf07a9085cc9586dcda83bb3f31c8e2cfb030 100644
--- a/Cabal/Distribution/Simple/Utils.hs
+++ b/Cabal/Distribution/Simple/Utils.hs
@@ -25,9 +25,6 @@ module Distribution.Simple.Utils (
         cabalVersion,
 
         -- * logging and errors
-        -- Old style
-        die, dieWithLocation,
-        -- New style
         dieNoVerbosity,
         die', dieWithLocation',
         dieNoWrap,
@@ -55,7 +52,6 @@ module Distribution.Simple.Utils (
         createProcessWithEnv,
         maybeExit,
         xargs,
-        findProgramLocation,
         findProgramVersion,
 
         -- ** 'IOData' re-export
@@ -67,10 +63,8 @@ module Distribution.Simple.Utils (
         IODataMode(..),
 
         -- * copying files
-        smartCopySources,
         createDirectoryIfMissingVerbose,
         copyFileVerbose,
-        copyDirectoryRecursiveVerbose,
         copyFiles,
         copyFileTo,
 
@@ -96,13 +90,13 @@ module Distribution.Simple.Utils (
         exeExtensions,
 
         -- * finding files
-        findFile,
+        findFileEx,
         findFirstFile,
         findFileWithExtension,
         findFileWithExtension',
         findAllFilesWithExtension,
-        findModuleFile,
-        findModuleFiles,
+        findModuleFileEx,
+        findModuleFilesEx,
         getDirectoryContentsRecursive,
 
         -- * environment variables
@@ -123,13 +117,11 @@ module Distribution.Simple.Utils (
         defaultPackageDesc,
         findPackageDesc,
         tryFindPackageDesc,
-        defaultHookedPackageDesc,
         findHookedPackageDesc,
 
         -- * reading and writing files safely
         withFileContents,
         writeFileAtomic,
-        rewriteFile,
         rewriteFileEx,
 
         -- * Unicode
@@ -166,6 +158,11 @@ module Distribution.Simple.Utils (
         -- * FilePath stuff
         isAbsoluteOnAnyPlatform,
         isRelativeOnAnyPlatform,
+
+        -- * Deprecated functions
+        findFile,
+        findModuleFile,
+        findModuleFiles,
   ) where
 
 import Prelude ()
@@ -209,7 +206,7 @@ import qualified Data.ByteString.Lazy as BS
 
 import System.Directory
     ( Permissions(executable), getDirectoryContents, getPermissions
-    , doesDirectoryExist, doesFileExist, removeFile, findExecutable
+    , doesDirectoryExist, doesFileExist, removeFile
     , getModificationTime, createDirectory, removeDirectoryRecursive )
 import System.Environment
     ( getProgName )
@@ -302,21 +299,6 @@ cabalVersion = mkVersion [1,9999]  --used when bootstrapping
 --    'ioeSetVerbatim' and 'ioeGetVerbatim'.
 --
 
-{-# DEPRECATED dieWithLocation "Messages thrown with dieWithLocation can't be controlled with Verbosity; use dieWithLocation' instead" #-}
-dieWithLocation :: FilePath -> Maybe Int -> String -> IO a
-dieWithLocation filename lineno msg =
-  ioError . setLocation lineno
-          . flip ioeSetFileName (normalise filename)
-          $ userError msg
-  where
-    setLocation Nothing  err = err
-    setLocation (Just n) err = ioeSetLocation err (show n)
-    _ = callStack -- TODO: Attach CallStack to exception
-
-{-# DEPRECATED die "Messages thrown with die can't be controlled with Verbosity; use die' instead, or dieNoVerbosity if Verbosity truly is not available" #-}
-die :: String -> IO a
-die = dieNoVerbosity
-
 dieNoVerbosity :: String -> IO a
 dieNoVerbosity msg
     = ioError (userError msg)
@@ -815,7 +797,7 @@ rawSystemStdout verbosity path args = withFrozenCallStack $ do
                                                   Nothing Nothing
                                                   Nothing IODataModeText
   when (exitCode /= ExitSuccess) $
-    die errors
+    die' verbosity errors
   return output
 
 -- | Run a command and return its output, errors and exit status. Optionally
@@ -893,20 +875,6 @@ rawSystemStdInOut verbosity path args mcwd menv input outputMode = withFrozenCal
       either (\e -> throwIO (ioeSetFileName e ("output of " ++ path)))
              return
 
-
-{-# DEPRECATED findProgramLocation
-    "No longer used within Cabal, try findProgramOnSearchPath" #-}
--- | Look for a program on the path.
-findProgramLocation :: Verbosity -> FilePath -> IO (Maybe FilePath)
-findProgramLocation verbosity prog = withFrozenCallStack $ do
-  debug verbosity $ "searching for " ++ prog ++ " in path."
-  res <- findExecutable prog
-  case res of
-      Nothing   -> debug verbosity ("Cannot find " ++ prog ++ " on the path")
-      Just path -> debug verbosity ("found " ++ prog ++ " at "++ path)
-  return res
-
-
 -- | Look for a program and try to find it's version number. It can accept
 -- either an absolute path or the name of a program binary, in which case we
 -- will look for the program on the path.
@@ -962,16 +930,24 @@ xargs maxSize rawSystemFun fixedArgs bigArgs =
 ----------------
 -- Finding files
 
--- | Find a file by looking in a search path. The file path must match exactly.
---
+
+{-# DEPRECATED findFile "Use findFileEx instead. This symbol will be removed in Cabal 3.2 (est. December 2019)" #-}
 findFile :: [FilePath]    -- ^search locations
          -> FilePath      -- ^File Name
          -> IO FilePath
-findFile searchPath fileName =
+findFile = findFileEx normal
+
+-- | Find a file by looking in a search path. The file path must match exactly.
+--
+findFileEx :: Verbosity
+           -> [FilePath]    -- ^search locations
+           -> FilePath      -- ^File Name
+           -> IO FilePath
+findFileEx verbosity searchPath fileName =
   findFirstFile id
     [ path </> fileName
     | path <- nub searchPath]
-  >>= maybe (die $ fileName ++ " doesn't exist") return
+  >>= maybe (die' verbosity $ fileName ++ " doesn't exist") return
 
 -- | Find a file by looking in a search path with one of a list of possible
 -- file extensions. The file base name should be given and it will be tried
@@ -1021,34 +997,52 @@ findFirstFile file = findFirst
 findAllFiles :: (a -> FilePath) -> [a] -> NoCallStackIO [a]
 findAllFiles file = filterM (doesFileExist . file)
 
--- | Finds the files corresponding to a list of Haskell module names.
---
--- As 'findModuleFile' but for a list of module names.
---
+
+{-# DEPRECATED findModuleFiles "Use findModuleFilesEx instead. This symbol will be removed in Cabal 3.2 (est. December 2019)" #-}
 findModuleFiles :: [FilePath]   -- ^ build prefix (location of objects)
                 -> [String]     -- ^ search suffixes
                 -> [ModuleName] -- ^ modules
                 -> IO [(FilePath, FilePath)]
-findModuleFiles searchPath extensions moduleNames =
-  traverse (findModuleFile searchPath extensions) moduleNames
+findModuleFiles = findModuleFilesEx normal
 
--- | Find the file corresponding to a Haskell module name.
+-- | Finds the files corresponding to a list of Haskell module names.
 --
--- This is similar to 'findFileWithExtension'' but specialised to a module
--- name. The function fails if the file corresponding to the module is missing.
+-- As 'findModuleFile' but for a list of module names.
 --
+findModuleFilesEx :: Verbosity
+                  -> [FilePath]   -- ^ build prefix (location of objects)
+                  -> [String]     -- ^ search suffixes
+                  -> [ModuleName] -- ^ modules
+                  -> IO [(FilePath, FilePath)]
+findModuleFilesEx verbosity searchPath extensions moduleNames =
+  traverse (findModuleFileEx verbosity searchPath extensions) moduleNames
+
+{-# DEPRECATED findModuleFile "Use findModuleFileEx instead. This symbol will be removed in Cabal 3.2 (est. December 2019)" #-}
 findModuleFile :: [FilePath]  -- ^ build prefix (location of objects)
                -> [String]    -- ^ search suffixes
                -> ModuleName  -- ^ module
                -> IO (FilePath, FilePath)
-findModuleFile searchPath extensions mod_name =
+findModuleFile = findModuleFileEx normal
+
+-- | Find the file corresponding to a Haskell module name.
+--
+-- This is similar to 'findFileWithExtension'' but specialised to a module
+-- name. The function fails if the file corresponding to the module is missing.
+--
+findModuleFileEx :: Verbosity
+                 -> [FilePath]  -- ^ build prefix (location of objects)
+                 -> [String]    -- ^ search suffixes
+                 -> ModuleName  -- ^ module
+                 -> IO (FilePath, FilePath)
+findModuleFileEx verbosity searchPath extensions mod_name =
       maybe notFound return
   =<< findFileWithExtension' extensions searchPath
                              (ModuleName.toFilePath mod_name)
   where
-    notFound = die $ "Error: Could not find module: " ++ prettyShow mod_name
-                  ++ " with any suffix: " ++ show extensions
-                  ++ " in the search path: " ++ show searchPath
+    notFound = die' verbosity $
+      "Error: Could not find module: " ++ prettyShow mod_name
+      ++ " with any suffix: "          ++ show extensions
+      ++ " in the search path: "       ++ show searchPath
 
 -- | List all the files in a directory and all subdirectories.
 --
@@ -1312,25 +1306,6 @@ doesExecutableExist f = do
             return (executable perms)
     else return False
 
----------------------------------
--- Deprecated file copy functions
-
-{-# DEPRECATED smartCopySources
-      "Use findModuleFiles and copyFiles or installOrdinaryFiles" #-}
-smartCopySources :: Verbosity -> [FilePath] -> FilePath
-                 -> [ModuleName] -> [String] -> IO ()
-smartCopySources verbosity searchPath targetDir moduleNames extensions = withFrozenCallStack $
-      findModuleFiles searchPath extensions moduleNames
-  >>= copyFiles verbosity targetDir
-
-{-# DEPRECATED copyDirectoryRecursiveVerbose
-      "You probably want installDirectoryContents instead" #-}
-copyDirectoryRecursiveVerbose :: Verbosity -> FilePath -> FilePath -> IO ()
-copyDirectoryRecursiveVerbose verbosity srcDir destDir = withFrozenCallStack $ do
-  info verbosity ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.")
-  srcFiles <- getDirectoryContentsRecursive srcDir
-  copyFiles verbosity destDir [ (srcDir, f) | f <- srcFiles ]
-
 ---------------------------
 -- Temporary files and dirs
 
@@ -1393,10 +1368,6 @@ withTempDirectoryEx _verbosity opts targetDir template f = withFrozenCallStack $
 -----------------------------------
 -- Safely reading and writing files
 
-{-# DEPRECATED rewriteFile "Use rewriteFileEx so that Verbosity is respected" #-}
-rewriteFile :: FilePath -> String -> IO ()
-rewriteFile = rewriteFileEx normal
-
 -- | Write a file but only if it would have new content. If we would be writing
 -- the same as the existing content then leave the file as is so that we do not
 -- update the file's modification time.
@@ -1458,9 +1429,9 @@ exeExtensions = case buildOS of
 -- * Finding the description file
 -- ------------------------------------------------------------
 
--- |Package description file (/pkgname/@.cabal@)
+-- | Package description file (/pkgname/@.cabal@)
 defaultPackageDesc :: Verbosity -> IO FilePath
-defaultPackageDesc _verbosity = tryFindPackageDesc currentDir
+defaultPackageDesc verbosity = tryFindPackageDesc verbosity currentDir
 
 -- |Find a package description file in the given directory.  Looks for
 -- @.cabal@ files.
@@ -1491,20 +1462,17 @@ findPackageDesc dir
                   ++ intercalate ", " l
 
 -- |Like 'findPackageDesc', but calls 'die' in case of error.
-tryFindPackageDesc :: FilePath -> IO FilePath
-tryFindPackageDesc dir = either die return =<< findPackageDesc dir
-
-{-# DEPRECATED defaultHookedPackageDesc "Use findHookedPackageDesc with the proper base directory instead" #-}
--- |Optional auxiliary package information file (/pkgname/@.buildinfo@)
-defaultHookedPackageDesc :: IO (Maybe FilePath)
-defaultHookedPackageDesc = findHookedPackageDesc currentDir
+tryFindPackageDesc :: Verbosity -> FilePath -> IO FilePath
+tryFindPackageDesc verbosity dir =
+  either (die' verbosity) return =<< findPackageDesc dir
 
 -- |Find auxiliary package information in the given directory.
 -- Looks for @.buildinfo@ files.
 findHookedPackageDesc
-    :: FilePath                 -- ^Directory to search
+    :: Verbosity
+    -> FilePath                 -- ^Directory to search
     -> IO (Maybe FilePath)      -- ^/dir/@\/@/pkgname/@.buildinfo@, if present
-findHookedPackageDesc dir = do
+findHookedPackageDesc verbosity dir = do
     files <- getDirectoryContents dir
     buildInfoFiles <- filterM doesFileExist
                         [ dir </> file
@@ -1512,9 +1480,9 @@ findHookedPackageDesc dir = do
                         , let (name, ext) = splitExtension file
                         , not (null name) && ext == buildInfoExt ]
     case buildInfoFiles of
-        [] -> return Nothing
+        []  -> return Nothing
         [f] -> return (Just f)
-        _ -> die ("Multiple files with extension " ++ buildInfoExt)
+        _   -> die' verbosity ("Multiple files with extension " ++ buildInfoExt)
 
 buildInfoExt  :: String
 buildInfoExt = ".buildinfo"
diff --git a/Cabal/Distribution/Simple/Utils/Json.hs b/Cabal/Distribution/Simple/Utils/Json.hs
new file mode 100644
index 0000000000000000000000000000000000000000..f90f2f38aa2c4b6cf569b832baf5f121b05d529c
--- /dev/null
+++ b/Cabal/Distribution/Simple/Utils/Json.hs
@@ -0,0 +1,46 @@
+-- | Utility json lib for Cabal
+-- TODO: Remove it again.
+module Distribution.Simple.Utils.Json
+    ( Json(..)
+    , renderJson
+    ) where
+
+data Json = JsonArray [Json]
+          | JsonBool !Bool
+          | JsonNull
+          | JsonNumber !Int
+          | JsonObject [(String, Json)]
+          | JsonString !String
+
+renderJson :: Json -> ShowS
+renderJson (JsonArray objs)   =
+  surround "[" "]" $ intercalate "," $ map renderJson objs
+renderJson (JsonBool True)    = showString "true"
+renderJson (JsonBool False)   = showString "false"
+renderJson  JsonNull          = showString "null"
+renderJson (JsonNumber n)     = shows n
+renderJson (JsonObject attrs) =
+  surround "{" "}" $ intercalate "," $ map render attrs
+  where
+    render (k,v) = (surround "\"" "\"" $ showString' k) . showString ":" . renderJson v
+renderJson (JsonString s)     = surround "\"" "\"" $ showString' s
+
+surround :: String -> String -> ShowS -> ShowS
+surround begin end middle = showString begin . middle . showString end
+
+showString' :: String -> ShowS
+showString' xs = showStringWorker xs
+    where
+        showStringWorker :: String -> ShowS
+        showStringWorker ('\"':as) = showString "\\\"" . showStringWorker as
+        showStringWorker ('\\':as) = showString "\\\\" . showStringWorker as
+        showStringWorker ('\'':as) = showString "\\\'" . showStringWorker as
+        showStringWorker (x:as) = showString [x] . showStringWorker as
+        showStringWorker [] = showString ""
+
+intercalate :: String -> [ShowS] -> ShowS
+intercalate sep = go
+  where
+    go []     = id
+    go [x]    = x
+    go (x:xs) = x . showString' sep . go xs
diff --git a/Cabal/Distribution/Text.hs b/Cabal/Distribution/Text.hs
index 41ce60b1d7667d54d40323daa043640b788423ac..258b4dc835fb43ac7588dc527889d8cb3c2d9aad 100644
--- a/Cabal/Distribution/Text.hs
+++ b/Cabal/Distribution/Text.hs
@@ -1,5 +1,5 @@
 -- Since @3.0@ this is a compat module.
-module Distribution.Text where
+module Distribution.Text (display, simpleParse) where
 {- {-# DEPRECATED "Use Distribution.Parsec or Distribution.Pretty" #-} -}
 
 import Distribution.Pretty
diff --git a/Cabal/Distribution/Types/BuildInfo.hs b/Cabal/Distribution/Types/BuildInfo.hs
index 1fc7357969679ad0d9f8684b517c7be673b676f5..06b69bf4db4e1a16f06ca48cf39a96d8ae9b4bea 100644
--- a/Cabal/Distribution/Types/BuildInfo.hs
+++ b/Cabal/Distribution/Types/BuildInfo.hs
@@ -94,6 +94,7 @@ data BuildInfo = BuildInfo {
         extraLibDirs      :: [String],
         includeDirs       :: [FilePath], -- ^directories to find .h files
         includes          :: [FilePath], -- ^ The .h files to be found in includeDirs
+        autogenIncludes   :: [FilePath], -- ^ The .h files to be generated (e.g. by @autoconf@)
         installIncludes   :: [FilePath], -- ^ .h files to install with the package
         options           :: PerCompilerFlavor [String],
         profOptions       :: PerCompilerFlavor [String],
@@ -147,6 +148,7 @@ instance Monoid BuildInfo where
     extraLibDirs        = [],
     includeDirs         = [],
     includes            = [],
+    autogenIncludes     = [],
     installIncludes     = [],
     options             = mempty,
     profOptions         = mempty,
@@ -194,6 +196,7 @@ instance Semigroup BuildInfo where
     extraLibDirs        = combineNub extraLibDirs,
     includeDirs         = combineNub includeDirs,
     includes            = combineNub includes,
+    autogenIncludes     = combineNub autogenIncludes,
     installIncludes     = combineNub installIncludes,
     options             = combine    options,
     profOptions         = combine    profOptions,
diff --git a/Cabal/Distribution/Types/BuildInfo/Lens.hs b/Cabal/Distribution/Types/BuildInfo/Lens.hs
index c656e644f2e6700f5387f93345872679656254d3..8754893f976775f89e7fc68a695fa078d339cd0d 100644
--- a/Cabal/Distribution/Types/BuildInfo/Lens.hs
+++ b/Cabal/Distribution/Types/BuildInfo/Lens.hs
@@ -160,6 +160,10 @@ class HasBuildInfo a where
    includes = buildInfo . includes
    {-# INLINE includes #-}
 
+   autogenIncludes :: Lens' a [FilePath]
+   autogenIncludes = buildInfo . autogenIncludes
+   {-# INLINE autogenIncludes #-}
+
    installIncludes :: Lens' a [FilePath]
    installIncludes = buildInfo . installIncludes
    {-# INLINE installIncludes #-}
@@ -299,6 +303,9 @@ instance HasBuildInfo BuildInfo where
     includes f s = fmap (\x -> s { T.includes = x }) (f (T.includes s))
     {-# INLINE includes #-}
 
+    autogenIncludes f s = fmap (\x -> s { T.autogenIncludes = x }) (f (T.autogenIncludes s))
+    {-# INLINE autogenIncludes #-}
+
     installIncludes f s = fmap (\x -> s { T.installIncludes = x }) (f (T.installIncludes s))
     {-# INLINE installIncludes #-}
 
diff --git a/Cabal/Distribution/Types/InstalledPackageInfo.hs b/Cabal/Distribution/Types/InstalledPackageInfo.hs
index ab896c5502d0b874fd615b5d767e98c8787f0861..0d6fb56b5ac08fa21286ae67beffa3dead8f7bc8 100644
--- a/Cabal/Distribution/Types/InstalledPackageInfo.hs
+++ b/Cabal/Distribution/Types/InstalledPackageInfo.hs
@@ -41,6 +41,7 @@ data InstalledPackageInfo
         sourcePackageId   :: PackageId,
         sourceLibName     :: LibraryName,
         installedComponentId_ :: ComponentId,
+        libVisibility     :: LibraryVisibility,
         installedUnitId   :: UnitId,
         -- INVARIANT: if this package is definite, OpenModule's
         -- OpenUnitId directly records UnitId.  If it is
@@ -87,8 +88,7 @@ data InstalledPackageInfo
         frameworks        :: [String],
         haddockInterfaces :: [FilePath],
         haddockHTMLs      :: [FilePath],
-        pkgRoot           :: Maybe FilePath,
-        libVisibility     :: LibraryVisibility
+        pkgRoot           :: Maybe FilePath
     }
     deriving (Eq, Generic, Typeable, Read, Show)
 
diff --git a/Cabal/Distribution/Types/InstalledPackageInfo/FieldGrammar.hs b/Cabal/Distribution/Types/InstalledPackageInfo/FieldGrammar.hs
index e629f97308504325ee3aa819db2d48f5c35cdf76..7ee9f27803509ba414c9ee870c8ad2faa89326a1 100644
--- a/Cabal/Distribution/Types/InstalledPackageInfo/FieldGrammar.hs
+++ b/Cabal/Distribution/Types/InstalledPackageInfo/FieldGrammar.hs
@@ -60,7 +60,7 @@ ipiFieldGrammar = mkInstalledPackageInfo
     <$> monoidalFieldAla    "hugs-options"         (alaList' FSep Token)         unitedList
         --- https://github.com/haskell/cabal/commit/40f3601e17024f07e0da8e64d3dd390177ce908b
         ^^^ deprecatedSince CabalSpecV1_22 "hugs isn't supported anymore"
-    -- Very basic fields: name, version, package-name and lib-name
+    -- Very basic fields: name, version, package-name, lib-name and visibility
     <+> blurFieldGrammar basic basicFieldGrammar
     -- Basic fields
     <+> optionalFieldDef    "id"                                                 L.installedUnitId (mkUnitId "")
@@ -102,7 +102,6 @@ ipiFieldGrammar = mkInstalledPackageInfo
     <+> monoidalFieldAla    "haddock-interfaces"   (alaList' FSep FilePathNT)    L.haddockInterfaces
     <+> monoidalFieldAla    "haddock-html"         (alaList' FSep FilePathNT)    L.haddockHTMLs
     <+> optionalFieldAla    "pkgroot"              FilePathNT                    L.pkgRoot
-    <+> optionalFieldDef    "visibility"                                         L.libVisibility LibraryVisibilityPrivate
   where
     mkInstalledPackageInfo _ Basic {..} = InstalledPackageInfo
         -- _basicPkgName is not used
@@ -110,6 +109,7 @@ ipiFieldGrammar = mkInstalledPackageInfo
         (PackageIdentifier pn _basicVersion)
         (combineLibraryName ln _basicLibName)
         (mkComponentId "") -- installedComponentId_, not in use
+        _basicLibVisibility
       where
         MungedPackageName pn ln = _basicName
 {-# SPECIALIZE ipiFieldGrammar :: FieldDescrs InstalledPackageInfo InstalledPackageInfo #-}
@@ -172,9 +172,7 @@ maybePackageName ipi = case sourceLibName ipi of
 
 newtype ExposedModules = ExposedModules { getExposedModules :: [ExposedModule] }
 
-instance Newtype ExposedModules [ExposedModule] where
-    pack   = ExposedModules
-    unpack = getExposedModules
+instance Newtype [ExposedModule] ExposedModules
 
 instance Parsec ExposedModules where
     parsec = ExposedModules <$> parsecOptCommaList parsec
@@ -185,9 +183,7 @@ instance Pretty ExposedModules where
 
 newtype CompatPackageKey = CompatPackageKey { getCompatPackageKey :: String }
 
-instance Newtype CompatPackageKey String where
-    pack = CompatPackageKey
-    unpack = getCompatPackageKey
+instance Newtype String CompatPackageKey
 
 instance Pretty CompatPackageKey where
     pretty = Disp.text . getCompatPackageKey
@@ -199,9 +195,7 @@ instance Parsec CompatPackageKey where
 
 newtype InstWith = InstWith { getInstWith :: [(ModuleName,OpenModule)] }
 
-instance Newtype InstWith [(ModuleName, OpenModule)] where
-    pack = InstWith
-    unpack = getInstWith
+instance Newtype  [(ModuleName, OpenModule)] InstWith
 
 instance Pretty InstWith where
     pretty = dispOpenModuleSubst . Map.fromList . getInstWith
@@ -213,15 +207,13 @@ instance Parsec InstWith where
 -- | SPDX License expression or legacy license. Lenient parser, accepts either.
 newtype SpecLicenseLenient = SpecLicenseLenient { getSpecLicenseLenient :: Either SPDX.License License }
 
-instance Newtype SpecLicenseLenient (Either SPDX.License License) where
-    pack = SpecLicenseLenient
-    unpack = getSpecLicenseLenient
+instance Newtype (Either SPDX.License License) SpecLicenseLenient
 
 instance Parsec SpecLicenseLenient where
     parsec = fmap SpecLicenseLenient $ Left <$> P.try parsec <|> Right <$> parsec
 
 instance Pretty SpecLicenseLenient where
-    pretty = either pretty pretty . unpack
+    pretty = either pretty pretty . getSpecLicenseLenient
 
 -------------------------------------------------------------------------------
 -- Basic fields
@@ -231,10 +223,11 @@ instance Pretty SpecLicenseLenient where
 -- in serialised textual representation
 -- to the actual 'InstalledPackageInfo' fields.
 data Basic = Basic
-    { _basicName    :: MungedPackageName
-    , _basicVersion :: Version
-    , _basicPkgName :: Maybe PackageName
-    , _basicLibName :: LibraryName
+    { _basicName          :: MungedPackageName
+    , _basicVersion       :: Version
+    , _basicPkgName       :: Maybe PackageName
+    , _basicLibName       :: LibraryName
+    , _basicLibVisibility :: LibraryVisibility
     }
 
 basic :: Lens' InstalledPackageInfo Basic
@@ -245,12 +238,14 @@ basic f ipi = g <$> f b
         (packageVersion ipi)
         (maybePackageName ipi)
         (sourceLibName ipi)
+        (libVisibility ipi)
 
-    g (Basic n v pn ln) = ipi
+    g (Basic n v pn ln lv) = ipi
         & setMungedPackageName n
         & L.sourcePackageId . L.pkgVersion .~ v
         & setMaybePackageName pn
         & L.sourceLibName .~ ln
+        & L.libVisibility .~ lv
 
 basicName :: Lens' Basic MungedPackageName
 basicName f b = (\x -> b { _basicName = x }) <$> f (_basicName b)
@@ -269,6 +264,11 @@ basicLibName f b = (\x -> b { _basicLibName = maybeToLibraryName x }) <$>
     f (libraryNameString (_basicLibName b))
 {-# INLINE basicLibName #-}
 
+basicLibVisibility :: Lens' Basic LibraryVisibility
+basicLibVisibility f b = (\x -> b { _basicLibVisibility = x }) <$>
+    f (_basicLibVisibility b)
+{-# INLINE basicLibVisibility #-}
+
 basicFieldGrammar
     :: (FieldGrammar g, Applicative (g Basic))
     => g Basic Basic
@@ -277,5 +277,21 @@ basicFieldGrammar = mkBasic
     <*> optionalFieldDefAla "version"       MQuoted  basicVersion nullVersion
     <*> optionalField       "package-name"           basicPkgName
     <*> optionalField       "lib-name"               basicLibName
+    <+> optionalFieldDef    "visibility"             basicLibVisibility LibraryVisibilityPrivate
   where
-    mkBasic n v pn ln = Basic n v pn (maybe LMainLibName LSubLibName ln)
+    mkBasic n v pn ln lv = Basic n v pn ln' lv'
+      where
+        ln' = maybe LMainLibName LSubLibName ln
+        -- Older GHCs (<8.8) always report installed libraries as private
+        -- because their ghc-pkg builds with an older Cabal.
+        -- So we always set LibraryVisibilityPublic for main (unnamed) libs.
+        -- This can be removed once we stop supporting GHC<8.8, at the
+        -- condition that we keep marking main libraries as public when
+        -- registering them.
+        lv' = if
+                let MungedPackageName _ mln = n in
+                -- We need to check both because on ghc<8.2 ln' will always
+                -- be LMainLibName
+                ln' == LMainLibName && mln == LMainLibName
+              then LibraryVisibilityPublic
+              else lv
diff --git a/Cabal/Distribution/Types/Library.hs b/Cabal/Distribution/Types/Library.hs
index b7ff72456f4a90d1d69331ee2b6819d782f2370e..26e9bfb324a54f8c60e0fb1296719d6966d59b08 100644
--- a/Cabal/Distribution/Types/Library.hs
+++ b/Cabal/Distribution/Types/Library.hs
@@ -6,7 +6,6 @@ module Distribution.Types.Library (
     emptyLibrary,
     explicitLibModules,
     libModulesAutogen,
-    libModules,
 ) where
 
 import Distribution.Compat.Prelude
@@ -88,16 +87,6 @@ explicitLibModules lib = exposedModules lib
 libModulesAutogen :: Library -> [ModuleName]
 libModulesAutogen lib = autogenModules (libBuildInfo lib)
 
--- | Backwards-compatibility shim for 'explicitLibModules'.  In most cases,
--- you actually want 'allLibModules', which returns all modules that will
--- actually be compiled, as opposed to those which are explicitly listed
--- in the package description ('explicitLibModules'); unfortunately, the
--- type signature for 'allLibModules' is incompatible since we need a
--- 'ComponentLocalBuildInfo'.
-{-# DEPRECATED libModules "If you want all modules that are built with a library, use 'allLibModules'.  Otherwise, use 'explicitLibModules' for ONLY the modules explicitly mentioned in the package description. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-libModules :: Library -> [ModuleName]
-libModules = explicitLibModules
-
 -- | Combine 'LibraryName'. in parsing we prefer value coming
 -- from munged @name@ field over the @lib-name@.
 --
diff --git a/Cabal/Distribution/Types/LocalBuildInfo.hs b/Cabal/Distribution/Types/LocalBuildInfo.hs
index 90bbf6dfef6d765a5d568837d83b41607ae1bcd5..31ad96ef89adc86695bb7879117bdd8e2c0cf420 100644
--- a/Cabal/Distribution/Types/LocalBuildInfo.hs
+++ b/Cabal/Distribution/Types/LocalBuildInfo.hs
@@ -46,11 +46,6 @@ module Distribution.Types.LocalBuildInfo (
     withAllTargetsInBuildOrder,
     neededTargetsInBuildOrder,
     withNeededTargetsInBuildOrder,
-
-    -- * Backwards compatibility.
-
-    componentsConfigs,
-    externalPackageDeps,
   ) where
 
 import Prelude ()
@@ -60,7 +55,6 @@ import Distribution.Types.PackageDescription
 import Distribution.Types.ComponentLocalBuildInfo
 import Distribution.Types.ComponentRequestedSpec
 import Distribution.Types.ComponentId
-import Distribution.Types.MungedPackageId
 import Distribution.Types.PackageId
 import Distribution.Types.UnitId
 import Distribution.Types.TargetInfo
@@ -306,32 +300,3 @@ neededTargetsInBuildOrder lbi = neededTargetsInBuildOrder' (localPkgDescr lbi) l
 
 withNeededTargetsInBuildOrder :: LocalBuildInfo -> [UnitId] -> (TargetInfo -> IO ()) -> IO ()
 withNeededTargetsInBuildOrder lbi = withNeededTargetsInBuildOrder' (localPkgDescr lbi) lbi
-
--------------------------------------------------------------------------------
--- Backwards compatibility
-
-{-# DEPRECATED componentsConfigs "Use 'componentGraph' instead; you can get a list of 'ComponentLocalBuildInfo' with 'Distribution.Compat.Graph.toList'. There's not a good way to get the list of 'ComponentName's the 'ComponentLocalBuildInfo' depends on because this query doesn't make sense; the graph is indexed by 'UnitId' not 'ComponentName'.  Given a 'UnitId' you can lookup the 'ComponentLocalBuildInfo' ('getCLBI') and then get the 'ComponentName' ('componentLocalName]). To be removed in Cabal 3.0" #-}
-componentsConfigs :: LocalBuildInfo -> [(ComponentName, ComponentLocalBuildInfo, [ComponentName])]
-componentsConfigs lbi =
-    [ (componentLocalName clbi,
-       clbi,
-       mapMaybe (fmap componentLocalName . flip Graph.lookup g)
-                (componentInternalDeps clbi))
-    | clbi <- Graph.toList g ]
-  where
-    g = componentGraph lbi
-
--- | External package dependencies for the package as a whole. This is the
--- union of the individual 'componentPackageDeps', less any internal deps.
-{-# DEPRECATED externalPackageDeps "You almost certainly don't want this function, which agglomerates the dependencies of ALL enabled components.  If you're using this to write out information on your dependencies, read off the dependencies directly from the actual component in question.  To be removed in Cabal 3.0" #-}
-externalPackageDeps :: LocalBuildInfo -> [(UnitId, MungedPackageId)]
-externalPackageDeps lbi =
-    -- TODO:  what about non-buildable components?
-    nub [ (ipkgid, pkgid)
-        | clbi            <- Graph.toList (componentGraph lbi)
-        , (ipkgid, pkgid) <- componentPackageDeps clbi
-        , not (internal ipkgid) ]
-  where
-    -- True if this dependency is an internal one (depends on the library
-    -- defined in the same package).
-    internal ipkgid = any ((==ipkgid) . componentUnitId) (Graph.toList (componentGraph lbi))
diff --git a/Cabal/Distribution/Types/PackageDescription.hs b/Cabal/Distribution/Types/PackageDescription.hs
index ea648a57a11a4e4fb9636d489e9c967ada3f42ea..10110fa66673e5bc6dc7cc7fe39fba988bab5da9 100644
--- a/Cabal/Distribution/Types/PackageDescription.hs
+++ b/Cabal/Distribution/Types/PackageDescription.hs
@@ -32,7 +32,6 @@ module Distribution.Types.PackageDescription (
     specVersion',
     license,
     license',
-    descCabalVersion,
     buildType,
     emptyPackageDescription,
     hasPublicLib,
@@ -190,18 +189,6 @@ license = license' . licenseRaw
 license' :: Either SPDX.License License -> SPDX.License
 license' = either id licenseToSPDX
 
--- | The range of versions of the Cabal tools that this package is intended to
--- work with.
---
--- This function is deprecated and should not be used for new purposes, only to
--- support old packages that rely on the old interpretation.
---
-descCabalVersion :: PackageDescription -> VersionRange
-descCabalVersion pkg = case specVersionRaw pkg of
-  Left  version      -> orLaterVersion version
-  Right versionRange -> versionRange
-{-# DEPRECATED descCabalVersion "Use specVersion instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-
 -- | The effective @build-type@ after applying defaulting rules.
 --
 -- The original @build-type@ value parsed is stored in the
diff --git a/Cabal/Distribution/Types/PkgconfigVersionRange.hs b/Cabal/Distribution/Types/PkgconfigVersionRange.hs
index 69c29ca2cd9f9d58bd8ab32cc5801e7b4501cae3..6b1bc94939d1d4ec93532c3817ab9177d95ed5cb 100644
--- a/Cabal/Distribution/Types/PkgconfigVersionRange.hs
+++ b/Cabal/Distribution/Types/PkgconfigVersionRange.hs
@@ -75,11 +75,11 @@ pkgconfigParser :: CabalParsing m => m PkgconfigVersionRange
 pkgconfigParser = P.spaces >> expr where
     -- every parser here eats trailing space
     expr = do
-        ts <- term `P.sepBy` (P.string "||" >> P.spaces)
+        ts <- term `P.sepByNonEmpty` (P.string "||" >> P.spaces)
         return $ foldr1 PcUnionVersionRanges ts
 
     term = do
-        fs <- factor `P.sepBy` (P.string "&&" >> P.spaces)
+        fs <- factor `P.sepByNonEmpty` (P.string "&&" >> P.spaces)
         return $ foldr1 PcIntersectVersionRanges fs
 
     factor = parens expr <|> prim
diff --git a/Cabal/Distribution/Types/UnitId.hs b/Cabal/Distribution/Types/UnitId.hs
index c040c15599dc8aa16ed3b659619aa0c9f5c4b112..464089d7b3cfb3369ae0a2fc254b6a9bf08d27f9 100644
--- a/Cabal/Distribution/Types/UnitId.hs
+++ b/Cabal/Distribution/Types/UnitId.hs
@@ -11,7 +11,6 @@ module Distribution.Types.UnitId
   , newSimpleUnitId
   , mkLegacyUnitId
   , getHSLibraryName
-  , InstalledPackageId -- backwards compat
   ) where
 
 import Prelude ()
@@ -66,9 +65,6 @@ import Text.PrettyPrint (text)
 newtype UnitId = UnitId ShortText
   deriving (Generic, Read, Show, Eq, Ord, Typeable, Data, NFData)
 
-{-# DEPRECATED InstalledPackageId "Use UnitId instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-type InstalledPackageId = UnitId
-
 instance Binary UnitId
 
 -- | The textual format for 'UnitId' coincides with the format
diff --git a/Cabal/Distribution/Types/Version.hs b/Cabal/Distribution/Types/Version.hs
index 03da7f18f1de9dad58280dc1d046c47bc71ab4a7..0a0cd3effd4816dadcad58cc9e27f5da08d9d7f1 100644
--- a/Cabal/Distribution/Types/Version.hs
+++ b/Cabal/Distribution/Types/Version.hs
@@ -10,9 +10,6 @@ module Distribution.Types.Version (
     alterVersion,
     version0,
 
-    -- ** Backwards compatibility
-    showVersion,
-
     -- * Internal
     validVersion,
     versionDigitParser,
@@ -236,7 +233,3 @@ alterVersion f = mkVersion . f . versionNumbers
 -- internal helper
 validVersion :: Version -> Bool
 validVersion v = v /= nullVersion && all (>=0) (versionNumbers v)
-
-showVersion :: Version -> String
-showVersion = prettyShow
-{-# DEPRECATED showVersion "Use prettyShow. This function will be removed in Cabal-3.0 (estimated Mar 2019)" #-}
diff --git a/Cabal/Distribution/Types/VersionInterval.hs b/Cabal/Distribution/Types/VersionInterval.hs
index 7b2843a31b5e517a87540e70fa0d7e1b750d8ab1..3304258bbe8dbbfecd7bc6c53e639090e75c4ef9 100644
--- a/Cabal/Distribution/Types/VersionInterval.hs
+++ b/Cabal/Distribution/Types/VersionInterval.hs
@@ -28,6 +28,9 @@ import Control.Exception (assert)
 import Distribution.Types.Version
 import Distribution.Types.VersionRange
 
+-- NonEmpty
+import qualified Prelude (foldr1)
+
 -------------------------------------------------------------------------------
 -- VersionRange
 -------------------------------------------------------------------------------
@@ -214,7 +217,7 @@ toVersionIntervals = foldVersionRange
 fromVersionIntervals :: VersionIntervals -> VersionRange
 fromVersionIntervals (VersionIntervals []) = noVersion
 fromVersionIntervals (VersionIntervals intervals) =
-    foldr1 unionVersionRanges [ interval l u | (l, u) <- intervals ]
+    Prelude.foldr1 unionVersionRanges [ interval l u | (l, u) <- intervals ]
 
   where
     interval (LowerBound v  InclusiveBound)
diff --git a/Cabal/Distribution/Types/VersionRange.hs b/Cabal/Distribution/Types/VersionRange.hs
index 23e1a7bdcbdb4a08e5830a5d50229d8618238bd8..c95bc5b25668f0df32c42c01611b03e5841ca532 100644
--- a/Cabal/Distribution/Types/VersionRange.hs
+++ b/Cabal/Distribution/Types/VersionRange.hs
@@ -1,13 +1,6 @@
-{-# LANGUAGE DeriveDataTypeable  #-}
-{-# LANGUAGE DeriveFoldable      #-}
-{-# LANGUAGE DeriveFunctor       #-}
-{-# LANGUAGE DeriveGeneric       #-}
-{-# LANGUAGE DeriveTraversable   #-}
-{-# LANGUAGE FlexibleContexts    #-}
-{-# LANGUAGE ScopedTypeVariables #-}
 module Distribution.Types.VersionRange (
     -- * Version ranges
-    VersionRange(..),
+    VersionRange,
 
     -- ** Constructing
     anyVersion, noVersion,
@@ -45,208 +38,9 @@ module Distribution.Types.VersionRange (
 
 import Distribution.Compat.Prelude
 import Distribution.Types.Version
+import Distribution.Types.VersionRange.Internal
 import Prelude ()
 
-import Distribution.CabalSpecVersion
-import Distribution.Parsec
-import Distribution.Pretty
-import Text.PrettyPrint              ((<+>))
-
-import qualified Distribution.Compat.CharParsing as P
-import qualified Distribution.Compat.DList       as DList
-import qualified Text.PrettyPrint                as Disp
-
-data VersionRange
-  = AnyVersion
-  | ThisVersion            Version -- = version
-  | LaterVersion           Version -- > version  (NB. not >=)
-  | OrLaterVersion         Version -- >= version
-  | EarlierVersion         Version -- < version
-  | OrEarlierVersion       Version -- <= version
-  | WildcardVersion        Version -- == ver.*   (same as >= ver && < ver+1)
-  | MajorBoundVersion      Version -- @^>= ver@ (same as >= ver && < MAJ(ver)+1)
-  | UnionVersionRanges     VersionRange VersionRange
-  | IntersectVersionRanges VersionRange VersionRange
-  | VersionRangeParens     VersionRange -- just '(exp)' parentheses syntax
-  deriving (Data, Eq, Generic, Read, Show, Typeable)
-
-instance Binary VersionRange
-
-instance NFData VersionRange where rnf = genericRnf
-
-{-# DeprecateD AnyVersion
-    "Use 'anyVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
-{-# DEPRECATED ThisVersion
-    "Use 'thisVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
-{-# DEPRECATED LaterVersion
-    "Use 'laterVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
-{-# DEPRECATED EarlierVersion
-    "Use 'earlierVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
-{-# DEPRECATED WildcardVersion
-    "Use 'anyVersion', 'foldVersionRange' or 'asVersionIntervals'" #-}
-{-# DEPRECATED UnionVersionRanges
-    "Use 'unionVersionRanges', 'foldVersionRange' or 'asVersionIntervals'" #-}
-{-# DEPRECATED IntersectVersionRanges
-    "Use 'intersectVersionRanges', 'foldVersionRange' or 'asVersionIntervals'"#-}
-
--- | The version range @-any@. That is, a version range containing all
--- versions.
---
--- > withinRange v anyVersion = True
---
-anyVersion :: VersionRange
-anyVersion = AnyVersion
-
--- | The empty version range, that is a version range containing no versions.
---
--- This can be constructed using any unsatisfiable version range expression,
--- for example @> 1 && < 1@.
---
--- > withinRange v noVersion = False
---
-noVersion :: VersionRange
-noVersion = IntersectVersionRanges (LaterVersion v) (EarlierVersion v)
-  where v = mkVersion [1]
-
--- | The version range @== v@
---
--- > withinRange v' (thisVersion v) = v' == v
---
-thisVersion :: Version -> VersionRange
-thisVersion = ThisVersion
-
--- | The version range @< v || > v@
---
--- > withinRange v' (notThisVersion v) = v' /= v
---
-notThisVersion :: Version -> VersionRange
-notThisVersion v = UnionVersionRanges (EarlierVersion v) (LaterVersion v)
-
--- | The version range @> v@
---
--- > withinRange v' (laterVersion v) = v' > v
---
-laterVersion :: Version -> VersionRange
-laterVersion = LaterVersion
-
--- | The version range @>= v@
---
--- > withinRange v' (orLaterVersion v) = v' >= v
---
-orLaterVersion :: Version -> VersionRange
-orLaterVersion = OrLaterVersion
-
--- | The version range @< v@
---
--- > withinRange v' (earlierVersion v) = v' < v
---
-earlierVersion :: Version -> VersionRange
-earlierVersion = EarlierVersion
-
--- | The version range @<= v@
---
--- > withinRange v' (orEarlierVersion v) = v' <= v
---
-orEarlierVersion :: Version -> VersionRange
-orEarlierVersion = OrEarlierVersion
-
--- | The version range @vr1 || vr2@
---
--- >   withinRange v' (unionVersionRanges vr1 vr2)
--- > = withinRange v' vr1 || withinRange v' vr2
---
-unionVersionRanges :: VersionRange -> VersionRange -> VersionRange
-unionVersionRanges = UnionVersionRanges
-
--- | The version range @vr1 && vr2@
---
--- >   withinRange v' (intersectVersionRanges vr1 vr2)
--- > = withinRange v' vr1 && withinRange v' vr2
---
-intersectVersionRanges :: VersionRange -> VersionRange -> VersionRange
-intersectVersionRanges = IntersectVersionRanges
-
--- | The version range @== v.*@.
---
--- For example, for version @1.2@, the version range @== 1.2.*@ is the same as
--- @>= 1.2 && < 1.3@
---
--- > withinRange v' (laterVersion v) = v' >= v && v' < upper v
--- >   where
--- >     upper (Version lower t) = Version (init lower ++ [last lower + 1]) t
---
-withinVersion :: Version -> VersionRange
-withinVersion = WildcardVersion
-
--- | The version range @^>= v@.
---
--- For example, for version @1.2.3.4@, the version range @^>= 1.2.3.4@ is the same as
--- @>= 1.2.3.4 && < 1.3@.
---
--- Note that @^>= 1@ is equivalent to @>= 1 && < 1.1@.
---
--- @since 2.0.0.2
-majorBoundVersion :: Version -> VersionRange
-majorBoundVersion = MajorBoundVersion
-
--- | F-Algebra of 'VersionRange'. See 'cataVersionRange'.
---
--- @since 2.2
-data VersionRangeF a
-  = AnyVersionF
-  | ThisVersionF            Version -- = version
-  | LaterVersionF           Version -- > version  (NB. not >=)
-  | OrLaterVersionF         Version -- >= version
-  | EarlierVersionF         Version -- < version
-  | OrEarlierVersionF       Version -- <= version
-  | WildcardVersionF        Version -- == ver.*   (same as >= ver && < ver+1)
-  | MajorBoundVersionF      Version -- @^>= ver@ (same as >= ver && < MAJ(ver)+1)
-  | UnionVersionRangesF     a a
-  | IntersectVersionRangesF a a
-  | VersionRangeParensF     a
-  deriving (Data, Eq, Generic, Read, Show, Typeable, Functor, Foldable, Traversable)
-
--- | @since 2.2
-projectVersionRange :: VersionRange -> VersionRangeF VersionRange
-projectVersionRange AnyVersion                   = AnyVersionF
-projectVersionRange (ThisVersion v)              = ThisVersionF v
-projectVersionRange (LaterVersion v)             = LaterVersionF v
-projectVersionRange (OrLaterVersion v)           = OrLaterVersionF v
-projectVersionRange (EarlierVersion v)           = EarlierVersionF v
-projectVersionRange (OrEarlierVersion v)         = OrEarlierVersionF v
-projectVersionRange (WildcardVersion v)          = WildcardVersionF v
-projectVersionRange (MajorBoundVersion v)        = MajorBoundVersionF v
-projectVersionRange (UnionVersionRanges a b)     = UnionVersionRangesF a b
-projectVersionRange (IntersectVersionRanges a b) = IntersectVersionRangesF a b
-projectVersionRange (VersionRangeParens a)       = VersionRangeParensF a
-
--- | Fold 'VersionRange'.
---
--- @since 2.2
-cataVersionRange :: (VersionRangeF a -> a) -> VersionRange -> a
-cataVersionRange f = c where c = f . fmap c . projectVersionRange
-
--- | @since 2.2
-embedVersionRange :: VersionRangeF VersionRange -> VersionRange
-embedVersionRange AnyVersionF                   = AnyVersion
-embedVersionRange (ThisVersionF v)              = ThisVersion v
-embedVersionRange (LaterVersionF v)             = LaterVersion v
-embedVersionRange (OrLaterVersionF v)           = OrLaterVersion v
-embedVersionRange (EarlierVersionF v)           = EarlierVersion v
-embedVersionRange (OrEarlierVersionF v)         = OrEarlierVersion v
-embedVersionRange (WildcardVersionF v)          = WildcardVersion v
-embedVersionRange (MajorBoundVersionF v)        = MajorBoundVersion v
-embedVersionRange (UnionVersionRangesF a b)     = UnionVersionRanges a b
-embedVersionRange (IntersectVersionRangesF a b) = IntersectVersionRanges a b
-embedVersionRange (VersionRangeParensF a)       = VersionRangeParens a
-
--- | Unfold 'VersionRange'.
---
--- @since 2.2
-anaVersionRange :: (a -> VersionRangeF a) -> a -> VersionRange
-anaVersionRange g = a where a = embedVersionRange . fmap a . g
-
-
 -- | Fold over the basic syntactic structure of a 'VersionRange'.
 --
 -- This provides a syntactic view of the expression defining the version range.
@@ -286,14 +80,6 @@ foldVersionRange anyv this later earlier union intersect = fold
                      (orLaterVersion v)
                      (earlierVersion (majorUpperBound v))
 
--- | Refold 'VersionRange'
---
--- @since 2.2
-hyloVersionRange :: (VersionRangeF VersionRange -> VersionRange)
-                 -> (VersionRange -> VersionRangeF VersionRange)
-                 -> VersionRange -> VersionRange
-hyloVersionRange f g = h where h = f . fmap h . g
-
 -- | Normalise 'VersionRange'.
 --
 -- In particular collapse @(== v || > v)@ into @>= v@, and so on.
@@ -352,200 +138,6 @@ isWildcardRange ver1 ver2 = check (versionNumbers ver1) (versionNumbers ver2)
         check (n:ns) (m:ms) | n   == m = check ns ms
         check _      _                 = False
 
--- | Compute next greater major version to be used as upper bound
---
--- Example: @0.4.1@ produces the version @0.5@ which then can be used
--- to construct a range @>= 0.4.1 && < 0.5@
---
--- @since 2.2
-majorUpperBound :: Version -> Version
-majorUpperBound = alterVersion $ \numbers -> case numbers of
-    []        -> [0,1] -- should not happen
-    [m1]      -> [m1,1] -- e.g. version '1'
-    (m1:m2:_) -> [m1,m2+1]
-
--------------------------------------------------------------------------------
--- Parsec & Pretty
--------------------------------------------------------------------------------
-
-instance Pretty VersionRange where
-    pretty = fst . cataVersionRange alg
-      where
-        alg AnyVersionF                     = (Disp.text "-any", 0 :: Int)
-        alg (ThisVersionF v)                = (Disp.text "==" <<>> pretty v, 0)
-        alg (LaterVersionF v)               = (Disp.char '>'  <<>> pretty v, 0)
-        alg (OrLaterVersionF v)             = (Disp.text ">=" <<>> pretty v, 0)
-        alg (EarlierVersionF v)             = (Disp.char '<'  <<>> pretty v, 0)
-        alg (OrEarlierVersionF v)           = (Disp.text "<=" <<>> pretty v, 0)
-        alg (WildcardVersionF v)            = (Disp.text "==" <<>> dispWild v, 0)
-        alg (MajorBoundVersionF v)          = (Disp.text "^>=" <<>> pretty v, 0)
-        alg (UnionVersionRangesF (r1, p1) (r2, p2)) =
-            (punct 1 p1 r1 <+> Disp.text "||" <+> punct 2 p2 r2 , 2)
-        alg (IntersectVersionRangesF (r1, p1) (r2, p2)) =
-            (punct 0 p1 r1 <+> Disp.text "&&" <+> punct 1 p2 r2 , 1)
-        alg (VersionRangeParensF (r, _))         =
-            (Disp.parens r, 0)
-
-        dispWild ver =
-            Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int $ versionNumbers ver))
-            <<>> Disp.text ".*"
-
-        punct p p' | p < p'    = Disp.parens
-                   | otherwise = id
-
-instance Parsec VersionRange where
-    parsec = versionRangeParser versionDigitParser
-
--- | 'VersionRange' parser parametrised by version digit parser
---
--- - 'versionDigitParser' is used for all 'VersionRange'
--- - 'P.integral' is used for backward-compat @pkgconfig-depends@ versions, 'PkgConfigVersionRange'.
---
--- @since 3.0
-versionRangeParser :: forall m. CabalParsing m => m Int -> m VersionRange
-versionRangeParser digitParser = expr
-      where
-        expr   = do P.spaces
-                    t <- term
-                    P.spaces
-                    (do _  <- P.string "||"
-                        P.spaces
-                        e <- expr
-                        return (unionVersionRanges t e)
-                     <|>
-                     return t)
-        term   = do f <- factor
-                    P.spaces
-                    (do _  <- P.string "&&"
-                        P.spaces
-                        t <- term
-                        return (intersectVersionRanges f t)
-                     <|>
-                     return f)
-        factor = parens expr <|> prim
-
-        prim = do
-            op <- P.munch1 (`elem` "<>=^-") P.<?> "operator"
-            case op of
-                "-" -> anyVersion <$ P.string "any" <|> P.string "none" *> noVersion'
-
-                "==" -> do
-                    P.spaces
-                    (do (wild, v) <- verOrWild
-                        pure $ (if wild then withinVersion else thisVersion) v
-                     <|>
-                     (verSet' thisVersion =<< verSet))
-
-                "^>=" -> do
-                    P.spaces
-                    (do (wild, v) <- verOrWild
-                        when wild $ P.unexpected $
-                            "wild-card version after ^>= operator"
-                        majorBoundVersion' v
-                     <|>
-                     (verSet' majorBoundVersion =<< verSet))
-
-                _ -> do
-                    P.spaces
-                    (wild, v) <- verOrWild
-                    when wild $ P.unexpected $
-                        "wild-card version after non-== operator: " ++ show op
-                    case op of
-                        ">="  -> pure $ orLaterVersion v
-                        "<"   -> pure $ earlierVersion v
-                        "<="  -> pure $ orEarlierVersion v
-                        ">"   -> pure $ laterVersion v
-                        _ -> fail $ "Unknown version operator " ++ show op
-
-        -- Note: There are other features:
-        -- && and || since 1.8
-        -- x.y.* (wildcard) since 1.6
-
-        -- -none version range is available since 1.22
-        noVersion' = do
-            csv <- askCabalSpecVersion
-            if csv >= CabalSpecV1_22
-            then pure noVersion
-            else fail $ unwords
-                [ "-none version range used."
-                , "To use this syntax the package needs to specify at least 'cabal-version: 1.22'."
-                , "Alternatively, if broader compatibility is important then use"
-                , "<0 or other empty range."
-                ]
-
-        -- ^>= is available since 2.0
-        majorBoundVersion' v = do
-            csv <- askCabalSpecVersion
-            if csv >= CabalSpecV2_0
-            then pure $ majorBoundVersion v
-            else fail $ unwords
-                [ "major bounded version syntax (caret, ^>=) used."
-                , "To use this syntax the package need to specify at least 'cabal-version: 2.0'."
-                , "Alternatively, if broader compatibility is important then use:"
-                , prettyShow $ eliminateMajorBoundSyntax $ majorBoundVersion v
-                ]
-          where
-            eliminateMajorBoundSyntax = hyloVersionRange embed projectVersionRange
-            embed (MajorBoundVersionF u) = intersectVersionRanges
-                (orLaterVersion u) (earlierVersion (majorUpperBound u))
-            embed vr = embedVersionRange vr
-
-        -- version set notation (e.g. "== { 0.0.1.0, 0.0.2.0, 0.1.0.0 }")
-        verSet' op vs = do
-            csv <- askCabalSpecVersion
-            if csv >= CabalSpecV3_0
-            then pure $ foldr1 unionVersionRanges (map op vs)
-            else fail $ unwords
-                [ "version set syntax used."
-                , "To use this syntax the package needs to specify at least 'cabal-version: 3.0'."
-                , "Alternatively, if broader compatibility is important then use"
-                , "a series of single version constraints joined with the || operator:"
-                , prettyShow (foldr1 unionVersionRanges (map op vs))
-                ]
-
-        verSet :: CabalParsing m => m [Version]
-        verSet = do
-            _ <- P.char '{'
-            P.spaces
-            vs <- P.sepBy1 (verPlain <* P.spaces) (P.char ',' *> P.spaces)
-            _ <- P.char '}'
-            pure vs
-
-        -- a plain version without tags or wildcards
-        verPlain :: CabalParsing m => m Version
-        verPlain = mkVersion <$> P.sepBy1 digitParser (P.char '.')
-
-        -- either wildcard or normal version
-        verOrWild :: CabalParsing m => m (Bool, Version)
-        verOrWild = do
-            x <- digitParser
-            verLoop (DList.singleton x)
-
-        -- trailing: wildcard (.y.*) or normal version (optional tags) (.y.z-tag)
-        verLoop :: CabalParsing m => DList.DList Int -> m (Bool, Version)
-        verLoop acc = verLoop' acc <|> (tags *> pure (False, mkVersion (DList.toList acc)))
-
-        verLoop' :: CabalParsing m => DList.DList Int -> m (Bool, Version)
-        verLoop' acc = do
-            _ <- P.char '.'
-            let digit = digitParser >>= verLoop . DList.snoc acc
-            let wild  = (True, mkVersion (DList.toList acc)) <$ P.char '*'
-            digit <|> wild
-
-        parens p = P.between
-            ((P.char '(' P.<?> "opening paren") >> P.spaces)
-            (P.char ')' >> P.spaces)
-            (do a <- p
-                P.spaces
-                return (VersionRangeParens a))
-
-        tags :: CabalParsing m => m ()
-        tags = do
-            ts <- many $ P.char '-' *> some (P.satisfy isAlphaNum)
-            case ts of
-                []      -> pure ()
-                (_ : _) -> parsecWarning PWTVersionTag "version with tags"
-
 -- | Does the version range have an upper bound?
 --
 -- @since 1.24.0.0
diff --git a/Cabal/Distribution/Types/VersionRange/Internal.hs b/Cabal/Distribution/Types/VersionRange/Internal.hs
new file mode 100644
index 0000000000000000000000000000000000000000..5a54faaebfffbb117c506358d507eb577c00769e
--- /dev/null
+++ b/Cabal/Distribution/Types/VersionRange/Internal.hs
@@ -0,0 +1,433 @@
+{-# LANGUAGE DeriveDataTypeable  #-}
+{-# LANGUAGE DeriveFoldable      #-}
+{-# LANGUAGE DeriveFunctor       #-}
+{-# LANGUAGE DeriveGeneric       #-}
+{-# LANGUAGE DeriveTraversable   #-}
+{-# LANGUAGE FlexibleContexts    #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+-- | The only purpose of this module is to prevent the export of
+-- 'VersionRange' constructors from
+-- 'Distribution.Types.VersionRange'. To avoid creating orphan
+-- instances, a lot of related code had to be moved here too.
+
+module Distribution.Types.VersionRange.Internal
+  ( VersionRange(..)
+  , anyVersion, noVersion
+  , thisVersion, notThisVersion
+  , laterVersion, earlierVersion
+  , orLaterVersion, orEarlierVersion
+  , unionVersionRanges, intersectVersionRanges
+  , withinVersion
+  , majorBoundVersion
+
+  , VersionRangeF(..)
+  , projectVersionRange
+  , embedVersionRange
+  , cataVersionRange
+  , anaVersionRange
+  , hyloVersionRange
+  , versionRangeParser
+
+  , majorUpperBound
+  ) where
+
+import Distribution.Compat.Prelude
+import Distribution.Types.Version
+import Prelude ()
+
+import Distribution.CabalSpecVersion
+import Distribution.Parsec
+import Distribution.Pretty
+import Text.PrettyPrint              ((<+>))
+
+import qualified Distribution.Compat.CharParsing as P
+import qualified Distribution.Compat.DList       as DList
+import qualified Text.PrettyPrint                as Disp
+
+data VersionRange
+  = AnyVersion
+  | ThisVersion            Version -- = version
+  | LaterVersion           Version -- > version  (NB. not >=)
+  | OrLaterVersion         Version -- >= version
+  | EarlierVersion         Version -- < version
+  | OrEarlierVersion       Version -- <= version
+  | WildcardVersion        Version -- == ver.*   (same as >= ver && < ver+1)
+  | MajorBoundVersion      Version -- @^>= ver@ (same as >= ver && < MAJ(ver)+1)
+  | UnionVersionRanges     VersionRange VersionRange
+  | IntersectVersionRanges VersionRange VersionRange
+  | VersionRangeParens     VersionRange -- just '(exp)' parentheses syntax
+  deriving ( Data, Eq, Generic, Read, Show, Typeable )
+
+instance Binary VersionRange
+
+instance NFData VersionRange where rnf = genericRnf
+
+-- | The version range @-any@. That is, a version range containing all
+-- versions.
+--
+-- > withinRange v anyVersion = True
+--
+anyVersion :: VersionRange
+anyVersion = AnyVersion
+
+-- | The empty version range, that is a version range containing no versions.
+--
+-- This can be constructed using any unsatisfiable version range expression,
+-- for example @> 1 && < 1@.
+--
+-- > withinRange v noVersion = False
+--
+noVersion :: VersionRange
+noVersion = IntersectVersionRanges (LaterVersion v) (EarlierVersion v)
+  where v = mkVersion [1]
+
+-- | The version range @== v@
+--
+-- > withinRange v' (thisVersion v) = v' == v
+--
+thisVersion :: Version -> VersionRange
+thisVersion = ThisVersion
+
+-- | The version range @< v || > v@
+--
+-- > withinRange v' (notThisVersion v) = v' /= v
+--
+notThisVersion :: Version -> VersionRange
+notThisVersion v = UnionVersionRanges (EarlierVersion v) (LaterVersion v)
+
+-- | The version range @> v@
+--
+-- > withinRange v' (laterVersion v) = v' > v
+--
+laterVersion :: Version -> VersionRange
+laterVersion = LaterVersion
+
+-- | The version range @>= v@
+--
+-- > withinRange v' (orLaterVersion v) = v' >= v
+--
+orLaterVersion :: Version -> VersionRange
+orLaterVersion = OrLaterVersion
+
+-- | The version range @< v@
+--
+-- > withinRange v' (earlierVersion v) = v' < v
+--
+earlierVersion :: Version -> VersionRange
+earlierVersion = EarlierVersion
+
+-- | The version range @<= v@
+--
+-- > withinRange v' (orEarlierVersion v) = v' <= v
+--
+orEarlierVersion :: Version -> VersionRange
+orEarlierVersion = OrEarlierVersion
+
+-- | The version range @vr1 || vr2@
+--
+-- >   withinRange v' (unionVersionRanges vr1 vr2)
+-- > = withinRange v' vr1 || withinRange v' vr2
+--
+unionVersionRanges :: VersionRange -> VersionRange -> VersionRange
+unionVersionRanges = UnionVersionRanges
+
+-- | The version range @vr1 && vr2@
+--
+-- >   withinRange v' (intersectVersionRanges vr1 vr2)
+-- > = withinRange v' vr1 && withinRange v' vr2
+--
+intersectVersionRanges :: VersionRange -> VersionRange -> VersionRange
+intersectVersionRanges = IntersectVersionRanges
+
+-- | The version range @== v.*@.
+--
+-- For example, for version @1.2@, the version range @== 1.2.*@ is the same as
+-- @>= 1.2 && < 1.3@
+--
+-- > withinRange v' (laterVersion v) = v' >= v && v' < upper v
+-- >   where
+-- >     upper (Version lower t) = Version (init lower ++ [last lower + 1]) t
+--
+withinVersion :: Version -> VersionRange
+withinVersion = WildcardVersion
+
+-- | The version range @^>= v@.
+--
+-- For example, for version @1.2.3.4@, the version range @^>= 1.2.3.4@
+-- is the same as @>= 1.2.3.4 && < 1.3@.
+--
+-- Note that @^>= 1@ is equivalent to @>= 1 && < 1.1@.
+--
+-- @since 2.0.0.2
+majorBoundVersion :: Version -> VersionRange
+majorBoundVersion = MajorBoundVersion
+
+
+-- | F-Algebra of 'VersionRange'. See 'cataVersionRange'.
+--
+-- @since 2.2
+data VersionRangeF a
+  = AnyVersionF
+  | ThisVersionF            Version -- = version
+  | LaterVersionF           Version -- > version  (NB. not >=)
+  | OrLaterVersionF         Version -- >= version
+  | EarlierVersionF         Version -- < version
+  | OrEarlierVersionF       Version -- <= version
+  | WildcardVersionF        Version -- == ver.*   (same as >= ver && < ver+1)
+  | MajorBoundVersionF      Version -- @^>= ver@ (same as >= ver && < MAJ(ver)+1)
+  | UnionVersionRangesF     a a
+  | IntersectVersionRangesF a a
+  | VersionRangeParensF     a
+  deriving ( Data, Eq, Generic, Read, Show, Typeable
+           , Functor, Foldable, Traversable )
+
+-- | @since 2.2
+projectVersionRange :: VersionRange -> VersionRangeF VersionRange
+projectVersionRange AnyVersion                   = AnyVersionF
+projectVersionRange (ThisVersion v)              = ThisVersionF v
+projectVersionRange (LaterVersion v)             = LaterVersionF v
+projectVersionRange (OrLaterVersion v)           = OrLaterVersionF v
+projectVersionRange (EarlierVersion v)           = EarlierVersionF v
+projectVersionRange (OrEarlierVersion v)         = OrEarlierVersionF v
+projectVersionRange (WildcardVersion v)          = WildcardVersionF v
+projectVersionRange (MajorBoundVersion v)        = MajorBoundVersionF v
+projectVersionRange (UnionVersionRanges a b)     = UnionVersionRangesF a b
+projectVersionRange (IntersectVersionRanges a b) = IntersectVersionRangesF a b
+projectVersionRange (VersionRangeParens a)       = VersionRangeParensF a
+
+-- | Fold 'VersionRange'.
+--
+-- @since 2.2
+cataVersionRange :: (VersionRangeF a -> a) -> VersionRange -> a
+cataVersionRange f = c where c = f . fmap c . projectVersionRange
+
+-- | @since 2.2
+embedVersionRange :: VersionRangeF VersionRange -> VersionRange
+embedVersionRange AnyVersionF                   = AnyVersion
+embedVersionRange (ThisVersionF v)              = ThisVersion v
+embedVersionRange (LaterVersionF v)             = LaterVersion v
+embedVersionRange (OrLaterVersionF v)           = OrLaterVersion v
+embedVersionRange (EarlierVersionF v)           = EarlierVersion v
+embedVersionRange (OrEarlierVersionF v)         = OrEarlierVersion v
+embedVersionRange (WildcardVersionF v)          = WildcardVersion v
+embedVersionRange (MajorBoundVersionF v)        = MajorBoundVersion v
+embedVersionRange (UnionVersionRangesF a b)     = UnionVersionRanges a b
+embedVersionRange (IntersectVersionRangesF a b) = IntersectVersionRanges a b
+embedVersionRange (VersionRangeParensF a)       = VersionRangeParens a
+
+-- | Unfold 'VersionRange'.
+--
+-- @since 2.2
+anaVersionRange :: (a -> VersionRangeF a) -> a -> VersionRange
+anaVersionRange g = a where a = embedVersionRange . fmap a . g
+
+-- | Refold 'VersionRange'
+--
+-- @since 2.2
+hyloVersionRange :: (VersionRangeF VersionRange -> VersionRange)
+                 -> (VersionRange -> VersionRangeF VersionRange)
+                 -> VersionRange -> VersionRange
+hyloVersionRange f g = h where h = f . fmap h . g
+
+-------------------------------------------------------------------------------
+-- Parsec & Pretty
+-------------------------------------------------------------------------------
+
+instance Pretty VersionRange where
+    pretty = fst . cataVersionRange alg
+      where
+        alg AnyVersionF                     = (Disp.text "-any", 0 :: Int)
+        alg (ThisVersionF v)                = (Disp.text "==" <<>> pretty v, 0)
+        alg (LaterVersionF v)               = (Disp.char '>'  <<>> pretty v, 0)
+        alg (OrLaterVersionF v)             = (Disp.text ">=" <<>> pretty v, 0)
+        alg (EarlierVersionF v)             = (Disp.char '<'  <<>> pretty v, 0)
+        alg (OrEarlierVersionF v)           = (Disp.text "<=" <<>> pretty v, 0)
+        alg (WildcardVersionF v)            = (Disp.text "==" <<>> dispWild v, 0)
+        alg (MajorBoundVersionF v)          = (Disp.text "^>=" <<>> pretty v, 0)
+        alg (UnionVersionRangesF (r1, p1) (r2, p2)) =
+            (punct 1 p1 r1 <+> Disp.text "||" <+> punct 2 p2 r2 , 2)
+        alg (IntersectVersionRangesF (r1, p1) (r2, p2)) =
+            (punct 0 p1 r1 <+> Disp.text "&&" <+> punct 1 p2 r2 , 1)
+        alg (VersionRangeParensF (r, _))         =
+            (Disp.parens r, 0)
+
+        dispWild ver =
+            Disp.hcat (Disp.punctuate (Disp.char '.')
+                        (map Disp.int $ versionNumbers ver))
+            <<>> Disp.text ".*"
+
+        punct p p' | p < p'    = Disp.parens
+                   | otherwise = id
+
+instance Parsec VersionRange where
+    parsec = versionRangeParser versionDigitParser
+
+-- | 'VersionRange' parser parametrised by version digit parser
+--
+-- - 'versionDigitParser' is used for all 'VersionRange'.
+-- - 'P.integral' is used for backward-compat @pkgconfig-depends@
+--   versions, 'PkgConfigVersionRange'.
+--
+-- @since 3.0
+versionRangeParser :: forall m. CabalParsing m => m Int -> m VersionRange
+versionRangeParser digitParser = expr
+      where
+        expr   = do P.spaces
+                    t <- term
+                    P.spaces
+                    (do _  <- P.string "||"
+                        P.spaces
+                        e <- expr
+                        return (unionVersionRanges t e)
+                     <|>
+                     return t)
+        term   = do f <- factor
+                    P.spaces
+                    (do _  <- P.string "&&"
+                        P.spaces
+                        t <- term
+                        return (intersectVersionRanges f t)
+                     <|>
+                     return f)
+        factor = parens expr <|> prim
+
+        prim = do
+            op <- P.munch1 (`elem` "<>=^-") P.<?> "operator"
+            case op of
+                "-" -> anyVersion <$ P.string "any" <|> P.string "none" *> noVersion'
+
+                "==" -> do
+                    P.spaces
+                    (do (wild, v) <- verOrWild
+                        pure $ (if wild then withinVersion else thisVersion) v
+                     <|>
+                     (verSet' thisVersion =<< verSet))
+
+                "^>=" -> do
+                    P.spaces
+                    (do (wild, v) <- verOrWild
+                        when wild $ P.unexpected $
+                            "wild-card version after ^>= operator"
+                        majorBoundVersion' v
+                     <|>
+                     (verSet' majorBoundVersion =<< verSet))
+
+                _ -> do
+                    P.spaces
+                    (wild, v) <- verOrWild
+                    when wild $ P.unexpected $
+                        "wild-card version after non-== operator: " ++ show op
+                    case op of
+                        ">="  -> pure $ orLaterVersion v
+                        "<"   -> pure $ earlierVersion v
+                        "<="  -> pure $ orEarlierVersion v
+                        ">"   -> pure $ laterVersion v
+                        _ -> fail $ "Unknown version operator " ++ show op
+
+        -- Note: There are other features:
+        -- && and || since 1.8
+        -- x.y.* (wildcard) since 1.6
+
+        -- -none version range is available since 1.22
+        noVersion' = do
+            csv <- askCabalSpecVersion
+            if csv >= CabalSpecV1_22
+            then pure noVersion
+            else fail $ unwords
+                [ "-none version range used."
+                , "To use this syntax the package needs to specify at least 'cabal-version: 1.22'."
+                , "Alternatively, if broader compatibility is important then use"
+                , "<0 or other empty range."
+                ]
+
+        -- ^>= is available since 2.0
+        majorBoundVersion' v = do
+            csv <- askCabalSpecVersion
+            if csv >= CabalSpecV2_0
+            then pure $ majorBoundVersion v
+            else fail $ unwords
+                [ "major bounded version syntax (caret, ^>=) used."
+                , "To use this syntax the package need to specify at least 'cabal-version: 2.0'."
+                , "Alternatively, if broader compatibility is important then use:"
+                , prettyShow $ eliminateMajorBoundSyntax $ majorBoundVersion v
+                ]
+          where
+            eliminateMajorBoundSyntax = hyloVersionRange embed projectVersionRange
+            embed (MajorBoundVersionF u) = intersectVersionRanges
+                (orLaterVersion u) (earlierVersion (majorUpperBound u))
+            embed vr = embedVersionRange vr
+
+        -- version set notation (e.g. "== { 0.0.1.0, 0.0.2.0, 0.1.0.0 }")
+        verSet' op vs = do
+            csv <- askCabalSpecVersion
+            if csv >= CabalSpecV3_0
+            then pure $ foldr1 unionVersionRanges (fmap op vs)
+            else fail $ unwords
+                [ "version set syntax used."
+                , "To use this syntax the package needs to specify at least 'cabal-version: 3.0'."
+                , "Alternatively, if broader compatibility is important then use"
+                , "a series of single version constraints joined with the || operator:"
+                , prettyShow (foldr1 unionVersionRanges (fmap op vs))
+                ]
+
+        verSet :: CabalParsing m => m (NonEmpty Version)
+        verSet = do
+            _ <- P.char '{'
+            P.spaces
+            vs <- P.sepByNonEmpty (verPlain <* P.spaces) (P.char ',' *> P.spaces)
+            _ <- P.char '}'
+            pure vs
+
+        -- a plain version without tags or wildcards
+        verPlain :: CabalParsing m => m Version
+        verPlain = mkVersion <$> P.sepBy1 digitParser (P.char '.')
+
+        -- either wildcard or normal version
+        verOrWild :: CabalParsing m => m (Bool, Version)
+        verOrWild = do
+            x <- digitParser
+            verLoop (DList.singleton x)
+
+        -- trailing: wildcard (.y.*) or normal version (optional tags) (.y.z-tag)
+        verLoop :: CabalParsing m => DList.DList Int -> m (Bool, Version)
+        verLoop acc = verLoop' acc
+                  <|> (tags *> pure (False, mkVersion (DList.toList acc)))
+
+        verLoop' :: CabalParsing m => DList.DList Int -> m (Bool, Version)
+        verLoop' acc = do
+            _ <- P.char '.'
+            let digit = digitParser >>= verLoop . DList.snoc acc
+            let wild  = (True, mkVersion (DList.toList acc)) <$ P.char '*'
+            digit <|> wild
+
+        parens p = P.between
+            ((P.char '(' P.<?> "opening paren") >> P.spaces)
+            (P.char ')' >> P.spaces)
+            (do a <- p
+                P.spaces
+                return (VersionRangeParens a))
+
+        tags :: CabalParsing m => m ()
+        tags = do
+            ts <- many $ P.char '-' *> some (P.satisfy isAlphaNum)
+            case ts of
+                []      -> pure ()
+                (_ : _) -> parsecWarning PWTVersionTag "version with tags"
+
+
+----------------------------
+-- Wildcard range utilities
+--
+
+-- | Compute next greater major version to be used as upper bound
+--
+-- Example: @0.4.1@ produces the version @0.5@ which then can be used
+-- to construct a range @>= 0.4.1 && < 0.5@
+--
+-- @since 2.2
+majorUpperBound :: Version -> Version
+majorUpperBound = alterVersion $ \numbers -> case numbers of
+    []        -> [0,1] -- should not happen
+    [m1]      -> [m1,1] -- e.g. version '1'
+    (m1:m2:_) -> [m1,m2+1]
diff --git a/Cabal/Distribution/Utils/NubList.hs b/Cabal/Distribution/Utils/NubList.hs
index 739239a826bd87d718acad9842da2ea822cd3c83..ab23a2a54cb859aab59e632679f69a7f2d2a8866 100644
--- a/Cabal/Distribution/Utils/NubList.hs
+++ b/Cabal/Distribution/Utils/NubList.hs
@@ -1,4 +1,5 @@
 {-# LANGUAGE DeriveDataTypeable #-}
+{-# LANGUAGE DeriveGeneric      #-}
 module Distribution.Utils.NubList
     ( NubList    -- opaque
     , toNubList  -- smart construtor
@@ -21,7 +22,7 @@ import qualified Text.Read as R
 -- | NubList : A de-duplicated list that maintains the original order.
 newtype NubList a =
     NubList { fromNubList :: [a] }
-    deriving (Eq, Typeable)
+    deriving (Eq, Generic, Typeable)
 
 -- NubList assumes that nub retains the list order while removing duplicate
 -- elements (keeping the first occurence). Documentation for "Data.List.nub"
diff --git a/Cabal/Distribution/Verbosity.hs b/Cabal/Distribution/Verbosity.hs
index e239f36520837a66d3799653c11c18e2ca529981..2920a3891f723375d6852b20411bd96dcb9c584e 100644
--- a/Cabal/Distribution/Verbosity.hs
+++ b/Cabal/Distribution/Verbosity.hs
@@ -57,6 +57,7 @@ import Distribution.ReadE
 import Data.List (elemIndex)
 import Data.Set (Set)
 import Distribution.Parsec
+import Distribution.Verbosity.Internal
 
 import qualified Data.Set as Set
 import qualified Distribution.Compat.CharParsing as P
@@ -86,11 +87,6 @@ instance Bounded Verbosity where
 
 instance Binary Verbosity
 
-data VerbosityLevel = Silent | Normal | Verbose | Deafening
-    deriving (Generic, Show, Read, Eq, Ord, Enum, Bounded)
-
-instance Binary VerbosityLevel
-
 -- We shouldn't print /anything/ unless an error occurs in silent mode
 silent :: Verbosity
 silent = mkVerbosity Silent
@@ -221,16 +217,6 @@ showForGHC   v = maybe (error "unknown verbosity") show $
     elemIndex v [silent,normal,__,verbose,deafening]
         where __ = silent -- this will be always ignored by elemIndex
 
-data VerbosityFlag
-    = VCallStack
-    | VCallSite
-    | VNoWrap
-    | VMarkOutput
-    | VTimestamp
-    deriving (Generic, Show, Read, Eq, Ord, Enum, Bounded)
-
-instance Binary VerbosityFlag
-
 -- | Turn on verbose call-site printing when we log.
 verboseCallSite :: Verbosity -> Verbosity
 verboseCallSite = verboseFlag VCallSite
diff --git a/Cabal/Distribution/Verbosity/Internal.hs b/Cabal/Distribution/Verbosity/Internal.hs
new file mode 100644
index 0000000000000000000000000000000000000000..d6bdef7f96d4112ac18f6b122721d35236c63fd4
--- /dev/null
+++ b/Cabal/Distribution/Verbosity/Internal.hs
@@ -0,0 +1,23 @@
+{-# LANGUAGE DeriveGeneric #-}
+module Distribution.Verbosity.Internal
+  ( VerbosityLevel(..)
+  , VerbosityFlag(..)
+  ) where
+
+import Prelude ()
+import Distribution.Compat.Prelude
+
+data VerbosityLevel = Silent | Normal | Verbose | Deafening
+    deriving (Generic, Show, Read, Eq, Ord, Enum, Bounded)
+
+instance Binary VerbosityLevel
+
+data VerbosityFlag
+    = VCallStack
+    | VCallSite
+    | VNoWrap
+    | VMarkOutput
+    | VTimestamp
+    deriving (Generic, Show, Read, Eq, Ord, Enum, Bounded)
+
+instance Binary VerbosityFlag
diff --git a/Cabal/Distribution/Version.hs b/Cabal/Distribution/Version.hs
index 9beb9385861568b1150d7e166cfbb533e7abd885..06571b7fd0a349d6509f36ea890064900189969b 100644
--- a/Cabal/Distribution/Version.hs
+++ b/Cabal/Distribution/Version.hs
@@ -22,11 +22,8 @@ module Distribution.Version (
   nullVersion,
   alterVersion,
 
-  -- ** Backwards compatibility
-  showVersion,
-
   -- * Version ranges
-  VersionRange(..),
+  VersionRange,
 
   -- ** Constructing
   anyVersion, noVersion,
@@ -38,7 +35,6 @@ module Distribution.Version (
   invertVersionRange,
   withinVersion,
   majorBoundVersion,
-  betweenVersionsInclusive,
 
   -- ** Inspection
   withinRange,
@@ -47,7 +43,6 @@ module Distribution.Version (
   isSpecificVersion,
   simplifyVersionRange,
   foldVersionRange,
-  foldVersionRange',
   normaliseVersionRange,
   stripParensVersionRange,
   hasUpperBound,
@@ -198,65 +193,3 @@ removeUpperBound = fromVersionIntervals . relaxLastInterval . toVersionIntervals
 -- @(>= 0 && < 3) || (>= 4 && < 5)@.
 removeLowerBound :: VersionRange -> VersionRange
 removeLowerBound = fromVersionIntervals . relaxHeadInterval . toVersionIntervals
-
--------------------------------------------------------------------------------
--- Deprecated
--------------------------------------------------------------------------------
-
--- In practice this is not very useful because we normally use inclusive lower
--- bounds and exclusive upper bounds.
---
--- > withinRange v' (laterVersion v) = v' > v
---
-betweenVersionsInclusive :: Version -> Version -> VersionRange
-betweenVersionsInclusive v1 v2 =
-  intersectVersionRanges (orLaterVersion v1) (orEarlierVersion v2)
-
-{-# DEPRECATED betweenVersionsInclusive
-    "In practice this is not very useful because we normally use inclusive lower bounds and exclusive upper bounds" #-}
-
-
-
-
--- | An extended variant of 'foldVersionRange' that also provides a view of the
--- expression in which the syntactic sugar @\">= v\"@, @\"<= v\"@ and @\"==
--- v.*\"@ is presented explicitly rather than in terms of the other basic
--- syntax.
---
-foldVersionRange' :: a                         -- ^ @\"-any\"@ version
-                  -> (Version -> a)            -- ^ @\"== v\"@
-                  -> (Version -> a)            -- ^ @\"> v\"@
-                  -> (Version -> a)            -- ^ @\"< v\"@
-                  -> (Version -> a)            -- ^ @\">= v\"@
-                  -> (Version -> a)            -- ^ @\"<= v\"@
-                  -> (Version -> Version -> a) -- ^ @\"== v.*\"@ wildcard. The
-                                               -- function is passed the
-                                               -- inclusive lower bound and the
-                                               -- exclusive upper bounds of the
-                                               -- range defined by the wildcard.
-                  -> (Version -> Version -> a) -- ^ @\"^>= v\"@ major upper bound
-                                               -- The function is passed the
-                                               -- inclusive lower bound and the
-                                               -- exclusive major upper bounds
-                                               -- of the range defined by this
-                                               -- operator.
-                  -> (a -> a -> a)             -- ^ @\"_ || _\"@ union
-                  -> (a -> a -> a)             -- ^ @\"_ && _\"@ intersection
-                  -> (a -> a)                  -- ^ @\"(_)\"@ parentheses
-                  -> VersionRange -> a
-foldVersionRange' anyv this later earlier orLater orEarlier
-                  wildcard major union intersect parens =
-    cataVersionRange alg . normaliseVersionRange
-  where
-    alg AnyVersionF                     = anyv
-    alg (ThisVersionF v)                = this v
-    alg (LaterVersionF v)               = later v
-    alg (EarlierVersionF v)             = earlier v
-    alg (OrLaterVersionF v)             = orLater v
-    alg (OrEarlierVersionF v)           = orEarlier v
-    alg (WildcardVersionF v)            = wildcard v (wildcardUpperBound v)
-    alg (MajorBoundVersionF v)          = major v (majorUpperBound v)
-    alg (UnionVersionRangesF v1 v2)     = union v1 v2
-    alg (IntersectVersionRangesF v1 v2) = intersect v1 v2
-    alg (VersionRangeParensF v)         = parens v
-{-# DEPRECATED foldVersionRange' "Use cataVersionRange & normaliseVersionRange for more principled folding" #-}
diff --git a/Cabal/Language/Haskell/Extension.hs b/Cabal/Language/Haskell/Extension.hs
index 2740b72e52ddf6dbe8e082ea357498eca015fbca..b279abafe1d99c69fd66ec08d865bb00fc628b78 100644
--- a/Cabal/Language/Haskell/Extension.hs
+++ b/Cabal/Language/Haskell/Extension.hs
@@ -19,7 +19,6 @@ module Language.Haskell.Extension (
 
         Extension(..),
         KnownExtension(..),
-        knownExtensions,
         deprecatedExtensions,
         classifyExtension,
   ) where
@@ -309,6 +308,9 @@ data KnownExtension =
   -- * <https://www.haskell.org/ghc/docs/latest/html/users_guide/glasgow_exts.html#ghc-flag--XGeneralizedNewtypeDeriving>
   | GeneralizedNewtypeDeriving
 
+  -- Synonym for GeneralizedNewtypeDeriving added in GHC 8.6.1.
+  | GeneralisedNewtypeDeriving
+
   -- | Enable the \"Trex\" extensible records system.
   --
   -- * <http://haskell.org/hugs/pages/users_guide/hugs-only.html#TREX>
@@ -818,17 +820,17 @@ data KnownExtension =
   -- | Have @*@ refer to @Type@.
   | StarIsType
 
+  -- | Liberalises deriving to provide instances for empty data types.
+  --
+  -- * <https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#deriving-instances-for-empty-data-types>
+  | EmptyDataDeriving
+
   deriving (Generic, Show, Read, Eq, Ord, Enum, Bounded, Typeable, Data)
 
 instance Binary KnownExtension
 
 instance NFData KnownExtension where rnf = genericRnf
 
-{-# DEPRECATED knownExtensions
-   "KnownExtension is an instance of Enum and Bounded, use those instead. This symbol will be removed in Cabal-3.0 (est. Mar 2019)." #-}
-knownExtensions :: [KnownExtension]
-knownExtensions = [minBound..maxBound]
-
 -- | Extensions that have been deprecated, possibly paired with another
 -- extension that replaces it.
 --
diff --git a/Cabal/Makefile b/Cabal/Makefile
index 1cd2645d258c5be5a9fcf7ab05dc66c96259125a..df01c714bed283c54db7c62e6340e3f5570e6f43 100644
--- a/Cabal/Makefile
+++ b/Cabal/Makefile
@@ -1,4 +1,4 @@
-VERSION=3.0.0.0
+VERSION=3.1.0.0
 
 #KIND=devel
 KIND=rc
diff --git a/Cabal/doc/conf.py b/Cabal/doc/conf.py
index b64b0344b68fc31ff5389611cbf6954277c1a807..808c1e653de943617fe554fa59f2a543edad761f 100644
--- a/Cabal/doc/conf.py
+++ b/Cabal/doc/conf.py
@@ -13,7 +13,7 @@ import sphinx_rtd_theme
 sys.path.insert(0, os.path.abspath('.'))
 import cabaldomain
 
-version = "3.0.0.0"
+version = "3.1.0.0"
 
 extensions = ['sphinx.ext.extlinks', 'sphinx.ext.todo']
 
diff --git a/Cabal/doc/developing-packages.rst b/Cabal/doc/developing-packages.rst
index 6a8aec18c82223873465de60baa13152158accfa..eb471606d3121738e88751889adeb5c1e5f4a41a 100644
--- a/Cabal/doc/developing-packages.rst
+++ b/Cabal/doc/developing-packages.rst
@@ -1485,11 +1485,13 @@ The following flags are supported by the ``outdated`` command:
     Read dependency version bounds from the freeze file (``cabal.config``)
     instead of the package description file (``$PACKAGENAME.cabal``).
     ``--v1-freeze-file`` is an alias for this flag starting in Cabal 2.4.
-``--new-freeze-file``
+``--v2-freeze-file``
+    :since: 2.4
+
     Read dependency version bounds from the v2-style freeze file
     (by default, ``cabal.project.freeze``) instead of the package
-    description file. ``--v2-freeze-file`` is an alias for this flag
-    starting in Cabal 2.4.
+    description file. ``--new-freeze-file`` is an alias for this flag
+    that can be used with pre-2.4 ``cabal``.
 ``--project-file`` *PROJECTFILE*
     :since: 2.4
 
@@ -3229,6 +3231,11 @@ rely on dependencies being implicitly in scope.  Please refer
 `this article <https://www.well-typed.com/blog/2015/07/cabal-setup-deps/>`__
 for more details.
 
+As of Cabal library version 3.0, ``defaultMain*`` variants implement support
+for response files. Custom ``Setup.hs`` files that do not use one of these
+main functions are required to implement their own support, such as by using
+``GHC.ResponseFile.getArgsWithResponseFiles``.
+
 Declaring a ``custom-setup`` stanza also enables the generation of
 ``MIN_VERSION_package_(A,B,C)`` CPP macros for the Setup component.
 
@@ -3321,8 +3328,8 @@ is to distinguish ``Cabal < 2.0`` from ``Cabal >= 2.0``.
 
 
 
-Autogenerated modules
----------------------
+Autogenerated modules and includes
+----------------------------------
 
 Modules that are built automatically at setup, created with a custom
 setup script, must appear on :pkg-field:`other-modules` for the library,
@@ -3367,6 +3374,13 @@ Right now :pkg-field:`executable:main-is` modules are not supported on
         autogen-modules:
             MyExeHelperModule
 
+.. pkg-field:: autogen-includes: filename list
+   :since: 3.0
+
+   A list of header files from this package which are autogenerated
+   (e.g. by a ``configure`` script). Autogenerated header files are not
+   packaged by ``sdist`` command.
+
 Accessing data files from package code
 --------------------------------------
 
diff --git a/Cabal/doc/file-format-changelog.rst b/Cabal/doc/file-format-changelog.rst
index b1e6d938ed7694247c1677ecf6b4a723ed4cb488..cf84b7e5d7f89189028df66f54e6668b19740c37 100644
--- a/Cabal/doc/file-format-changelog.rst
+++ b/Cabal/doc/file-format-changelog.rst
@@ -19,6 +19,11 @@ relative to the respective preceding *published* version.
     versions of the ``Cabal`` library denote unreleased development
     branches which have no stability guarantee.
 
+``cabal-version: 3.2``
+----------------------
+
+* Nothing yet
+
 ``cabal-version: 3.0``
 ----------------------
 
@@ -30,7 +35,7 @@ relative to the respective preceding *published* version.
   and indentation. In other words, you don't need to add dots for blank lines.
 
 * License fields use identifiers from SPDX License List version
-  ``3.5 2019-04-02``
+  ``3.6 2019-07-10``
 
 * Remove deprecated ``hs-source-dir``, :pkg-field:`extensions` and
   :pkg-field:`build-tools` fields.
@@ -66,6 +71,9 @@ relative to the respective preceding *published* version.
 * Wildcards are disallowed in :pkg-field:`pkgconfig-depends`,
   Yet the pkgconfig format is relaxed to accept e.g. versions like ``1.1.0h``.
 
+* New :pkg-field:`autogen-includes` for specifying :pkg-field:`install-includes`
+  which are autogenerated (e.g. by a ``configure`` script).
+
 ``cabal-version: 2.4``
 ----------------------
 
diff --git a/Cabal/doc/installing-packages.rst b/Cabal/doc/installing-packages.rst
index 3bfbe2ffe5ae2198ee8ae9aa8735fdfbfb6eb7ea..a446c4c63b2371e2be2087cf35fef9a152b3eff9 100644
--- a/Cabal/doc/installing-packages.rst
+++ b/Cabal/doc/installing-packages.rst
@@ -44,7 +44,7 @@ files created by older versions of ``cabal``.
 Repository specification
 ------------------------
 
-An important part of the configuration if the specification of the
+An important part of the configuration is the specification of the
 repository. When ``cabal`` creates a default config file, it configures
 the repository to be the central Hackage server:
 
@@ -1719,6 +1719,13 @@ the package.
     quote options containing spaces because a single option is assumed,
     so options will not be split on spaces.
 
+.. option:: --test-wrapper=path
+
+   The wrapper script/application used to setup and tear down the test
+   execution context. The text executable path and test arguments are
+   passed as arguments to the wrapper and it is expected that the wrapper
+   will return the test's return code, as well as a copy of stdout/stderr.
+
 .. _setup-sdist:
 
 setup sdist
diff --git a/Cabal/doc/nix-local-build.rst b/Cabal/doc/nix-local-build.rst
index bf8f9db5898261fe5aabc1fce0fd5c0ab4faac28..a865c12c6d5f2c1bd0d63f0f9edffd2ed1e2d03e 100644
--- a/Cabal/doc/nix-local-build.rst
+++ b/Cabal/doc/nix-local-build.rst
@@ -1424,7 +1424,8 @@ Object code options
     Not all Haskell implementations generate native binaries. For such
     implementations this option has no effect.
 
-    (TODO: Check what happens if you combine this with ``debug-info``.)
+    If ``debug-info`` is set explicitly then ``executable-stripping`` is set
+    to ``False`` as otherwise all the debug symbols will be stripped.
 
     The command line variant of this flag is
     ``--enable-executable-stripping`` and
@@ -1440,6 +1441,9 @@ Object code options
     binary, saving space on the file system. See also
     ``executable-stripping``.
 
+    If ``debug-info`` is set explicitly then ``library-stripping`` is set
+    to ``False`` as otherwise all the debug symbols will be stripped.
+
     The command line variant of this flag is
     ``--enable-library-stripping`` and ``--disable-library-stripping``.
 
@@ -1825,6 +1829,7 @@ running ``setup haddock``. (TODO: Where does the documentation get put.)
     ``haddock`` command).
 
 .. cfg-field:: haddock-html-location: templated path
+               --html-location=TEMPLATE
     :synopsis: Haddock HTML templates location.
 
     Specify a template for the location of HTML documentation for
@@ -1835,15 +1840,19 @@ running ``setup haddock``. (TODO: Where does the documentation get put.)
 
     ::
 
-        html-location: 'http://hackage.haskell.org/packages/archive/$pkg/latest/doc/html'
+        html-location: http://hackage.haskell.org/packages/archive/$pkg/latest/doc/html
+
+    The command line variant of this flag is ``--html-location`` (for
+    the ``haddock`` subcommand).
+
+    ::
+
+        --html-location='http://hackage.haskell.org/packages/archive/$pkg/latest/doc/html'
 
     Here the argument is quoted to prevent substitution by the shell. If
     this option is omitted, the location for each package is obtained
     using the package tool (e.g. ``ghc-pkg``).
 
-    The command line variant of this flag is ``--html-location`` (for
-    the ``haddock`` subcommand).
-
 .. cfg-field:: haddock-executables: boolean
     :synopsis: Generate documentation for executables.
 
diff --git a/Cabal/tests/CheckTests.hs b/Cabal/tests/CheckTests.hs
index cd9c8f1dc4404a3f582b46b6924437949ac053b0..42768dc48253c025eebb9a6545688930280ef2e8 100644
--- a/Cabal/tests/CheckTests.hs
+++ b/Cabal/tests/CheckTests.hs
@@ -17,6 +17,7 @@ import System.FilePath                        (replaceExtension, (</>))
 
 import qualified Data.ByteString       as BS
 import qualified Data.ByteString.Char8 as BS8
+import qualified Data.List.NonEmpty    as NE
 
 tests :: TestTree
 tests = checkTests
@@ -52,7 +53,7 @@ checkTest fp = cabalGoldenTest fp correct $ do
             -- D.PD.Check functionality.
             unlines (map (showPWarning fp) ws) ++
             unlines (map show (checkPackage gpd Nothing))
-        Left (_, errs) -> unlines $ map (("ERROR: " ++) . showPError fp) errs
+        Left (_, errs) -> unlines $ map (("ERROR: " ++) . showPError fp) $ NE.toList errs
   where
     input = "tests" </> "ParserTests" </> "regressions" </> fp
     correct = replaceExtension input "check"
diff --git a/Cabal/tests/ParserTests.hs b/Cabal/tests/ParserTests.hs
index 88126a6167f2fdfeb44152091d074b941f09fedf..9d8e69d6a9c61b24908ebb64fabb5bbca9a7ce40 100644
--- a/Cabal/tests/ParserTests.hs
+++ b/Cabal/tests/ParserTests.hs
@@ -26,6 +26,7 @@ import System.FilePath                             (replaceExtension, (</>))
 
 import qualified Data.ByteString       as BS
 import qualified Data.ByteString.Char8 as BS8
+import qualified Data.List.NonEmpty    as NE
 
 import qualified Distribution.InstalledPackageInfo as IPI
 
@@ -136,7 +137,7 @@ errorTest fp = cabalGoldenTest fp correct $ do
             "UNXPECTED SUCCESS\n" ++
             showGenericPackageDescription gpd
         Left (v, errs) ->
-            unlines $ ("VERSION: " ++ show v) : map (showPError fp) errs
+            unlines $ ("VERSION: " ++ show v) : map (showPError fp) (NE.toList errs)
   where
     input = "tests" </> "ParserTests" </> "errors" </> fp
     correct = replaceExtension input "errors"
@@ -202,7 +203,7 @@ formatGoldenTest fp = cabalGoldenTest "format" correct $ do
             unlines (map (showPWarning fp) warns)
             ++ showGenericPackageDescription gpd
         Left (_, errs) ->
-            unlines $ "ERROR" : map (showPError fp) errs
+            unlines $ "ERROR" : map (showPError fp) (NE.toList errs)
   where
     input = "tests" </> "ParserTests" </> "regressions" </> fp
     correct = replaceExtension input "format"
@@ -215,7 +216,7 @@ treeDiffGoldenTest fp = ediffGolden goldenTest "expr" exprFile $ do
     let (_, x) = runParseResult res
     case x of
         Right gpd      -> pure (toExpr gpd)
-        Left (_, errs) -> fail $ unlines $ "ERROR" : map (showPError fp) errs
+        Left (_, errs) -> fail $ unlines $ "ERROR" : map (showPError fp) (NE.toList errs)
   where
     input = "tests" </> "ParserTests" </> "regressions" </> fp
     exprFile = replaceExtension input "expr"
@@ -251,7 +252,7 @@ formatRoundTripTest fp = testCase "roundtrip" $ do
         case x' of
             Right gpd      -> pure gpd
             Left (_, errs) -> do
-                void $ assertFailure $ unlines (map (showPError fp) errs)
+                void $ assertFailure $ unlines (map (showPError fp) $ NE.toList errs)
                 fail "failure"
     input = "tests" </> "ParserTests" </> "regressions" </> fp
 
diff --git a/Cabal/tests/ParserTests/ipi/internal-preprocessor-test.expr b/Cabal/tests/ParserTests/ipi/internal-preprocessor-test.expr
index 7a6057367a225f00fd2d716165154390a53651bb..70c02985f88a6623d8b9313c97de2b10a98ea1ec 100644
--- a/Cabal/tests/ParserTests/ipi/internal-preprocessor-test.expr
+++ b/Cabal/tests/ParserTests/ipi/internal-preprocessor-test.expr
@@ -29,7 +29,7 @@ InstalledPackageInfo
    installedUnitId = `UnitId "internal-preprocessor-test-0.1.0.0"`,
    instantiatedWith = [],
    ldOptions = [],
-   libVisibility = LibraryVisibilityPrivate,
+   libVisibility = LibraryVisibilityPublic,
    libraryDirs = ["/home/ogre/Documents/other-haskell/cabal/cabal-testsuite/PackageTests/CustomPreProcess/setup.dist/work/dist/build",
                   "/home/ogre/Documents/other-haskell/cabal/cabal-testsuite/PackageTests/CustomPreProcess/setup.dist/work/dist/build"],
    libraryDynDirs = [],
diff --git a/Cabal/tests/ParserTests/ipi/internal-preprocessor-test.format b/Cabal/tests/ParserTests/ipi/internal-preprocessor-test.format
index a30b4382efdc27dd978893ff61b832729e105168..ad305dae42294e1d263cee5ee8b8cff8b78250df 100644
--- a/Cabal/tests/ParserTests/ipi/internal-preprocessor-test.format
+++ b/Cabal/tests/ParserTests/ipi/internal-preprocessor-test.format
@@ -1,5 +1,6 @@
 name:               internal-preprocessor-test
 version:            0.1.0.0
+visibility:         public
 id:                 internal-preprocessor-test-0.1.0.0
 key:                internal-preprocessor-test-0.1.0.0
 license:            GPL-3
diff --git a/Cabal/tests/ParserTests/ipi/issue-2276-ghc-9885.expr b/Cabal/tests/ParserTests/ipi/issue-2276-ghc-9885.expr
index a2480aed77b11d3966b4d7dd76514797be7cbafe..32f483a34c7d60c1b179e59227658b040649ed52 100644
--- a/Cabal/tests/ParserTests/ipi/issue-2276-ghc-9885.expr
+++ b/Cabal/tests/ParserTests/ipi/issue-2276-ghc-9885.expr
@@ -2071,7 +2071,7 @@ InstalledPackageInfo
                 "-lm",
                 "-lm",
                 "-lm"],
-   libVisibility = LibraryVisibilityPrivate,
+   libVisibility = LibraryVisibilityPublic,
    libraryDirs = ["/opt/ghc/8.2.2/lib/ghc-8.2.2/transformers-0.5.2.0"],
    libraryDynDirs = ["/opt/ghc/8.2.2/lib/ghc-8.2.2/transformers-0.5.2.0"],
    license = Right BSD3,
diff --git a/Cabal/tests/ParserTests/ipi/issue-2276-ghc-9885.format b/Cabal/tests/ParserTests/ipi/issue-2276-ghc-9885.format
index ca626833486e151e4b3cf891c624b317fe9f8add..281203ceb09781369a23797766f0432036912536 100644
--- a/Cabal/tests/ParserTests/ipi/issue-2276-ghc-9885.format
+++ b/Cabal/tests/ParserTests/ipi/issue-2276-ghc-9885.format
@@ -1,5 +1,6 @@
 name:                 transformers
 version:              0.5.2.0
+visibility:           public
 id:                   transformers-0.5.2.0
 key:                  transformers-0.5.2.0
 license:              BSD3
diff --git a/Cabal/tests/ParserTests/ipi/transformers.expr b/Cabal/tests/ParserTests/ipi/transformers.expr
index 9d0adce36b17fef2f565d9485328b401c38b9ce6..a42deb65af1db57a911e53dcd5bcd12f3b13ee3e 100644
--- a/Cabal/tests/ParserTests/ipi/transformers.expr
+++ b/Cabal/tests/ParserTests/ipi/transformers.expr
@@ -71,7 +71,7 @@ InstalledPackageInfo
    installedUnitId = `UnitId "transformers-0.5.2.0"`,
    instantiatedWith = [],
    ldOptions = [],
-   libVisibility = LibraryVisibilityPrivate,
+   libVisibility = LibraryVisibilityPublic,
    libraryDirs = ["/opt/ghc/8.2.2/lib/ghc-8.2.2/transformers-0.5.2.0"],
    libraryDynDirs = ["/opt/ghc/8.2.2/lib/ghc-8.2.2/transformers-0.5.2.0"],
    license = Right BSD3,
diff --git a/Cabal/tests/ParserTests/ipi/transformers.format b/Cabal/tests/ParserTests/ipi/transformers.format
index e54d54af6c12b4c9ab7af13a0fc727ea463227b1..66a0e14e5b517aca459d8ea7f28fa2953962a318 100644
--- a/Cabal/tests/ParserTests/ipi/transformers.format
+++ b/Cabal/tests/ParserTests/ipi/transformers.format
@@ -1,5 +1,6 @@
 name:                 transformers
 version:              0.5.2.0
+visibility:           public
 id:                   transformers-0.5.2.0
 key:                  transformers-0.5.2.0
 license:              BSD3
diff --git a/Cabal/tests/ParserTests/regressions/Octree-0.5.expr b/Cabal/tests/ParserTests/regressions/Octree-0.5.expr
index 540b424a781f69eb1a00607351bfe8d9c67c49e3..97823233724d9a007ee0ade1a6de7c510486b400 100644
--- a/Cabal/tests/ParserTests/regressions/Octree-0.5.expr
+++ b/Cabal/tests/ParserTests/regressions/Octree-0.5.expr
@@ -24,6 +24,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -113,6 +114,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
@@ -206,6 +208,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/common-conditional.expr b/Cabal/tests/ParserTests/regressions/common-conditional.expr
index bf66e970a7f08f7f53d2a7ee47f5351ee93f8938..50d2560f7de0b74d51d8bb50b16d11eab7b8aac0 100644
--- a/Cabal/tests/ParserTests/regressions/common-conditional.expr
+++ b/Cabal/tests/ParserTests/regressions/common-conditional.expr
@@ -23,6 +23,7 @@ GenericPackageDescription
                                                                                                                                       libBuildInfo = BuildInfo
                                                                                                                                                        {asmOptions = [],
                                                                                                                                                         asmSources = [],
+                                                                                                                                                        autogenIncludes = [],
                                                                                                                                                         autogenModules = [],
                                                                                                                                                         buildToolDepends = [],
                                                                                                                                                         buildTools = [],
@@ -99,6 +100,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -174,6 +176,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -237,6 +240,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -308,6 +312,7 @@ GenericPackageDescription
                                                                                                                                          {testBuildInfo = BuildInfo
                                                                                                                                                             {asmOptions = [],
                                                                                                                                                              asmSources = [],
+                                                                                                                                                             autogenIncludes = [],
                                                                                                                                                              autogenModules = [],
                                                                                                                                                              buildToolDepends = [],
                                                                                                                                                              buildTools = [],
@@ -379,6 +384,7 @@ GenericPackageDescription
                                                                                                                                          {testBuildInfo = BuildInfo
                                                                                                                                                             {asmOptions = [],
                                                                                                                                                              asmSources = [],
+                                                                                                                                                             autogenIncludes = [],
                                                                                                                                                              autogenModules = [],
                                                                                                                                                              buildToolDepends = [],
                                                                                                                                                              buildTools = [],
@@ -454,6 +460,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -528,6 +535,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/common.expr b/Cabal/tests/ParserTests/regressions/common.expr
index 9533ab5a30ee28c864d1761309e556f833ed4dd2..7408732f7b3f620525e4eded9871a72974972984 100644
--- a/Cabal/tests/ParserTests/regressions/common.expr
+++ b/Cabal/tests/ParserTests/regressions/common.expr
@@ -14,6 +14,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -76,6 +77,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/common2.expr b/Cabal/tests/ParserTests/regressions/common2.expr
index 460e4c33422e14ace654bd777b91b1d962861fde..c62cc295410fcb07d3207212989e8bb0d3b04c16 100644
--- a/Cabal/tests/ParserTests/regressions/common2.expr
+++ b/Cabal/tests/ParserTests/regressions/common2.expr
@@ -19,6 +19,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -95,6 +96,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -176,6 +178,7 @@ GenericPackageDescription
                                                                                              libBuildInfo = BuildInfo
                                                                                                               {asmOptions = [],
                                                                                                                asmSources = [],
+                                                                                                               autogenIncludes = [],
                                                                                                                autogenModules = [],
                                                                                                                buildToolDepends = [],
                                                                                                                buildTools = [],
@@ -253,6 +256,7 @@ GenericPackageDescription
                                               libBuildInfo = BuildInfo
                                                                {asmOptions = [],
                                                                 asmSources = [],
+                                                                autogenIncludes = [],
                                                                 autogenModules = [],
                                                                 buildToolDepends = [],
                                                                 buildTools = [],
@@ -337,6 +341,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -408,6 +413,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -475,6 +481,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -546,6 +553,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/common3.expr b/Cabal/tests/ParserTests/regressions/common3.expr
index 76d5e14be683f09195aedbf58e4dd1675ab15c4d..3e0ed2d5867c1adad479ec5bd4edbb4d137ba31b 100644
--- a/Cabal/tests/ParserTests/regressions/common3.expr
+++ b/Cabal/tests/ParserTests/regressions/common3.expr
@@ -14,6 +14,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -86,6 +87,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/elif.expr b/Cabal/tests/ParserTests/regressions/elif.expr
index 11a1191c358ffa96a438b2d6fefae16c86067b32..fe0d1195668a535a447b33c0594cfe983a942c10 100644
--- a/Cabal/tests/ParserTests/regressions/elif.expr
+++ b/Cabal/tests/ParserTests/regressions/elif.expr
@@ -19,6 +19,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -82,6 +83,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/elif2.expr b/Cabal/tests/ParserTests/regressions/elif2.expr
index fd7e6bb63632619b4c0fb6a91dd51860e2655d21..3de829c72d6086cf0cac7b9dbc7b235db64a63a9 100644
--- a/Cabal/tests/ParserTests/regressions/elif2.expr
+++ b/Cabal/tests/ParserTests/regressions/elif2.expr
@@ -19,6 +19,7 @@ GenericPackageDescription
                                                                                                                                             libBuildInfo = BuildInfo
                                                                                                                                                              {asmOptions = [],
                                                                                                                                                               asmSources = [],
+                                                                                                                                                              autogenIncludes = [],
                                                                                                                                                               autogenModules = [],
                                                                                                                                                               buildToolDepends = [],
                                                                                                                                                               buildTools = [],
@@ -84,6 +85,7 @@ GenericPackageDescription
                                                                                                                                          libBuildInfo = BuildInfo
                                                                                                                                                           {asmOptions = [],
                                                                                                                                                            asmSources = [],
+                                                                                                                                                           autogenIncludes = [],
                                                                                                                                                            autogenModules = [],
                                                                                                                                                            buildToolDepends = [],
                                                                                                                                                            buildTools = [],
@@ -147,6 +149,7 @@ GenericPackageDescription
                                                                                           libBuildInfo = BuildInfo
                                                                                                            {asmOptions = [],
                                                                                                             asmSources = [],
+                                                                                                            autogenIncludes = [],
                                                                                                             autogenModules = [],
                                                                                                             buildToolDepends = [],
                                                                                                             buildTools = [],
@@ -212,6 +215,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -275,6 +279,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/encoding-0.8.expr b/Cabal/tests/ParserTests/regressions/encoding-0.8.expr
index fb3277136f97a4e55cfe327ed97acf8699676a7b..32fc912232e2d3fc8feae896da1f383cd4b0210e 100644
--- a/Cabal/tests/ParserTests/regressions/encoding-0.8.expr
+++ b/Cabal/tests/ParserTests/regressions/encoding-0.8.expr
@@ -17,6 +17,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/generics-sop.expr b/Cabal/tests/ParserTests/regressions/generics-sop.expr
index 4d1061af7b73de7bbf61779eb57e1de82884e88e..299c14c3a803846cecf944a5c59d97bd2e1089bb 100644
--- a/Cabal/tests/ParserTests/regressions/generics-sop.expr
+++ b/Cabal/tests/ParserTests/regressions/generics-sop.expr
@@ -23,6 +23,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -112,6 +113,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -193,6 +195,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -258,6 +261,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -354,6 +358,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -498,6 +503,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
@@ -579,6 +585,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/hidden-main-lib.expr b/Cabal/tests/ParserTests/regressions/hidden-main-lib.expr
index bd2163c2ee818298532a78c99ecbd7862d7475a7..656549e5bfe29a62bdffd714a1f82dd768c68d6b 100644
--- a/Cabal/tests/ParserTests/regressions/hidden-main-lib.expr
+++ b/Cabal/tests/ParserTests/regressions/hidden-main-lib.expr
@@ -14,6 +14,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/indentation.expr b/Cabal/tests/ParserTests/regressions/indentation.expr
index 041b2da99210b92289791808988d5751421a253b..138bfb272fcbc98313a542603c6e0ebff7df7426 100644
--- a/Cabal/tests/ParserTests/regressions/indentation.expr
+++ b/Cabal/tests/ParserTests/regressions/indentation.expr
@@ -11,6 +11,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/indentation2.expr b/Cabal/tests/ParserTests/regressions/indentation2.expr
index 7aed84303e73cf41b80f5c684d8467ede33b66cf..c017bb44fadfa4e66a0629b180b8b8450d547a89 100644
--- a/Cabal/tests/ParserTests/regressions/indentation2.expr
+++ b/Cabal/tests/ParserTests/regressions/indentation2.expr
@@ -11,6 +11,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/indentation3.expr b/Cabal/tests/ParserTests/regressions/indentation3.expr
index ff34d8bff4365ceb7440e171f9822a559be5a1f1..cbe7d26d0c3491bd781a229c45a8eb9e4428cfd5 100644
--- a/Cabal/tests/ParserTests/regressions/indentation3.expr
+++ b/Cabal/tests/ParserTests/regressions/indentation3.expr
@@ -11,6 +11,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/issue-5055.expr b/Cabal/tests/ParserTests/regressions/issue-5055.expr
index 2997e06737faa48b577b45cf12dffabe22d06eb1..a4bea5c8a292918f8e75a5ab836d2005ff7da30e 100644
--- a/Cabal/tests/ParserTests/regressions/issue-5055.expr
+++ b/Cabal/tests/ParserTests/regressions/issue-5055.expr
@@ -14,6 +14,7 @@ GenericPackageDescription
                                             {buildInfo = BuildInfo
                                                            {asmOptions = [],
                                                             asmSources = [],
+                                                            autogenIncludes = [],
                                                             autogenModules = [],
                                                             buildToolDepends = [],
                                                             buildTools = [],
@@ -81,6 +82,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -144,6 +146,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/issue-774.expr b/Cabal/tests/ParserTests/regressions/issue-774.expr
index 64e0037e8f5466151f8d12e8012c4e531bfc844e..1b27a8cf0b66c499026fb13bc611bc911f63c608 100644
--- a/Cabal/tests/ParserTests/regressions/issue-774.expr
+++ b/Cabal/tests/ParserTests/regressions/issue-774.expr
@@ -11,6 +11,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/jaeger-flamegraph.expr b/Cabal/tests/ParserTests/regressions/jaeger-flamegraph.expr
index 00e10cf33dd4f6c68628a67924a5f9d0da6c2797..eeb49511f5462d266145f071bc72cd31914f9538 100644
--- a/Cabal/tests/ParserTests/regressions/jaeger-flamegraph.expr
+++ b/Cabal/tests/ParserTests/regressions/jaeger-flamegraph.expr
@@ -42,6 +42,7 @@ GenericPackageDescription
                                             {buildInfo = BuildInfo
                                                            {asmOptions = [],
                                                             asmSources = [],
+                                                            autogenIncludes = [],
                                                             autogenModules = [],
                                                             buildToolDepends = [],
                                                             buildTools = [],
@@ -157,6 +158,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -250,6 +252,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [`ExeDependency (PackageName "tasty-discover") (UnqualComponentName "tasty-discover") (MajorBoundVersion (mkVersion [4,2,1]))`],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/leading-comma-2.expr b/Cabal/tests/ParserTests/regressions/leading-comma-2.expr
index 68bf1e5ce226ade5d7adc9523eee274fc85f6111..44b54cbdc648e07e7e8d9b959390c35ebdbce6c4 100644
--- a/Cabal/tests/ParserTests/regressions/leading-comma-2.expr
+++ b/Cabal/tests/ParserTests/regressions/leading-comma-2.expr
@@ -41,6 +41,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/leading-comma.expr b/Cabal/tests/ParserTests/regressions/leading-comma.expr
index a95daebdb8c7d1b54d0796a3b76680be9884b31b..7548ac5cb00904e932c47f62dddc8688d813cdda 100644
--- a/Cabal/tests/ParserTests/regressions/leading-comma.expr
+++ b/Cabal/tests/ParserTests/regressions/leading-comma.expr
@@ -34,6 +34,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/libpq1.expr b/Cabal/tests/ParserTests/regressions/libpq1.expr
index e751cfc456e1ee47ab26dbafd64ebccbb51e3b4f..1fa3f47d4709b9d5c157c4f2faba4cc5de53f77f 100644
--- a/Cabal/tests/ParserTests/regressions/libpq1.expr
+++ b/Cabal/tests/ParserTests/regressions/libpq1.expr
@@ -23,6 +23,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -103,6 +104,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -183,6 +185,7 @@ GenericPackageDescription
                                                                                                                                                                                            libBuildInfo = BuildInfo
                                                                                                                                                                                                             {asmOptions = [],
                                                                                                                                                                                                              asmSources = [],
+                                                                                                                                                                                                             autogenIncludes = [],
                                                                                                                                                                                                              autogenModules = [],
                                                                                                                                                                                                              buildToolDepends = [],
                                                                                                                                                                                                              buildTools = [],
@@ -243,6 +246,7 @@ GenericPackageDescription
                                                                                                                                             libBuildInfo = BuildInfo
                                                                                                                                                              {asmOptions = [],
                                                                                                                                                               asmSources = [],
+                                                                                                                                                              autogenIncludes = [],
                                                                                                                                                               autogenModules = [],
                                                                                                                                                               buildToolDepends = [],
                                                                                                                                                               buildTools = [],
@@ -304,6 +308,7 @@ GenericPackageDescription
                                                                                                                                          libBuildInfo = BuildInfo
                                                                                                                                                           {asmOptions = [],
                                                                                                                                                            asmSources = [],
+                                                                                                                                                           autogenIncludes = [],
                                                                                                                                                            autogenModules = [],
                                                                                                                                                            buildToolDepends = [],
                                                                                                                                                            buildTools = [],
@@ -363,6 +368,7 @@ GenericPackageDescription
                                                                                           libBuildInfo = BuildInfo
                                                                                                            {asmOptions = [],
                                                                                                             asmSources = [],
+                                                                                                            autogenIncludes = [],
                                                                                                             autogenModules = [],
                                                                                                             buildToolDepends = [],
                                                                                                             buildTools = [],
@@ -424,6 +430,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -495,6 +502,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [`LegacyExeDependency "hsc2hs" AnyVersion`],
diff --git a/Cabal/tests/ParserTests/regressions/libpq2.expr b/Cabal/tests/ParserTests/regressions/libpq2.expr
index d7d7356b1715773f7fa6f6341aedf95ba1c478c5..2aa2cff8ec39a77621bbd5acef17e74918415fec 100644
--- a/Cabal/tests/ParserTests/regressions/libpq2.expr
+++ b/Cabal/tests/ParserTests/regressions/libpq2.expr
@@ -23,6 +23,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -103,6 +104,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -183,6 +185,7 @@ GenericPackageDescription
                                                                                                                                                                                            libBuildInfo = BuildInfo
                                                                                                                                                                                                             {asmOptions = [],
                                                                                                                                                                                                              asmSources = [],
+                                                                                                                                                                                                             autogenIncludes = [],
                                                                                                                                                                                                              autogenModules = [],
                                                                                                                                                                                                              buildToolDepends = [],
                                                                                                                                                                                                              buildTools = [],
@@ -243,6 +246,7 @@ GenericPackageDescription
                                                                                                                                             libBuildInfo = BuildInfo
                                                                                                                                                              {asmOptions = [],
                                                                                                                                                               asmSources = [],
+                                                                                                                                                              autogenIncludes = [],
                                                                                                                                                               autogenModules = [],
                                                                                                                                                               buildToolDepends = [],
                                                                                                                                                               buildTools = [],
@@ -304,6 +308,7 @@ GenericPackageDescription
                                                                                                                                          libBuildInfo = BuildInfo
                                                                                                                                                           {asmOptions = [],
                                                                                                                                                            asmSources = [],
+                                                                                                                                                           autogenIncludes = [],
                                                                                                                                                            autogenModules = [],
                                                                                                                                                            buildToolDepends = [],
                                                                                                                                                            buildTools = [],
@@ -363,6 +368,7 @@ GenericPackageDescription
                                                                                           libBuildInfo = BuildInfo
                                                                                                            {asmOptions = [],
                                                                                                             asmSources = [],
+                                                                                                            autogenIncludes = [],
                                                                                                             autogenModules = [],
                                                                                                             buildToolDepends = [],
                                                                                                             buildTools = [],
@@ -424,6 +430,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -495,6 +502,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [`ExeDependency (PackageName "hsc2hs") (UnqualComponentName "hsc2hs") AnyVersion`],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/mixin-1.expr b/Cabal/tests/ParserTests/regressions/mixin-1.expr
index fd330eed190f05c3619ffe272adc19c5193c46d3..f49c417221fe118823fe4a0e2270a0841ae122e0 100644
--- a/Cabal/tests/ParserTests/regressions/mixin-1.expr
+++ b/Cabal/tests/ParserTests/regressions/mixin-1.expr
@@ -20,6 +20,7 @@ GenericPackageDescription
                                             {buildInfo = BuildInfo
                                                            {asmOptions = [],
                                                             asmSources = [],
+                                                            autogenIncludes = [],
                                                             autogenModules = [],
                                                             buildToolDepends = [],
                                                             buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/mixin-2.expr b/Cabal/tests/ParserTests/regressions/mixin-2.expr
index c36df74f8ac4eff486ad258a99fedc1af9d50520..9baa2b18908654c858bf1c621dfc3206a80174de 100644
--- a/Cabal/tests/ParserTests/regressions/mixin-2.expr
+++ b/Cabal/tests/ParserTests/regressions/mixin-2.expr
@@ -20,6 +20,7 @@ GenericPackageDescription
                                             {buildInfo = BuildInfo
                                                            {asmOptions = [],
                                                             asmSources = [],
+                                                            autogenIncludes = [],
                                                             autogenModules = [],
                                                             buildToolDepends = [],
                                                             buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/mixin-3.expr b/Cabal/tests/ParserTests/regressions/mixin-3.expr
index 2262dc5235b87d8521f4b062ae6b6a5c8cab3f67..c0bf4c03bd35ead11b17a152593d548ef57816a7 100644
--- a/Cabal/tests/ParserTests/regressions/mixin-3.expr
+++ b/Cabal/tests/ParserTests/regressions/mixin-3.expr
@@ -20,6 +20,7 @@ GenericPackageDescription
                                             {buildInfo = BuildInfo
                                                            {asmOptions = [],
                                                             asmSources = [],
+                                                            autogenIncludes = [],
                                                             autogenModules = [],
                                                             buildToolDepends = [],
                                                             buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/multiple-libs-2.check b/Cabal/tests/ParserTests/regressions/multiple-libs-2.check
index c9d75918dc64e3b0a92049dcef7c51d155b2eb8a..a244e2b89b7c89cfd19ab62241fc37cffb82617f 100644
--- a/Cabal/tests/ParserTests/regressions/multiple-libs-2.check
+++ b/Cabal/tests/ParserTests/regressions/multiple-libs-2.check
@@ -1,4 +1,4 @@
-multiple-libs-2.cabal:17:3: The field "visibility" is available only since the Cabal specification version 3.0.
+multiple-libs-2.cabal:17:3: The field "visibility" is available only since the Cabal specification version 3.0. This field will be ignored.
 No 'category' field.
 No 'maintainer' field.
 No 'description' field.
diff --git a/Cabal/tests/ParserTests/regressions/multiple-libs-2.expr b/Cabal/tests/ParserTests/regressions/multiple-libs-2.expr
index 955b0ea5e02e026355acb960eeebaa7428ea7374..55b3d0acdc30db7dad94760f1426adbc1364da95 100644
--- a/Cabal/tests/ParserTests/regressions/multiple-libs-2.expr
+++ b/Cabal/tests/ParserTests/regressions/multiple-libs-2.expr
@@ -14,6 +14,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -76,6 +77,7 @@ GenericPackageDescription
                                               libBuildInfo = BuildInfo
                                                                {asmOptions = [],
                                                                 asmSources = [],
+                                                                autogenIncludes = [],
                                                                 autogenModules = [],
                                                                 buildToolDepends = [],
                                                                 buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/multiple-libs-2.format b/Cabal/tests/ParserTests/regressions/multiple-libs-2.format
index c5e9321112d4bc4a0a0f8f57ff9da0af5892c009..aba24b3c2a8417c1a767dea6ca469221ed958700 100644
--- a/Cabal/tests/ParserTests/regressions/multiple-libs-2.format
+++ b/Cabal/tests/ParserTests/regressions/multiple-libs-2.format
@@ -1,4 +1,4 @@
-multiple-libs-2.cabal:17:3: The field "visibility" is available only since the Cabal specification version 3.0.
+multiple-libs-2.cabal:17:3: The field "visibility" is available only since the Cabal specification version 3.0. This field will be ignored.
 cabal-version: 2.0
 name:          multiple-libs
 version:       0
diff --git a/Cabal/tests/ParserTests/regressions/noVersion.expr b/Cabal/tests/ParserTests/regressions/noVersion.expr
index 633c6cf880f1c41c829c51c849e2ba9ba448357f..80e2d4c7b359611313f168e24b2ea3ef4447be26 100644
--- a/Cabal/tests/ParserTests/regressions/noVersion.expr
+++ b/Cabal/tests/ParserTests/regressions/noVersion.expr
@@ -16,6 +16,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/nothing-unicode.expr b/Cabal/tests/ParserTests/regressions/nothing-unicode.expr
index 2882bd7196acc54acec1d66296157c28331bc33a..96e2ed49a298144339464aec1de63c9b1cc58deb 100644
--- a/Cabal/tests/ParserTests/regressions/nothing-unicode.expr
+++ b/Cabal/tests/ParserTests/regressions/nothing-unicode.expr
@@ -15,6 +15,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -74,6 +75,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/shake.expr b/Cabal/tests/ParserTests/regressions/shake.expr
index 7cafa64a06ff5d0c8d94591f7a8b7a526a98b39e..c67b75f07dec8121dd10d9eaee6f9f0af604768f 100644
--- a/Cabal/tests/ParserTests/regressions/shake.expr
+++ b/Cabal/tests/ParserTests/regressions/shake.expr
@@ -13,6 +13,7 @@ GenericPackageDescription
                                                                                            {buildInfo = BuildInfo
                                                                                                           {asmOptions = [],
                                                                                                            asmSources = [],
+                                                                                                           autogenIncludes = [],
                                                                                                            autogenModules = [],
                                                                                                            buildToolDepends = [],
                                                                                                            buildTools = [],
@@ -84,6 +85,7 @@ GenericPackageDescription
                                                                                                                                              {buildInfo = BuildInfo
                                                                                                                                                             {asmOptions = [],
                                                                                                                                                              asmSources = [],
+                                                                                                                                                             autogenIncludes = [],
                                                                                                                                                              autogenModules = [],
                                                                                                                                                              buildToolDepends = [],
                                                                                                                                                              buildTools = [],
@@ -145,6 +147,7 @@ GenericPackageDescription
                                                                                               {buildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -211,6 +214,7 @@ GenericPackageDescription
                                                                                                                                           {buildInfo = BuildInfo
                                                                                                                                                          {asmOptions = [],
                                                                                                                                                           asmSources = [],
+                                                                                                                                                          autogenIncludes = [],
                                                                                                                                                           autogenModules = [],
                                                                                                                                                           buildToolDepends = [],
                                                                                                                                                           buildTools = [],
@@ -271,6 +275,7 @@ GenericPackageDescription
                                                                                            {buildInfo = BuildInfo
                                                                                                           {asmOptions = [],
                                                                                                            asmSources = [],
+                                                                                                           autogenIncludes = [],
                                                                                                            autogenModules = [],
                                                                                                            buildToolDepends = [],
                                                                                                            buildTools = [],
@@ -336,6 +341,7 @@ GenericPackageDescription
                                                                                            {buildInfo = BuildInfo
                                                                                                           {asmOptions = [],
                                                                                                            asmSources = [],
+                                                                                                           autogenIncludes = [],
                                                                                                            autogenModules = [],
                                                                                                            buildToolDepends = [],
                                                                                                            buildTools = [],
@@ -463,6 +469,7 @@ GenericPackageDescription
                                             {buildInfo = BuildInfo
                                                            {asmOptions = [],
                                                             asmSources = [],
+                                                            autogenIncludes = [],
                                                             autogenModules = [],
                                                             buildToolDepends = [],
                                                             buildTools = [],
@@ -679,6 +686,7 @@ GenericPackageDescription
                                                                                                                                          libBuildInfo = BuildInfo
                                                                                                                                                           {asmOptions = [],
                                                                                                                                                            asmSources = [],
+                                                                                                                                                           autogenIncludes = [],
                                                                                                                                                            autogenModules = [],
                                                                                                                                                            buildToolDepends = [],
                                                                                                                                                            buildTools = [],
@@ -743,6 +751,7 @@ GenericPackageDescription
                                                                                           libBuildInfo = BuildInfo
                                                                                                            {asmOptions = [],
                                                                                                             asmSources = [],
+                                                                                                            autogenIncludes = [],
                                                                                                             autogenModules = [],
                                                                                                             buildToolDepends = [],
                                                                                                             buildTools = [],
@@ -812,6 +821,7 @@ GenericPackageDescription
                                                                                                                                       libBuildInfo = BuildInfo
                                                                                                                                                        {asmOptions = [],
                                                                                                                                                         asmSources = [],
+                                                                                                                                                        autogenIncludes = [],
                                                                                                                                                         autogenModules = [],
                                                                                                                                                         buildToolDepends = [],
                                                                                                                                                         buildTools = [],
@@ -875,6 +885,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -943,6 +954,7 @@ GenericPackageDescription
                                                                                        libBuildInfo = BuildInfo
                                                                                                         {asmOptions = [],
                                                                                                          asmSources = [],
+                                                                                                         autogenIncludes = [],
                                                                                                          autogenModules = [],
                                                                                                          buildToolDepends = [],
                                                                                                          buildTools = [],
@@ -1076,6 +1088,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -1263,6 +1276,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -1326,6 +1340,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -1398,6 +1413,7 @@ GenericPackageDescription
                                                                                                                                             {testBuildInfo = BuildInfo
                                                                                                                                                                {asmOptions = [],
                                                                                                                                                                 asmSources = [],
+                                                                                                                                                                autogenIncludes = [],
                                                                                                                                                                 autogenModules = [],
                                                                                                                                                                 buildToolDepends = [],
                                                                                                                                                                 buildTools = [],
@@ -1461,6 +1477,7 @@ GenericPackageDescription
                                                                                              {testBuildInfo = BuildInfo
                                                                                                                 {asmOptions = [],
                                                                                                                  asmSources = [],
+                                                                                                                 autogenIncludes = [],
                                                                                                                  autogenModules = [],
                                                                                                                  buildToolDepends = [],
                                                                                                                  buildTools = [],
@@ -1529,6 +1546,7 @@ GenericPackageDescription
                                                                                                                                          {testBuildInfo = BuildInfo
                                                                                                                                                             {asmOptions = [],
                                                                                                                                                              asmSources = [],
+                                                                                                                                                             autogenIncludes = [],
                                                                                                                                                              autogenModules = [],
                                                                                                                                                              buildToolDepends = [],
                                                                                                                                                              buildTools = [],
@@ -1591,6 +1609,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -1658,6 +1677,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -1787,6 +1807,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/spdx-1.expr b/Cabal/tests/ParserTests/regressions/spdx-1.expr
index e8d1bd85836e91aafda692a19bf8bfe5593dfccc..c1c45218a2b8e8d790ee48552b843b04c673924d 100644
--- a/Cabal/tests/ParserTests/regressions/spdx-1.expr
+++ b/Cabal/tests/ParserTests/regressions/spdx-1.expr
@@ -11,6 +11,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/spdx-2.expr b/Cabal/tests/ParserTests/regressions/spdx-2.expr
index f4c489a7a16cbf2395c252d4d0742ecb57637a76..3beaa44ce1344aac39478a0d6f4317c40bae8978 100644
--- a/Cabal/tests/ParserTests/regressions/spdx-2.expr
+++ b/Cabal/tests/ParserTests/regressions/spdx-2.expr
@@ -11,6 +11,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/spdx-3.expr b/Cabal/tests/ParserTests/regressions/spdx-3.expr
index 22ef0b353dbecaf97e4d0b93069917fbaa73d75d..9120fa0fad8a8917325ea505ef6676348f44a3ed 100644
--- a/Cabal/tests/ParserTests/regressions/spdx-3.expr
+++ b/Cabal/tests/ParserTests/regressions/spdx-3.expr
@@ -11,6 +11,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/th-lift-instances.expr b/Cabal/tests/ParserTests/regressions/th-lift-instances.expr
index 4ddd656e5aa1fbdaf9e4de927be40fd007245d39..af9d3025d3ffe4fa1c417e23b787ebbea3b82db6 100644
--- a/Cabal/tests/ParserTests/regressions/th-lift-instances.expr
+++ b/Cabal/tests/ParserTests/regressions/th-lift-instances.expr
@@ -48,6 +48,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
@@ -201,6 +202,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
@@ -321,6 +323,7 @@ GenericPackageDescription
                                                                                           {testBuildInfo = BuildInfo
                                                                                                              {asmOptions = [],
                                                                                                               asmSources = [],
+                                                                                                              autogenIncludes = [],
                                                                                                               autogenModules = [],
                                                                                                               buildToolDepends = [],
                                                                                                               buildTools = [],
@@ -394,6 +397,7 @@ GenericPackageDescription
                                            {testBuildInfo = BuildInfo
                                                               {asmOptions = [],
                                                                asmSources = [],
+                                                               autogenIncludes = [],
                                                                autogenModules = [],
                                                                buildToolDepends = [],
                                                                buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/version-sets.expr b/Cabal/tests/ParserTests/regressions/version-sets.expr
index 82b0d9a4af9362d173b4e11291d7404f4d347afd..a1159fb210d06131eae2df74020acb7d5559203f 100644
--- a/Cabal/tests/ParserTests/regressions/version-sets.expr
+++ b/Cabal/tests/ParserTests/regressions/version-sets.expr
@@ -64,6 +64,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/wl-pprint-indef.expr b/Cabal/tests/ParserTests/regressions/wl-pprint-indef.expr
index 9f245fb042292416cc71b0662789d0987a612ed2..941c90e1f4ee61e1e782f9709cfa7b8fef3edcf8 100644
--- a/Cabal/tests/ParserTests/regressions/wl-pprint-indef.expr
+++ b/Cabal/tests/ParserTests/regressions/wl-pprint-indef.expr
@@ -20,6 +20,7 @@ GenericPackageDescription
                                             {buildInfo = BuildInfo
                                                            {asmOptions = [],
                                                             asmSources = [],
+                                                            autogenIncludes = [],
                                                             autogenModules = [],
                                                             buildToolDepends = [],
                                                             buildTools = [],
@@ -96,6 +97,7 @@ GenericPackageDescription
                                         libBuildInfo = BuildInfo
                                                          {asmOptions = [],
                                                           asmSources = [],
+                                                          autogenIncludes = [],
                                                           autogenModules = [],
                                                           buildToolDepends = [],
                                                           buildTools = [],
diff --git a/Cabal/tests/ParserTests/regressions/wl-pprint-indef.format b/Cabal/tests/ParserTests/regressions/wl-pprint-indef.format
index 407402ec7327504431720fb446e191f4deb526c8..c2bcddfcbcbfc6b240b694b04908d7e70ba89504 100644
--- a/Cabal/tests/ParserTests/regressions/wl-pprint-indef.format
+++ b/Cabal/tests/ParserTests/regressions/wl-pprint-indef.format
@@ -1,6 +1,6 @@
-wl-pprint-indef.cabal:28:3: The field "mixins" is available only since the Cabal specification version 2.0.
-wl-pprint-indef.cabal:27:3: The field "signatures" is available only since the Cabal specification version 2.0.
-wl-pprint-indef.cabal:23:3: The field "mixins" is available only since the Cabal specification version 2.0.
+wl-pprint-indef.cabal:28:3: The field "mixins" is available only since the Cabal specification version 2.0. This field will be ignored.
+wl-pprint-indef.cabal:27:3: The field "signatures" is available only since the Cabal specification version 2.0. This field will be ignored.
+wl-pprint-indef.cabal:23:3: The field "mixins" is available only since the Cabal specification version 2.0. This field will be ignored.
 cabal-version: >=1.6
 name:          wl-pprint-indef
 version:       1.2
diff --git a/Cabal/tests/UnitTests/Distribution/SPDX.hs b/Cabal/tests/UnitTests/Distribution/SPDX.hs
index d3088e309f61e3c8030ba5a76fe051a161df423c..c1cf95df56e607264fd89b329f6f447582308b64 100644
--- a/Cabal/tests/UnitTests/Distribution/SPDX.hs
+++ b/Cabal/tests/UnitTests/Distribution/SPDX.hs
@@ -1,3 +1,4 @@
+{-# LANGUAGE CPP #-}
 {-# OPTIONS_GHC -fno-warn-orphans -fno-warn-deprecations #-}
 module UnitTests.Distribution.SPDX (spdxTests) where
 
@@ -11,10 +12,26 @@ import Distribution.Pretty (prettyShow)
 import Test.Tasty
 import Test.Tasty.QuickCheck
 
+#if MIN_VERSION_binary(0,7,0)
+import qualified Data.Binary as Binary
+import qualified Data.Binary.Get as Binary
+import qualified Data.Binary.Put as Binary
+import qualified Data.ByteString.Lazy as LBS
+import GHC.Generics (to, from)
+#endif
+
 spdxTests :: [TestTree]
 spdxTests =
     [ testProperty "LicenseId roundtrip" licenseIdRoundtrip
+#if MIN_VERSION_binary(0,7,0)
+    , testProperty "LicenseId Binary.put" licenseIdBinaryPut
+    , testProperty "LicenseId Binary.get" licenseIdBinaryGet
+#endif
     , testProperty "LicenseExceptionId roundtrip" licenseExceptionIdRoundtrip
+#if MIN_VERSION_binary(0,7,0)
+    , testProperty "LicenseExceptionId Binary.put" licenseExceptionIdBinaryPut
+    , testProperty "LicenseExceptionId Binary.get" licenseExceptionIdBinaryGet
+#endif
     , testProperty "LicenseRef roundtrip" licenseRefRoundtrip
     , testProperty "SimpleLicenseExpression roundtrip" simpleLicenseExpressionRoundtrip
     , testProperty "LicenseExpression roundtrip" licenseExpressionRoundtrip
@@ -23,27 +40,73 @@ spdxTests =
     ]
 
 licenseIdRoundtrip :: LicenseId -> Property
-licenseIdRoundtrip x = 
+licenseIdRoundtrip x =
     counterexample (prettyShow x) $
     Right x === eitherParsec (prettyShow x)
 
+#if MIN_VERSION_binary(0,7,0)
+licenseIdBinaryPut :: LicenseId -> Property
+licenseIdBinaryPut x =
+    Binary.runPut (Binary.put x)
+    ===
+    Binary.runPut (Binary.gput (from x))
+
+licenseIdBinaryGet :: Word8 -> Word8 -> Property
+licenseIdBinaryGet w0 w1 =
+    stripMsg id (Binary.runGetOrFail Binary.get bs)
+    ===
+    stripMsg to (Binary.runGetOrFail Binary.gget bs)
+  where
+    bs = LBS.pack [w0, w1]
+
+    stripMsg
+        :: (a -> LicenseId)
+        -> Either (x, y, String) (x, y, a)
+        -> Either (x, y) (x, y, LicenseId)
+    stripMsg _ (Left (x,y,_))  = Left (x,y)
+    stripMsg f (Right (x,y,t)) = Right (x,y,f t)
+#endif
+
 licenseExceptionIdRoundtrip :: LicenseExceptionId -> Property
 licenseExceptionIdRoundtrip x =
     counterexample (prettyShow x) $
     Right x === eitherParsec (prettyShow x)
 
+#if MIN_VERSION_binary(0,7,0)
+licenseExceptionIdBinaryPut :: LicenseExceptionId -> Property
+licenseExceptionIdBinaryPut x =
+    Binary.runPut (Binary.put x)
+    ===
+    Binary.runPut (Binary.gput (from x))
+
+licenseExceptionIdBinaryGet :: Word8 -> Property
+licenseExceptionIdBinaryGet w0 =
+    stripMsg id (Binary.runGetOrFail Binary.get bs)
+    ===
+    stripMsg to (Binary.runGetOrFail Binary.gget bs)
+  where
+    bs = LBS.pack [w0]
+
+    stripMsg
+        :: (a -> LicenseExceptionId)
+        -> Either (x, y, String) (x, y, a)
+        -> Either (x, y) (x, y, LicenseExceptionId)
+    stripMsg _ (Left (x,y,_))  = Left (x,y)
+    stripMsg f (Right (x,y,t)) = Right (x,y,f t)
+#endif
+
 licenseRefRoundtrip :: LicenseRef -> Property
 licenseRefRoundtrip x =
     counterexample (prettyShow x) $
     Right x === eitherParsec (prettyShow x)
 
 simpleLicenseExpressionRoundtrip :: SimpleLicenseExpression -> Property
-simpleLicenseExpressionRoundtrip x = 
+simpleLicenseExpressionRoundtrip x =
     counterexample (prettyShow x) $
     Right x === eitherParsec (prettyShow x)
 
 licenseExpressionRoundtrip :: LicenseExpression -> Property
-licenseExpressionRoundtrip x = 
+licenseExpressionRoundtrip x =
     counterexample (prettyShow x) $
     Right (reassoc x) === eitherParsec (prettyShow x)
 
@@ -119,10 +182,10 @@ shouldRejectProp = conjoin $
 -------------------------------------------------------------------------------
 
 instance Arbitrary LicenseId where
-    arbitrary = elements $ licenseIdList LicenseListVersion_3_5
+    arbitrary = elements $ licenseIdList LicenseListVersion_3_6
 
 instance Arbitrary LicenseExceptionId where
-    arbitrary = elements $ licenseExceptionIdList LicenseListVersion_3_5
+    arbitrary = elements $ licenseExceptionIdList LicenseListVersion_3_6
 
 instance Arbitrary LicenseRef where
     arbitrary = mkLicenseRef' <$> ids' <*> ids
@@ -149,7 +212,7 @@ instance Arbitrary LicenseExpression where
                 ]
               where
                 m = n `div` 2
-                arbA = arb m 
+                arbA = arb m
                 arbB = arb (n - m)
 
     shrink (EAnd a b) = a : b : map (uncurry EAnd) (shrink (a, b))
diff --git a/Cabal/tests/UnitTests/Distribution/Version.hs b/Cabal/tests/UnitTests/Distribution/Version.hs
index 5b382008adf4c3e34ee92554b8c6b4e024a042ed..f090997eba9c29e89b588320ef67f4206ad45919 100644
--- a/Cabal/tests/UnitTests/Distribution/Version.hs
+++ b/Cabal/tests/UnitTests/Distribution/Version.hs
@@ -9,6 +9,7 @@ import Distribution.Compat.Prelude.Internal
 import Prelude ()
 
 import Distribution.Version
+import Distribution.Types.VersionRange.Internal
 import Distribution.Parsec (simpleParsec)
 import Distribution.Pretty
 
@@ -69,7 +70,6 @@ versionTests =
     , typProperty prop_invertVersionRange
     , typProperty prop_withinVersion
     , typProperty prop_foldVersionRange
-    , typProperty prop_foldVersionRange'
 
       -- the semantic query functions
   --, typProperty prop_isAnyVersion1       --FIXME: runs out of test cases
@@ -344,19 +344,6 @@ prop_foldVersionRange range =
 
     upper = alterVersion $ \numbers -> init numbers ++ [last numbers + 1]
 
-prop_foldVersionRange' :: VersionRange -> Property
-prop_foldVersionRange' range =
-     normaliseVersionRange srange
-  === foldVersionRange' anyVersion thisVersion
-                       laterVersion earlierVersion
-                       orLaterVersion orEarlierVersion
-                       (\v _ -> withinVersion v)
-                       (\v _ -> majorBoundVersion v)
-                       unionVersionRanges intersectVersionRanges id
-                       srange
-  where
-    srange = stripParensVersionRange range
-
 prop_isAnyVersion1 :: VersionRange -> Version -> Property
 prop_isAnyVersion1 range version =
   isAnyVersion range ==> withinRange version range
@@ -750,21 +737,24 @@ prop_parse_disp5 vr =
 displayRaw :: VersionRange -> String
 displayRaw =
    Disp.render
- . foldVersionRange'                         -- precedence:
-     -- All the same as the usual pretty printer, except for the parens
-     (          Disp.text "-any")
-     (\v     -> Disp.text "==" <<>> pretty v)
-     (\v     -> Disp.char '>'  <<>> pretty v)
-     (\v     -> Disp.char '<'  <<>> pretty v)
-     (\v     -> Disp.text ">=" <<>> pretty v)
-     (\v     -> Disp.text "<=" <<>> pretty v)
-     (\v _   -> Disp.text "==" <<>> dispWild v)
-     (\v _   -> Disp.text "^>=" <<>> pretty v)
-     (\r1 r2 -> r1 <+> Disp.text "||" <+> r2)
-     (\r1 r2 -> r1 <+> Disp.text "&&" <+> r2)
-     (\r     -> Disp.parens r) -- parens
-
+ . cataVersionRange alg . normaliseVersionRange
   where
+
+    -- precedence:
+    -- All the same as the usual pretty printer, except for the parens
+    alg AnyVersionF                     = Disp.text "-any"
+    alg (ThisVersionF v)                = Disp.text "==" <<>> pretty v
+    alg (LaterVersionF v)               = Disp.char '>'  <<>> pretty v
+    alg (EarlierVersionF v)             = Disp.char '<'  <<>> pretty v
+    alg (OrLaterVersionF v)             = Disp.text ">=" <<>> pretty v
+    alg (OrEarlierVersionF v)           = Disp.text "<=" <<>> pretty v
+    alg (WildcardVersionF v)            = Disp.text "==" <<>> dispWild v
+    alg (MajorBoundVersionF v)          = Disp.text "^>=" <<>> pretty v
+    alg (UnionVersionRangesF r1 r2)     = r1 <+> Disp.text "||" <+> r2
+    alg (IntersectVersionRangesF r1 r2) = r1 <+> Disp.text "&&" <+> r2
+    alg (VersionRangeParensF r)         = Disp.parens r -- parens
+
+
     dispWild v =
            Disp.hcat (Disp.punctuate (Disp.char '.')
                                      (map Disp.int (versionNumbers v)))
diff --git a/Cabal/tests/custom-setup/CabalDoctestSetup.hs b/Cabal/tests/custom-setup/CabalDoctestSetup.hs
index 7e064ab2ed0f5dd89f52dd676a55f2a2166fa536..1e20f264c371e2bfb96bff4c36745a7f7d690af8 100644
--- a/Cabal/tests/custom-setup/CabalDoctestSetup.hs
+++ b/Cabal/tests/custom-setup/CabalDoctestSetup.hs
@@ -94,10 +94,6 @@ import qualified Data.Foldable as F
        (for_)
 import qualified Data.Traversable as T
        (traverse)
-import qualified Distribution.ModuleName as ModuleName
-       (fromString)
-import Distribution.ModuleName
-       (ModuleName)
 import Distribution.Package
        (InstalledPackageId)
 import Distribution.Package
@@ -107,8 +103,10 @@ import Distribution.PackageDescription
        PackageDescription (), TestSuite (..))
 import Distribution.Simple
        (UserHooks (..), autoconfUserHooks, defaultMainWithHooks, simpleUserHooks)
+#if !MIN_VERSION_Cabal(1,25,0)
 import Distribution.Simple.BuildPaths
        (autogenModulesDir)
+#endif
 import Distribution.Simple.Compiler
        (PackageDB (..), showCompilerId)
 import Distribution.Simple.LocalBuildInfo
@@ -117,11 +115,11 @@ import Distribution.Simple.LocalBuildInfo
 import Distribution.Simple.Setup
        (BuildFlags (buildDistPref, buildVerbosity), fromFlag)
 import Distribution.Simple.Utils
-       (createDirectoryIfMissingVerbose, findFile, rewriteFile)
+       (createDirectoryIfMissingVerbose)
 import Distribution.Text
        (display, simpleParse)
 import System.FilePath
-       ((</>), (<.>), dropExtension)
+       ((</>))
 
 import Data.IORef (newIORef, modifyIORef, readIORef)
 
@@ -136,6 +134,14 @@ import Distribution.Types.UnqualComponentName
        (unUnqualComponentName)
 #endif
 
+#if MIN_VERSION_Cabal(3,0,0)
+import Distribution.Simple.Utils
+       (findFileEx)
+#else
+import Distribution.Simple.Utils
+       (findFile)
+#endif
+
 #if MIN_VERSION_Cabal(2,5,0)
 import Distribution.Types.LibraryName
        (libraryNameString)
@@ -157,6 +163,15 @@ makeAbsolute p | isAbsolute p = return p
     return $ cwd </> p
 #endif
 
+#if !MIN_VERSION_Cabal(3,0,0)
+findFileEx :: Verbosity
+           -> [FilePath]    -- ^search locations
+           -> FilePath      -- ^File Name
+           -> IO FilePath
+findFileEx _verbosity = findFile
+#endif
+
+
 -- | A default main with doctests:
 --
 -- @
@@ -328,7 +343,7 @@ generateBuildModule testSuiteName flags pkg lbi = do
            -- even though the main-is module is named Main, its filepath might
            -- actually be Something.hs. To account for this possibility, we simply
            -- pass the full path to the main-is module instead.
-           mainIsPath <- T.traverse (findFile iArgsNoPrefix) (compMainIs comp)
+           mainIsPath <- T.traverse (findFileEx verbosity iArgsNoPrefix) (compMainIs comp)
 
            let all_sources = map display module_sources
                              ++ additionalModules
@@ -356,7 +371,7 @@ generateBuildModule testSuiteName flags pkg lbi = do
     getBuildDoctests withExeLBI (NameExe . executableName) (const [])     (Just . modulePath) buildInfo
 
     components <- readIORef componentsRef
-    F.for_ components $ \(Component name pkgs flags sources) -> do
+    F.for_ components $ \(Component name pkgs flags' sources) -> do
        let compSuffix          = nameToString name
            pkgs_comp           = "pkgs"           ++ compSuffix
            flags_comp          = "flags"          ++ compSuffix
@@ -369,7 +384,7 @@ generateBuildModule testSuiteName flags pkg lbi = do
          , pkgs_comp ++ " = " ++ show pkgs
          , ""
          , flags_comp ++ " :: [String]"
-         , flags_comp ++ " = " ++ show flags
+         , flags_comp ++ " = " ++ show flags'
          , ""
          , module_sources_comp ++ " :: [String]"
          , module_sources_comp ++ " = " ++ show sources
diff --git a/Cabal/tests/custom-setup/IdrisSetup.hs b/Cabal/tests/custom-setup/IdrisSetup.hs
index b26b0038c7d1d21f2f48ab815e089b4469fcf58d..04ad4cd6aed8e0a2996d5d280ca013d3a73b535e 100644
--- a/Cabal/tests/custom-setup/IdrisSetup.hs
+++ b/Cabal/tests/custom-setup/IdrisSetup.hs
@@ -38,7 +38,7 @@ IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 -}
 
 {-# LANGUAGE CPP #-}
-{-# OPTIONS_GHC -fno-warn-deprecations #-}
+{-# OPTIONS_GHC -w #-}
 module IdrisSetup (main) where
 
 #if !defined(MIN_VERSION_Cabal)
@@ -60,7 +60,8 @@ import Distribution.Simple.InstallDirs as I
 import Distribution.Simple.LocalBuildInfo as L
 import qualified Distribution.Simple.Setup as S
 import qualified Distribution.Simple.Program as P
-import Distribution.Simple.Utils (createDirectoryIfMissingVerbose, rewriteFile, notice, installOrdinaryFiles)
+import Distribution.Simple.Utils (createDirectoryIfMissingVerbose, notice, installOrdinaryFiles)
+import Distribution.Simple.Utils (rewriteFileEx)
 import Distribution.Compiler
 import Distribution.PackageDescription
 import Distribution.Text
@@ -177,7 +178,7 @@ generateVersionModule verbosity dir release = do
     putStrLn $ "Generating " ++ versionModulePath ++
              if release then " for release" else " for prerelease " ++ hash
     createDirectoryIfMissingVerbose verbosity True dir
-    rewriteFile versionModulePath (versionModuleContents hash)
+    rewriteFileEx verbosity versionModulePath (versionModuleContents hash)
 
   where versionModuleContents h = "module Version_idris where\n\n" ++
                                   "gitHash :: String\n" ++
@@ -191,7 +192,7 @@ generateTargetModule verbosity dir targetDir = do
     let targetModulePath = dir </> "Target_idris" Px.<.> "hs"
     putStrLn $ "Generating " ++ targetModulePath
     createDirectoryIfMissingVerbose verbosity True dir
-    rewriteFile targetModulePath (versionModuleContents absPath targetDir)
+    rewriteFileEx verbosity targetModulePath (versionModuleContents absPath targetDir)
             where versionModuleContents absolute td = "module Target_idris where\n\n" ++
                                     "import System.FilePath\n" ++
                                     "import System.Environment\n" ++
@@ -217,7 +218,7 @@ generateToolchainModule verbosity srcDir toolDir = do
                                    "getToolchainDir = \"\""
     let toolPath = srcDir </> "Tools_idris" Px.<.> "hs"
     createDirectoryIfMissingVerbose verbosity True srcDir
-    rewriteFile toolPath (commonContent ++ toolContent)
+    rewriteFileEx verbosity toolPath (commonContent ++ toolContent)
 
 idrisConfigure _ flags pkgdesc local = do
     configureRTS
@@ -249,6 +250,7 @@ idrisConfigure _ flags pkgdesc local = do
       autogenComponentModulesDir lbi _ = autogenModulesDir lbi
 #endif
 
+#if !MIN_VERSION_Cabal(3,0,0)
 idrisPreSDist args flags = do
   let dir = S.fromFlag (S.sDistDirectory flags)
   let verb = S.fromFlag (S.sDistVerbosity flags)
@@ -277,6 +279,7 @@ idrisPostSDist args flags desc lbi = do
                               removeFile targetFile)
              (\e -> let e' = (e :: SomeException) in return ())
   postSDist simpleUserHooks args flags desc lbi
+#endif
 
 -- -----------------------------------------------------------------------------
 -- Build
@@ -376,8 +379,10 @@ main = defaultMainWithHooks $ simpleUserHooks
    , postInst = \_ flags pkg local ->
                   idrisInstall (S.fromFlag $ S.installVerbosity flags)
                                NoCopyDest pkg local
+#if !MIN_VERSION_Cabal(3,0,0)
    , preSDist = idrisPreSDist
    , sDistHook = idrisSDist (sDistHook simpleUserHooks)
    , postSDist = idrisPostSDist
+#endif
    , testHook = idrisTestHook
    }
diff --git a/Makefile b/Makefile
index 920a0cb65984e823ace6f9578661ad15b86306bc..2dcf46e8778bc04bb7fde5ec445e92f722756bc8 100644
--- a/Makefile
+++ b/Makefile
@@ -33,10 +33,10 @@ $(LEXER_HS) : boot/Lexer.x
 spdx : $(SPDX_LICENSE_HS) $(SPDX_EXCEPTION_HS)
 
 $(SPDX_LICENSE_HS) : boot/SPDX.LicenseId.template.hs cabal-dev-scripts/src/GenUtils.hs cabal-dev-scripts/src/GenSPDX.hs license-list-data/licenses-3.0.json license-list-data/licenses-3.2.json
-	cabal new-run --builddir=dist-newstyle-meta --project-file=cabal.project.meta gen-spdx -- boot/SPDX.LicenseId.template.hs license-list-data/licenses-3.0.json license-list-data/licenses-3.2.json license-list-data/licenses-3.5.json $(SPDX_LICENSE_HS)
+	cabal new-run --builddir=dist-newstyle-meta --project-file=cabal.project.meta gen-spdx -- boot/SPDX.LicenseId.template.hs license-list-data/licenses-3.0.json license-list-data/licenses-3.2.json license-list-data/licenses-3.6.json $(SPDX_LICENSE_HS)
 
 $(SPDX_EXCEPTION_HS) : boot/SPDX.LicenseExceptionId.template.hs cabal-dev-scripts/src/GenUtils.hs cabal-dev-scripts/src/GenSPDXExc.hs license-list-data/exceptions-3.0.json license-list-data/exceptions-3.2.json
-	cabal new-run --builddir=dist-newstyle-meta --project-file=cabal.project.meta gen-spdx-exc -- boot/SPDX.LicenseExceptionId.template.hs license-list-data/exceptions-3.0.json license-list-data/exceptions-3.2.json license-list-data/exceptions-3.5.json $(SPDX_EXCEPTION_HS)
+	cabal new-run --builddir=dist-newstyle-meta --project-file=cabal.project.meta gen-spdx-exc -- boot/SPDX.LicenseExceptionId.template.hs license-list-data/exceptions-3.0.json license-list-data/exceptions-3.2.json license-list-data/exceptions-3.6.json $(SPDX_EXCEPTION_HS)
 
 # cabal-install.cabal file generation
 
diff --git a/appveyor.yml b/appveyor.yml
index 9c8703478c2984e8a2d4d434b87288cfb271f087..0a9bbb4f0127ccdf81703fed471ded9312b91a3b 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -3,6 +3,7 @@
 branches:
   only:
     - master
+    - "3.0"
     - "2.4"    
     - "2.2"
     - "2.0"
@@ -47,7 +48,7 @@ build_script:
   - cabal %CABOPTS% new-test Cabal
   - appveyor-retry cabal %CABOPTS% new-build exe:cabal exe:cabal-tests --only-dependencies
   - cabal %CABOPTS% new-build exe:cabal
-  - cabal %CABOPTS% new-run cabal-tests -- -j3 --with-cabal=dist-newstyle\build\x86_64-windows\ghc-8.0.2\cabal-install-3.0.0.0\x\cabal\build\cabal\cabal.exe
+  - cabal %CABOPTS% new-run cabal-tests -- -j3 --with-cabal=dist-newstyle\build\x86_64-windows\ghc-8.0.2\cabal-install-3.1.0.0\x\cabal\build\cabal\cabal.exe
   - appveyor-retry cabal %CABOPTS% new-build cabal-install:tests --only-dependencies
   - cd cabal-install
   - cabal %CABOPTS% new-run cabal-install:memory-usage-tests
diff --git a/boot/SPDX.LicenseExceptionId.template.hs b/boot/SPDX.LicenseExceptionId.template.hs
index b5b1113c68f3dbaac8ca60971b0791345b07e1a1..38f61b493a557815701a6ad0daf267738a446286 100644
--- a/boot/SPDX.LicenseExceptionId.template.hs
+++ b/boot/SPDX.LicenseExceptionId.template.hs
@@ -16,6 +16,8 @@ import Distribution.Parsec
 import Distribution.Utils.Generic (isAsciiAlphaNum)
 import Distribution.SPDX.LicenseListVersion
 
+import qualified Data.Binary.Get as Binary
+import qualified Data.Binary.Put as Binary
 import qualified Data.Map.Strict as Map
 import qualified Distribution.Compat.CharParsing as P
 import qualified Text.PrettyPrint as Disp
@@ -29,7 +31,13 @@ data LicenseExceptionId
 {{{ licenseIds }}}
   deriving (Eq, Ord, Enum, Bounded, Show, Read, Typeable, Data, Generic)
 
-instance Binary LicenseExceptionId
+instance Binary LicenseExceptionId where
+    put = Binary.putWord8 . fromIntegral . fromEnum
+    get = do
+        i <- Binary.getWord8
+        if i > fromIntegral (fromEnum (maxBound :: LicenseExceptionId))
+        then fail "Too large LicenseExceptionId tag"
+        else return (toEnum (fromIntegral i))
 
 instance Pretty LicenseExceptionId where
     pretty = Disp.text . licenseExceptionId
@@ -71,15 +79,15 @@ licenseExceptionIdList LicenseListVersion_3_0 =
 licenseExceptionIdList LicenseListVersion_3_2 =
 {{{licenseList_3_2}}}
     ++ bulkOfLicenses
-licenseExceptionIdList LicenseListVersion_3_5 =
-{{{licenseList_3_5}}}
+licenseExceptionIdList LicenseListVersion_3_6 =
+{{{licenseList_3_6}}}
     ++ bulkOfLicenses
 
 -- | Create a 'LicenseExceptionId' from a 'String'.
 mkLicenseExceptionId :: LicenseListVersion -> String -> Maybe LicenseExceptionId
 mkLicenseExceptionId LicenseListVersion_3_0 s = Map.lookup s stringLookup_3_0
 mkLicenseExceptionId LicenseListVersion_3_2 s = Map.lookup s stringLookup_3_2
-mkLicenseExceptionId LicenseListVersion_3_5 s = Map.lookup s stringLookup_3_5
+mkLicenseExceptionId LicenseListVersion_3_6 s = Map.lookup s stringLookup_3_6
 
 stringLookup_3_0 :: Map String LicenseExceptionId
 stringLookup_3_0 = Map.fromList $ map (\i -> (licenseExceptionId i, i)) $
@@ -89,9 +97,9 @@ stringLookup_3_2 :: Map String LicenseExceptionId
 stringLookup_3_2 = Map.fromList $ map (\i -> (licenseExceptionId i, i)) $
     licenseExceptionIdList LicenseListVersion_3_2
 
-stringLookup_3_5 :: Map String LicenseExceptionId
-stringLookup_3_5 = Map.fromList $ map (\i -> (licenseExceptionId i, i)) $
-    licenseExceptionIdList LicenseListVersion_3_5
+stringLookup_3_6 :: Map String LicenseExceptionId
+stringLookup_3_6 = Map.fromList $ map (\i -> (licenseExceptionId i, i)) $
+    licenseExceptionIdList LicenseListVersion_3_6
 
 --  | License exceptions in all SPDX License lists
 bulkOfLicenses :: [LicenseExceptionId]
diff --git a/boot/SPDX.LicenseId.template.hs b/boot/SPDX.LicenseId.template.hs
index 7c86beee6b15fa140f377f93d2647bb25c0c1b37..61555fc38db65ebac5aa8fde30f03e94c1970ad6 100644
--- a/boot/SPDX.LicenseId.template.hs
+++ b/boot/SPDX.LicenseId.template.hs
@@ -19,6 +19,8 @@ import Distribution.Parsec
 import Distribution.Utils.Generic (isAsciiAlphaNum)
 import Distribution.SPDX.LicenseListVersion
 
+import qualified Data.Binary.Get as Binary
+import qualified Data.Binary.Put as Binary
 import qualified Data.Map.Strict as Map
 import qualified Distribution.Compat.CharParsing as P
 import qualified Text.PrettyPrint as Disp
@@ -32,7 +34,15 @@ data LicenseId
 {{{ licenseIds }}}
   deriving (Eq, Ord, Enum, Bounded, Show, Read, Typeable, Data, Generic)
 
-instance Binary LicenseId
+instance Binary LicenseId where
+    -- Word16 is encoded in big endianess
+    -- https://github.com/kolmodin/binary/blob/master/src/Data/Binary/Class.hs#L220-LL227
+    put = Binary.putWord16be . fromIntegral . fromEnum
+    get = do
+        i <- Binary.getWord16be
+        if i > fromIntegral (fromEnum (maxBound :: LicenseId))
+        then fail "Too large LicenseId tag"
+        else return (toEnum (fromIntegral i))
 
 instance Pretty LicenseId where
     pretty = Disp.text . licenseId
@@ -129,15 +139,15 @@ licenseIdList LicenseListVersion_3_0 =
 licenseIdList LicenseListVersion_3_2 =
 {{{licenseList_3_2}}}
     ++ bulkOfLicenses
-licenseIdList LicenseListVersion_3_5 =
-{{{licenseList_3_5}}}
+licenseIdList LicenseListVersion_3_6 =
+{{{licenseList_3_6}}}
     ++ bulkOfLicenses
 
 -- | Create a 'LicenseId' from a 'String'.
 mkLicenseId :: LicenseListVersion -> String -> Maybe LicenseId
 mkLicenseId LicenseListVersion_3_0 s = Map.lookup s stringLookup_3_0
 mkLicenseId LicenseListVersion_3_2 s = Map.lookup s stringLookup_3_2
-mkLicenseId LicenseListVersion_3_5 s = Map.lookup s stringLookup_3_5
+mkLicenseId LicenseListVersion_3_6 s = Map.lookup s stringLookup_3_6
 
 stringLookup_3_0 :: Map String LicenseId
 stringLookup_3_0 = Map.fromList $ map (\i -> (licenseId i, i)) $
@@ -147,9 +157,9 @@ stringLookup_3_2 :: Map String LicenseId
 stringLookup_3_2 = Map.fromList $ map (\i -> (licenseId i, i)) $
     licenseIdList LicenseListVersion_3_2
 
-stringLookup_3_5 :: Map String LicenseId
-stringLookup_3_5 = Map.fromList $ map (\i -> (licenseId i, i)) $
-    licenseIdList LicenseListVersion_3_5
+stringLookup_3_6 :: Map String LicenseId
+stringLookup_3_6 = Map.fromList $ map (\i -> (licenseId i, i)) $
+    licenseIdList LicenseListVersion_3_6
 
 --  | Licenses in all SPDX License lists
 bulkOfLicenses :: [LicenseId]
diff --git a/cabal-dev-scripts/src/GenSPDX.hs b/cabal-dev-scripts/src/GenSPDX.hs
index f2eb64ffe38142c286fa74c9a23ac0e0eea35e8d..e7b13c0d1539d1d1ae661fead2cd72c33a4ad33e 100644
--- a/cabal-dev-scripts/src/GenSPDX.hs
+++ b/cabal-dev-scripts/src/GenSPDX.hs
@@ -72,17 +72,17 @@ generate' lss template = M.renderMustacheW template $ object
         (\vers -> vers /= allVers && Set.member SPDXLicenseListVersion_3_0 vers)
     , "licenseList_3_2" .= mkLicenseList
         (\vers -> vers /= allVers && Set.member SPDXLicenseListVersion_3_2 vers)
-    , "licenseList_3_5" .= mkLicenseList
-        (\vers -> vers /= allVers && Set.member SPDXLicenseListVersion_3_5 vers)
+    , "licenseList_3_6" .= mkLicenseList
+        (\vers -> vers /= allVers && Set.member SPDXLicenseListVersion_3_6 vers)
     ]
   where
-    PerV (LL ls_3_0) (LL ls_3_2) (LL ls_3_5) = lss
+    PerV (LL ls_3_0) (LL ls_3_2) (LL ls_3_6) = lss
 
     constructorNames :: [(Text, License, Set.Set SPDXLicenseListVersion)]
     constructorNames
         = map (\(l, tags) -> (toConstructorName $ licenseId l, l, tags))
         $ combine licenseId $ \ver -> case ver of
-            SPDXLicenseListVersion_3_5 -> filterDeprecated ls_3_5
+            SPDXLicenseListVersion_3_6 -> filterDeprecated ls_3_6
             SPDXLicenseListVersion_3_2 -> filterDeprecated ls_3_2
             SPDXLicenseListVersion_3_0 -> filterDeprecated ls_3_0
 
diff --git a/cabal-dev-scripts/src/GenSPDXExc.hs b/cabal-dev-scripts/src/GenSPDXExc.hs
index ecf9d48e0a6ce35a95546bdb5511472511eb09e8..a267e922e1be6d6bec10808f6c74692657a279dd 100644
--- a/cabal-dev-scripts/src/GenSPDXExc.hs
+++ b/cabal-dev-scripts/src/GenSPDXExc.hs
@@ -72,17 +72,17 @@ generate' lss template = M.renderMustacheW template $ object
         (\vers -> vers /= allVers && Set.member SPDXLicenseListVersion_3_0 vers)
     , "licenseList_3_2" .= mkLicenseList
         (\vers -> vers /= allVers && Set.member SPDXLicenseListVersion_3_2 vers)
-    , "licenseList_3_5" .= mkLicenseList
-        (\vers -> vers /= allVers && Set.member SPDXLicenseListVersion_3_5 vers)
+    , "licenseList_3_6" .= mkLicenseList
+        (\vers -> vers /= allVers && Set.member SPDXLicenseListVersion_3_6 vers)
     ]
   where
-    PerV (LL ls_3_0) (LL ls_3_2) (LL ls_3_5) = lss
+    PerV (LL ls_3_0) (LL ls_3_2) (LL ls_3_6) = lss
 
     constructorNames :: [(Text, License, Set.Set SPDXLicenseListVersion)]
     constructorNames
         = map (\(l, tags) -> (toConstructorName $ licenseId l, l, tags))
         $ combine licenseId $ \ver -> case ver of
-            SPDXLicenseListVersion_3_5 -> filterDeprecated ls_3_5
+            SPDXLicenseListVersion_3_6 -> filterDeprecated ls_3_6
             SPDXLicenseListVersion_3_2 -> filterDeprecated ls_3_2
             SPDXLicenseListVersion_3_0 -> filterDeprecated ls_3_0
 
diff --git a/cabal-dev-scripts/src/GenUtils.hs b/cabal-dev-scripts/src/GenUtils.hs
index 866ca2643416af4e24c384e74de29dd8e5b8f0df..e3cee13eab05798783a4b4ea4ee2bdcd9aa14a8b 100644
--- a/cabal-dev-scripts/src/GenUtils.hs
+++ b/cabal-dev-scripts/src/GenUtils.hs
@@ -24,14 +24,14 @@ import qualified Data.Text.Lazy      as TL
 data SPDXLicenseListVersion
     = SPDXLicenseListVersion_3_0
     | SPDXLicenseListVersion_3_2
-    | SPDXLicenseListVersion_3_5
+    | SPDXLicenseListVersion_3_6
   deriving (Eq, Ord, Show, Enum, Bounded)
 
 allVers :: Set.Set SPDXLicenseListVersion
 allVers =  Set.fromList [minBound .. maxBound]
 
 prettyVer :: SPDXLicenseListVersion -> Text
-prettyVer SPDXLicenseListVersion_3_5 = "SPDX License List 3.5"
+prettyVer SPDXLicenseListVersion_3_6 = "SPDX License List 3.6"
 prettyVer SPDXLicenseListVersion_3_2 = "SPDX License List 3.2"
 prettyVer SPDXLicenseListVersion_3_0 = "SPDX License List 3.0"
 
diff --git a/cabal-install/Distribution/Client/CmdBench.hs b/cabal-install/Distribution/Client/CmdBench.hs
index c07f5be3890f9742f1a2fbc5b9f017e49214b03a..bb38b91976874092f03e9e12d3282969e56df1b4 100644
--- a/cabal-install/Distribution/Client/CmdBench.hs
+++ b/cabal-install/Distribution/Client/CmdBench.hs
@@ -78,7 +78,7 @@ benchAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags, TestFlag
 benchAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags)
             targetStrings globalFlags = do
 
-    baseCtx <- establishProjectBaseContext verbosity cliConfig
+    baseCtx <- establishProjectBaseContext verbosity cliConfig OtherCommand
 
     targetSelectors <- either (reportTargetSelectorProblems verbosity) return
                    =<< readTargetSelectors (localPackages baseCtx) (Just BenchKind) targetStrings
diff --git a/cabal-install/Distribution/Client/CmdBuild.hs b/cabal-install/Distribution/Client/CmdBuild.hs
index cb1858837a4b29e656c47562aba99ff9049764b8..d4123b42ef50b15af3cf7497502287328ee3449d 100644
--- a/cabal-install/Distribution/Client/CmdBuild.hs
+++ b/cabal-install/Distribution/Client/CmdBuild.hs
@@ -116,7 +116,7 @@ buildAction
             | onlyConfigure = TargetActionConfigure
             | otherwise = TargetActionBuild
 
-    baseCtx <- establishProjectBaseContext verbosity cliConfig
+    baseCtx <- establishProjectBaseContext verbosity cliConfig OtherCommand
 
     targetSelectors <-
       either (reportTargetSelectorProblems verbosity) return
diff --git a/cabal-install/Distribution/Client/CmdConfigure.hs b/cabal-install/Distribution/Client/CmdConfigure.hs
index 7953167cdcbfd12ca1fb19c8841bfcd049523058..ff76847c93e3dcf3ff37a4158a72042337825378 100644
--- a/cabal-install/Distribution/Client/CmdConfigure.hs
+++ b/cabal-install/Distribution/Client/CmdConfigure.hs
@@ -84,7 +84,7 @@ configureAction (configFlags, configExFlags, installFlags, haddockFlags, testFla
                 _extraArgs globalFlags = do
     --TODO: deal with _extraArgs, since flags with wrong syntax end up there
 
-    baseCtx <- establishProjectBaseContext verbosity cliConfig
+    baseCtx <- establishProjectBaseContext verbosity cliConfig OtherCommand
 
     -- Write out the @cabal.project.local@ so it gets picked up by the
     -- planning phase. If old config exists, then print the contents
diff --git a/cabal-install/Distribution/Client/CmdErrorMessages.hs b/cabal-install/Distribution/Client/CmdErrorMessages.hs
index 6285e26637d9e7c6344054b94e8bfe4bc809242e..6d15652190cf82ba37101f0b5a0046acc7e95718 100644
--- a/cabal-install/Distribution/Client/CmdErrorMessages.hs
+++ b/cabal-install/Distribution/Client/CmdErrorMessages.hs
@@ -305,6 +305,8 @@ renderTargetProblemNoneEnabled verb targetSelector targets =
          ++ plural (listPlural targets') " is " " are "
          ++ "not available because the solver did not find a plan that "
          ++ "included the " ++ renderOptionalStanza Plural stanza
+         ++ ". Force the solver to enable this for all packages by adding the "
+         ++ "line 'tests: True' to the 'cabal.project.local' file."
         (TargetNotBuildable, _) ->
             renderListCommaAnd
               [ "the " ++ showComponentName availableTargetComponentName
diff --git a/cabal-install/Distribution/Client/CmdExec.hs b/cabal-install/Distribution/Client/CmdExec.hs
index 596337250faffb16812aa6a3e6e11a04421504f2..e576e108c21b160e45c612406ef39f93b7919761 100644
--- a/cabal-install/Distribution/Client/CmdExec.hs
+++ b/cabal-install/Distribution/Client/CmdExec.hs
@@ -31,6 +31,7 @@ import qualified Distribution.Client.Setup as Client
 import Distribution.Client.ProjectOrchestration
   ( ProjectBuildContext(..)
   , runProjectPreBuildPhase
+  , CurrentCommand(..)
   , establishProjectBaseContext
   , distDirLayout
   , commandLineFlagsToProjectConfig
@@ -125,7 +126,7 @@ execAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags, TestFlags
 execAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags)
            extraArgs globalFlags = do
 
-  baseCtx <- establishProjectBaseContext verbosity cliConfig
+  baseCtx <- establishProjectBaseContext verbosity cliConfig OtherCommand
 
   -- To set up the environment, we'd like to select the libraries in our
   -- dependency tree that we've already built. So first we set up an install
diff --git a/cabal-install/Distribution/Client/CmdFreeze.hs b/cabal-install/Distribution/Client/CmdFreeze.hs
index f8328dd70defcd1ff25172e33f81fd1fbdb35dd8..e4b5e22531f8c9ad250cffec41c98e69c66b75af 100644
--- a/cabal-install/Distribution/Client/CmdFreeze.hs
+++ b/cabal-install/Distribution/Client/CmdFreeze.hs
@@ -113,7 +113,7 @@ freezeAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags)
       cabalDirLayout,
       projectConfig,
       localPackages
-    } <- establishProjectBaseContext verbosity cliConfig
+    } <- establishProjectBaseContext verbosity cliConfig OtherCommand
 
     (_, elaboratedPlan, _) <-
       rebuildInstallPlan verbosity
diff --git a/cabal-install/Distribution/Client/CmdHaddock.hs b/cabal-install/Distribution/Client/CmdHaddock.hs
index 2670cda5e0460a84089249422297ad593fae3706..0ed1aca2a200379d67f445edc76ec02c60f21b84 100644
--- a/cabal-install/Distribution/Client/CmdHaddock.hs
+++ b/cabal-install/Distribution/Client/CmdHaddock.hs
@@ -74,7 +74,7 @@ haddockAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags, TestFl
 haddockAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags)
                 targetStrings globalFlags = do
 
-    baseCtx <- establishProjectBaseContext verbosity cliConfig
+    baseCtx <- establishProjectBaseContext verbosity cliConfig HaddockCommand
 
     targetSelectors <- either (reportTargetSelectorProblems verbosity) return
                    =<< readTargetSelectors (localPackages baseCtx) Nothing targetStrings
diff --git a/cabal-install/Distribution/Client/CmdInstall.hs b/cabal-install/Distribution/Client/CmdInstall.hs
index 687eee9f778cafa34158053da28ec31cf3f91caa..bbd18c8eb657aa0e96673ac76e0251407bdd4325 100644
--- a/cabal-install/Distribution/Client/CmdInstall.hs
+++ b/cabal-install/Distribution/Client/CmdInstall.hs
@@ -1,8 +1,8 @@
-{-# LANGUAGE LambdaCase #-}
-{-# LANGUAGE NamedFieldPuns #-}
-{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE NamedFieldPuns      #-}
+{-# LANGUAGE RecordWildCards     #-}
 {-# LANGUAGE ScopedTypeVariables #-}
-{-# LANGUAGE ViewPatterns #-}
+{-# LANGUAGE ViewPatterns        #-}
 
 -- | cabal-install CLI command: build
 --
@@ -178,7 +178,8 @@ installCommand = CommandUI
         (filter ((`notElem` ["constraint", "dependency"
                             , "exact-configuration"])
                  . optionName) $ configureOptions showOrParseArgs)
-     ++ liftOptions get2 set2 (configureExOptions showOrParseArgs ConstraintSourceCommandlineFlag)
+     ++ liftOptions get2 set2 (configureExOptions showOrParseArgs
+                               ConstraintSourceCommandlineFlag)
      ++ liftOptions get3 set3
         -- hide "target-package-db" and "symlink-bindir" flags from the
         -- install options.
@@ -194,7 +195,8 @@ installCommand = CommandUI
                                 haddockOptions showOrParseArgs)
      ++ liftOptions get5 set5 (testOptions showOrParseArgs)
      ++ liftOptions get6 set6 (clientInstallOptions showOrParseArgs)
-  , commandDefaultFlags = (mempty, mempty, mempty, mempty, mempty, defaultClientInstallFlags)
+  , commandDefaultFlags = ( mempty, mempty, mempty, mempty, mempty
+                          , defaultClientInstallFlags )
   }
   where
     get1 (a,_,_,_,_,_) = a; set1 a (_,b,c,d,e,f) = (a,b,c,d,e,f)
@@ -222,10 +224,14 @@ installCommand = CommandUI
 -- For more details on how this works, see the module
 -- "Distribution.Client.ProjectOrchestration"
 --
-installAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags, TestFlags, ClientInstallFlags)
-            -> [String] -> GlobalFlags -> IO ()
-installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags, clientInstallFlags')
-            targetStrings globalFlags = do
+installAction
+  :: ( ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags, TestFlags
+     , ClientInstallFlags)
+  -> [String] -> GlobalFlags
+  -> IO ()
+installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
+              , clientInstallFlags' )
+              targetStrings globalFlags = do
   -- We never try to build tests/benchmarks for remote packages.
   -- So we set them as disabled by default and error if they are explicitly
   -- enabled.
@@ -245,34 +251,48 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
     pure $ savedClientInstallFlags savedConfig `mappend` clientInstallFlags'
 
   let
+    installLibs    = fromFlagOrDefault False (cinstInstallLibs clientInstallFlags)
+    targetFilter   = if installLibs then Just LibKind else Just ExeKind
+    targetStrings' = if null targetStrings then ["."] else targetStrings
+
     withProject = do
       let verbosity' = lessVerbose verbosity
 
       -- First, we need to learn about what's available to be installed.
-      localBaseCtx <- establishProjectBaseContext verbosity' cliConfig
+      localBaseCtx <- establishProjectBaseContext verbosity'
+                      cliConfig InstallCommand
       let localDistDirLayout = distDirLayout localBaseCtx
-      pkgDb <- projectConfigWithBuilderRepoContext verbosity' (buildSettings localBaseCtx) (getSourcePackages verbosity)
+      pkgDb <- projectConfigWithBuilderRepoContext verbosity'
+               (buildSettings localBaseCtx) (getSourcePackages verbosity)
 
       let
-        (targetStrings', packageIds) = partitionEithers . flip fmap targetStrings $
+        (targetStrings'', packageIds) =
+          partitionEithers .
+          flip fmap targetStrings' $
           \str -> case simpleParse str of
             Just (pkgId :: PackageId)
               | pkgVersion pkgId /= nullVersion -> Right pkgId
-            _ -> Left str
-        packageSpecifiers = flip fmap packageIds $ \case
+            _                                   -> Left str
+        packageSpecifiers =
+          flip fmap packageIds $ \case
           PackageIdentifier{..}
             | pkgVersion == nullVersion -> NamedPackage pkgName []
-            | otherwise ->
-              NamedPackage pkgName [PackagePropertyVersion (thisVersion pkgVersion)]
-        packageTargets = flip TargetPackageNamed Nothing . pkgName <$> packageIds
+            | otherwise                 -> NamedPackage pkgName
+                                           [PackagePropertyVersion
+                                            (thisVersion pkgVersion)]
+        packageTargets =
+          flip TargetPackageNamed targetFilter . pkgName <$> packageIds
 
       if null targetStrings'
         then return (packageSpecifiers, packageTargets, projectConfig localBaseCtx)
         else do
-          targetSelectors <- either (reportTargetSelectorProblems verbosity) return
-                        =<< readTargetSelectors (localPackages localBaseCtx) Nothing targetStrings'
+          targetSelectors <-
+            either (reportTargetSelectorProblems verbosity) return
+            =<< readTargetSelectors (localPackages localBaseCtx)
+                                    Nothing targetStrings''
 
-          (specs, selectors) <- withInstallPlan verbosity' localBaseCtx $ \elaboratedPlan _ -> do
+          (specs, selectors) <-
+            withInstallPlan verbosity' localBaseCtx $ \elaboratedPlan _ -> do
             -- Split into known targets and hackage packages.
             (targets, hackageNames) <- case
               resolveTargets
@@ -282,10 +302,10 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
                 elaboratedPlan
                 (Just pkgDb)
                 targetSelectors of
-              Right targets -> do
+              Right targets ->
                 -- Everything is a local dependency.
                 return (targets, [])
-              Left errs -> do
+              Left errs     -> do
                 -- Not everything is local.
                 let
                   (errs', hackageNames) = partitionEithers . flip fmap errs $ \case
@@ -312,10 +332,13 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
                       | name `elem` hackageNames -> False
                     TargetPackageNamed name _
                       | name `elem` hackageNames -> False
-                    _ -> True
+                    _                            -> True
 
-                -- This can't fail, because all of the errors are removed (or we've given up).
-                targets <- either (reportTargetProblems verbosity) return $ resolveTargets
+                -- This can't fail, because all of the errors are
+                -- removed (or we've given up).
+                targets <-
+                  either (reportTargetProblems verbosity) return $
+                  resolveTargets
                     selectPackageTargets
                     selectComponentTarget
                     TargetProblemCommon
@@ -329,7 +352,8 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
               planMap = InstallPlan.toMap elaboratedPlan
               targetIds = Map.keys targets
 
-              sdistize (SpecificSourcePackage spkg@SourcePackage{..}) = SpecificSourcePackage spkg'
+              sdistize (SpecificSourcePackage spkg@SourcePackage{..}) =
+                SpecificSourcePackage spkg'
                 where
                   sdistPath = distSdistFile localDistDirLayout packageInfoId
                   spkg' = spkg { packageSource = LocalTarballPackage sdistPath }
@@ -338,7 +362,7 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
               local = sdistize <$> localPackages localBaseCtx
 
               gatherTargets :: UnitId -> TargetSelector
-              gatherTargets targetId = TargetPackageNamed pkgName Nothing
+              gatherTargets targetId = TargetPackageNamed pkgName targetFilter
                 where
                   Just targetUnit = Map.lookup targetId planMap
                   PackageIdentifier{..} = packageId targetUnit
@@ -347,8 +371,10 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
 
               hackagePkgs :: [PackageSpecifier UnresolvedSourcePackage]
               hackagePkgs = flip NamedPackage [] <$> hackageNames
+
               hackageTargets :: [TargetSelector]
-              hackageTargets = flip TargetPackageNamed Nothing <$> hackageNames
+              hackageTargets =
+                flip TargetPackageNamed targetFilter <$> hackageNames
 
             createDirectoryIfMissing True (distSdistDirectory localDistDirLayout)
 
@@ -363,14 +389,16 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
               then return (hackagePkgs, hackageTargets)
               else return (local ++ hackagePkgs, targets' ++ hackageTargets)
 
-          return (specs ++ packageSpecifiers, selectors ++ packageTargets, projectConfig localBaseCtx)
+          return ( specs ++ packageSpecifiers
+                 , selectors ++ packageTargets
+                 , projectConfig localBaseCtx )
 
     withoutProject globalConfig = do
       let
         parsePkg pkgName
           | Just (pkg :: PackageId) <- simpleParse pkgName = return pkg
           | otherwise = die' verbosity ("Invalid package ID: " ++ pkgName)
-      packageIds <- mapM parsePkg targetStrings
+      packageIds <- mapM parsePkg targetStrings'
 
       cabalDir <- getCabalDir
       let
@@ -396,7 +424,7 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
                                             verbosity buildSettings
                                             (getSourcePackages verbosity)
 
-      for_ targetStrings $ \case
+      for_ targetStrings' $ \case
             name
               | null (lookupPackageName packageIndex (mkPackageName name))
               , xs@(_:_) <- searchByName packageIndex name ->
@@ -411,13 +439,15 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
         packageSpecifiers = flip fmap packageIds $ \case
           PackageIdentifier{..}
             | pkgVersion == nullVersion -> NamedPackage pkgName []
-            | otherwise ->
-              NamedPackage pkgName [PackagePropertyVersion (thisVersion pkgVersion)]
+            | otherwise                 -> NamedPackage pkgName
+                                           [PackagePropertyVersion
+                                            (thisVersion pkgVersion)]
         packageTargets = flip TargetPackageNamed Nothing . pkgName <$> packageIds
       return (packageSpecifiers, packageTargets, projectConfig)
 
-  (specs, selectors, config) <- withProjectOrGlobalConfig verbosity globalConfigFlag
-                                  withProject withoutProject
+  (specs, selectors, config) <-
+    withProjectOrGlobalConfig verbosity globalConfigFlag
+                              withProject withoutProject
 
   home <- getHomeDirectory
   let
@@ -438,7 +468,8 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
     hcPath   = flagToMaybe projectConfigHcPath
     hcPkg    = flagToMaybe projectConfigHcPkg
 
-    progDb =
+    -- ProgramDb with directly user specified paths
+    preProgDb =
         userSpecifyPaths (Map.toList (getMapLast packageConfigProgramPaths))
       . userSpecifyArgss (Map.toList (getMapMappend packageConfigProgramArgs))
       . modifyProgramSearchPath
@@ -446,29 +477,31 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
               | dir <- fromNubList packageConfigProgramPathExtra ])
       $ defaultProgramDb
 
+  -- progDb is a program database with compiler tools configured properly
   (compiler@Compiler { compilerId =
-    compilerId@(CompilerId compilerFlavor compilerVersion) }, platform, progDb') <-
-      configCompilerEx hcFlavor hcPath hcPkg progDb verbosity
+    compilerId@(CompilerId compilerFlavor compilerVersion) }, platform, progDb) <-
+      configCompilerEx hcFlavor hcPath hcPkg preProgDb verbosity
 
   let
     globalEnv name =
       home </> ".ghc" </> ghcPlatformAndVersionString platform compilerVersion
            </> "environments" </> name
     localEnv dir =
-      dir </> ".ghc.environment." ++ ghcPlatformAndVersionString platform compilerVersion
+      dir </>
+      ".ghc.environment." <> ghcPlatformAndVersionString platform compilerVersion
 
     GhcImplInfo{ supportsPkgEnvFiles } = getImplInfo compiler
     -- Why? We know what the first part will be, we only care about the packages.
     filterEnvEntries = filter $ \case
       GhcEnvFilePackageId _ -> True
-      _ -> False
+      _                     -> False
 
   envFile <- case flagToMaybe (cinstEnvironmentPath clientInstallFlags) of
     Just spec
       -- Is spec a bare word without any "pathy" content, then it refers to
       -- a named global environment.
       | takeBaseName spec == spec -> return (globalEnv spec)
-      | otherwise -> do
+      | otherwise                 -> do
         spec' <- makeAbsolute spec
         isDir <- doesDirectoryExist spec'
         if isDir
@@ -477,7 +510,7 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
           then return (localEnv spec')
           -- Otherwise, treat it like a literal file path.
           else return spec'
-    Nothing -> return (globalEnv "default")
+    Nothing                       -> return (globalEnv "default")
 
   envFileExists <- doesFileExist envFile
   envEntries <- filterEnvEntries <$> if
@@ -489,15 +522,17 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
     else return []
 
   cabalDir  <- getCabalDir
-  mstoreDir <- sequenceA $ makeAbsolute <$> flagToMaybe (globalStoreDir globalFlags)
+  mstoreDir <-
+    sequenceA $ makeAbsolute <$> flagToMaybe (globalStoreDir globalFlags)
   let
     mlogsDir    = flagToMaybe (globalLogsDir globalFlags)
     cabalLayout = mkCabalDirLayout cabalDir mstoreDir mlogsDir
     packageDbs  = storePackageDBStack (cabalStoreDirLayout cabalLayout) compilerId
 
-  installedIndex <- getInstalledPackages verbosity compiler packageDbs progDb'
+  installedIndex <- getInstalledPackages verbosity compiler packageDbs progDb
 
-  let (envSpecs, envEntries') = environmentFileToSpecifiers installedIndex envEntries
+  let (envSpecs, envEntries') =
+        environmentFileToSpecifiers installedIndex envEntries
 
   -- Second, we need to use a fake project to let Cabal build the
   -- installables correctly. For that, we need a place to put a
@@ -513,6 +548,7 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
                  config
                  tmpDir
                  (envSpecs ++ specs)
+                 InstallCommand
 
     buildCtx <-
       runProjectPreBuildPhase verbosity baseCtx $ \elaboratedPlan -> do
@@ -549,13 +585,14 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
     -- First, figure out if / what parts we want to install:
     let
       dryRun = buildSettingDryRun $ buildSettings baseCtx
-      installLibs = fromFlagOrDefault False (cinstInstallLibs clientInstallFlags)
 
     -- Then, install!
     when (not dryRun) $
       if installLibs
-      then installLibraries verbosity buildCtx compiler packageDbs progDb envFile envEntries'
-      else installExes verbosity baseCtx buildCtx platform compiler clientInstallFlags
+      then installLibraries verbosity
+           buildCtx compiler packageDbs progDb envFile envEntries'
+      else installExes verbosity
+           baseCtx buildCtx platform compiler clientInstallFlags
   where
     configFlags' = disableTestsBenchsByDefault configFlags
     verbosity = fromFlagOrDefault normal (configVerbosity configFlags')
@@ -567,28 +604,31 @@ installAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags
 
 -- | Install any built exe by symlinking/copying it
 -- we don't use BuildOutcomes because we also need the component names
-installExes :: Verbosity
-            -> ProjectBaseContext
-            -> ProjectBuildContext
-            -> Platform
-            -> Compiler
-            -> ClientInstallFlags
-            -> IO ()
+installExes
+  :: Verbosity
+  -> ProjectBaseContext
+  -> ProjectBuildContext
+  -> Platform
+  -> Compiler
+  -> ClientInstallFlags
+  -> IO ()
 installExes verbosity baseCtx buildCtx platform compiler
             clientInstallFlags = do
   let storeDirLayout = cabalStoreDirLayout $ cabalDirLayout baseCtx
-  let mkUnitBinDir :: UnitId -> FilePath
-      mkUnitBinDir = InstallDirs.bindir .
-                     storePackageInstallDirs'
-                       storeDirLayout
-                       (compilerId compiler)
+
+      mkUnitBinDir :: UnitId -> FilePath
+      mkUnitBinDir =
+        InstallDirs.bindir .
+        storePackageInstallDirs' storeDirLayout (compilerId compiler)
+
       mkExeName :: UnqualComponentName -> FilePath
       mkExeName exe = unUnqualComponentName exe <.> exeExtension platform
       installdirUnknown =
         "installdir is not defined. Set it in your cabal config file "
         ++ "or use --installdir=<path>"
-  installdir <- fromFlagOrDefault (die' verbosity installdirUnknown)
-              $ pure <$> cinstInstalldir clientInstallFlags
+
+  installdir <- fromFlagOrDefault (die' verbosity installdirUnknown) $
+                pure <$> cinstInstalldir clientInstallFlags
   createDirectoryIfMissingVerbose verbosity False installdir
   warnIfNoExes verbosity buildCtx
   let
@@ -599,20 +639,21 @@ installExes verbosity baseCtx buildCtx platform compiler
                   installdir installMethod
     in traverse_ doInstall $ Map.toList $ targetsMap buildCtx
   where
-    overwritePolicy = fromFlagOrDefault NeverOverwrite
-                        $ cinstOverwritePolicy clientInstallFlags
-    installMethod    = fromFlagOrDefault InstallMethodSymlink
-                        $ cinstInstallMethod clientInstallFlags
+    overwritePolicy = fromFlagOrDefault NeverOverwrite $
+                      cinstOverwritePolicy clientInstallFlags
+    installMethod   = fromFlagOrDefault InstallMethodSymlink $
+                      cinstInstallMethod clientInstallFlags
 
 -- | Install any built library by adding it to the default ghc environment
-installLibraries :: Verbosity
-                 -> ProjectBuildContext
-                 -> Compiler
-                 -> PackageDBStack
-                 -> ProgramDb
-                 -> FilePath -- ^ Environment file
-                 -> [GhcEnvironmentFileEntry]
-                 -> IO ()
+installLibraries
+  :: Verbosity
+  -> ProjectBuildContext
+  -> Compiler
+  -> PackageDBStack
+  -> ProgramDb
+  -> FilePath -- ^ Environment file
+  -> [GhcEnvironmentFileEntry]
+  -> IO ()
 installLibraries verbosity buildCtx compiler
                  packageDbs programDb envFile envEntries = do
   -- Why do we get it again? If we updated a globalPackage then we need
@@ -644,19 +685,19 @@ installLibraries verbosity buildCtx compiler
 warnIfNoExes :: Verbosity -> ProjectBuildContext -> IO ()
 warnIfNoExes verbosity buildCtx =
   when noExes $
-    warn verbosity $ "You asked to install executables, "
-                  <> "but there are no executables in "
-                  <> plural (listPlural selectors) "target" "targets" <> ": "
-                  <> intercalate ", " (showTargetSelector <$> selectors) <> ". "
-                  <> "Perhaps you want to use --lib "
-                  <> "to install libraries instead."
+    warn verbosity $
+    "You asked to install executables, but there are no executables in "
+    <> plural (listPlural selectors) "target" "targets" <> ": "
+    <> intercalate ", " (showTargetSelector <$> selectors) <> ". "
+    <> "Perhaps you want to use --lib to install libraries instead."
   where
-    targets = concat $ Map.elems $ targetsMap buildCtx
+    targets    = concat $ Map.elems $ targetsMap buildCtx
     components = fst <$> targets
-    selectors = concatMap snd targets
-    noExes = null $ catMaybes $ exeMaybe <$> components
+    selectors  = concatMap snd targets
+    noExes     = null $ catMaybes $ exeMaybe <$> components
+
     exeMaybe (ComponentTarget (CExeName exe) _) = Just exe
-    exeMaybe _ = Nothing
+    exeMaybe _                                  = Nothing
 
 globalPackages :: [PackageName]
 globalPackages = mkPackageName <$>
@@ -667,13 +708,16 @@ globalPackages = mkPackageName <$>
   , "bin-package-db"
   ]
 
-environmentFileToSpecifiers :: PI.InstalledPackageIndex -> [GhcEnvironmentFileEntry]
-                            -> ([PackageSpecifier a], [GhcEnvironmentFileEntry])
+environmentFileToSpecifiers
+  :: PI.InstalledPackageIndex -> [GhcEnvironmentFileEntry]
+  -> ([PackageSpecifier a], [GhcEnvironmentFileEntry])
 environmentFileToSpecifiers ipi = foldMap $ \case
     (GhcEnvFilePackageId unitId)
-        | Just InstalledPackageInfo{ sourcePackageId = PackageIdentifier{..}, installedUnitId }
+        | Just InstalledPackageInfo
+          { sourcePackageId = PackageIdentifier{..}, installedUnitId }
           <- PI.lookupUnitId ipi unitId
-        , let pkgSpec = NamedPackage pkgName [PackagePropertyVersion (thisVersion pkgVersion)]
+        , let pkgSpec = NamedPackage pkgName
+                        [PackagePropertyVersion (thisVersion pkgVersion)]
         -> if pkgName `elem` globalPackages
           then ([pkgSpec], [])
           else ([pkgSpec], [GhcEnvFilePackageId installedUnitId])
@@ -687,17 +731,18 @@ disableTestsBenchsByDefault configFlags =
               , configBenchmarks = Flag False <> configBenchmarks configFlags }
 
 -- | Symlink/copy every exe from a package from the store to a given location
-installUnitExes :: Verbosity
-                -> OverwritePolicy -- ^ Whether to overwrite existing files
-                -> (UnitId -> FilePath) -- ^ A function to get an UnitId's
-                                        -- store directory
-                -> (UnqualComponentName -> FilePath) -- ^ A function to get
-                                                     -- ^ an exe's filename
-                -> FilePath
-                -> InstallMethod
-                -> ( UnitId
-                    , [(ComponentTarget, [TargetSelector])] )
-                -> IO ()
+installUnitExes
+  :: Verbosity
+  -> OverwritePolicy -- ^ Whether to overwrite existing files
+  -> (UnitId -> FilePath) -- ^ A function to get an UnitId's
+                          -- ^ store directory
+  -> (UnqualComponentName -> FilePath) -- ^ A function to get an
+                                       -- ^ exe's filename
+  -> FilePath
+  -> InstallMethod
+  -> ( UnitId
+     , [(ComponentTarget, [TargetSelector])] )
+  -> IO ()
 installUnitExes verbosity overwritePolicy
                 mkSourceBinDir mkExeName
                 installdir installMethod
@@ -713,24 +758,26 @@ installUnitExes verbosity overwritePolicy
                    (mkSourceBinDir unit) (mkExeName exe)
                    installdir installMethod
       let errorMessage = case overwritePolicy of
-                  NeverOverwrite ->
-                    "Path '" <> (installdir </> prettyShow exe) <> "' already exists. "
-                    <> "Use --overwrite-policy=always to overwrite."
-                  -- This shouldn't even be possible, but we keep it in case
-                  -- symlinking/copying logic changes
-                  AlwaysOverwrite -> case installMethod of
-                                       InstallMethodSymlink -> "Symlinking"
-                                       InstallMethodCopy    -> "Copying"
-                                  <> " '" <> prettyShow exe <> "' failed."
+            NeverOverwrite ->
+              "Path '" <> (installdir </> prettyShow exe) <> "' already exists. "
+              <> "Use --overwrite-policy=always to overwrite."
+            -- This shouldn't even be possible, but we keep it in case
+            -- symlinking/copying logic changes
+            AlwaysOverwrite ->
+              case installMethod of
+                InstallMethodSymlink -> "Symlinking"
+                InstallMethodCopy    ->
+                  "Copying" <> " '" <> prettyShow exe <> "' failed."
       unless success $ die' verbosity errorMessage
 
 -- | Install a specific exe.
-installBuiltExe :: Verbosity -> OverwritePolicy
-                -> FilePath -- ^ The directory where the built exe is located
-                -> FilePath -- ^ The exe's filename
-                -> FilePath -- ^ the directory where it should be installed
-                -> InstallMethod
-                -> IO Bool -- ^ Whether the installation was successful
+installBuiltExe
+  :: Verbosity -> OverwritePolicy
+  -> FilePath -- ^ The directory where the built exe is located
+  -> FilePath -- ^ The exe's filename
+  -> FilePath -- ^ the directory where it should be installed
+  -> InstallMethod
+  -> IO Bool -- ^ Whether the installation was successful
 installBuiltExe verbosity overwritePolicy
                 sourceDir exeName
                 installdir InstallMethodSymlink = do
@@ -768,7 +815,9 @@ entriesForLibraryComponents = Map.foldrWithKey' (\k v -> mappend (go k v)) []
     hasLib (ComponentTarget (CLibName _) _, _) = True
     hasLib _                                   = False
 
-    go :: UnitId -> [(ComponentTarget, [TargetSelector])] -> [GhcEnvironmentFileEntry]
+    go :: UnitId
+       -> [(ComponentTarget, [TargetSelector])]
+       -> [GhcEnvironmentFileEntry]
     go unitId targets
       | any hasLib targets = [GhcEnvFilePackageId unitId]
       | otherwise          = []
@@ -782,9 +831,10 @@ establishDummyProjectBaseContext
      -- ^ Where to put the dist directory
   -> [PackageSpecifier UnresolvedSourcePackage]
      -- ^ The packages to be included in the project
+  -> CurrentCommand
   -> IO ProjectBaseContext
-establishDummyProjectBaseContext verbosity cliConfig tmpDir localPackages = do
-
+establishDummyProjectBaseContext verbosity cliConfig tmpDir
+                                 localPackages currentCommand = do
     cabalDir <- getCabalDir
 
     -- Create the dist directories
@@ -819,7 +869,8 @@ establishDummyProjectBaseContext verbosity cliConfig tmpDir localPackages = do
       cabalDirLayout,
       projectConfig,
       localPackages,
-      buildSettings
+      buildSettings,
+      currentCommand
     }
   where
     mdistDirectory = flagToMaybe
@@ -837,8 +888,9 @@ establishDummyProjectBaseContext verbosity cliConfig tmpDir localPackages = do
 -- and disabled tests\/benchmarks, fail if there are no such
 -- components
 --
-selectPackageTargets :: TargetSelector
-                     -> [AvailableTarget k] -> Either TargetProblem [k]
+selectPackageTargets
+  :: TargetSelector
+  -> [AvailableTarget k] -> Either TargetProblem [k]
 selectPackageTargets targetSelector targets
 
     -- If there are any buildable targets then we select those
@@ -870,8 +922,9 @@ selectPackageTargets targetSelector targets
 --
 -- For the @build@ command we just need the basic checks on being buildable etc.
 --
-selectComponentTarget :: SubComponentTarget
-                      -> AvailableTarget k -> Either TargetProblem k
+selectComponentTarget
+  :: SubComponentTarget
+  -> AvailableTarget k -> Either TargetProblem k
 selectComponentTarget subtarget =
     either (Left . TargetProblemCommon) Right
   . selectComponentTargetBasic subtarget
diff --git a/cabal-install/Distribution/Client/CmdInstall/ClientInstallFlags.hs b/cabal-install/Distribution/Client/CmdInstall/ClientInstallFlags.hs
index a139d74401eab08966f269dfcb04fb0fc753ab4f..d5e790dbfde43921712ab7d2638f7397d4d0d5da 100644
--- a/cabal-install/Distribution/Client/CmdInstall/ClientInstallFlags.hs
+++ b/cabal-install/Distribution/Client/CmdInstall/ClientInstallFlags.hs
@@ -27,11 +27,11 @@ data InstallMethod = InstallMethodCopy
 instance Binary InstallMethod
 
 data ClientInstallFlags = ClientInstallFlags
-  { cinstInstallLibs :: Flag Bool
+  { cinstInstallLibs     :: Flag Bool
   , cinstEnvironmentPath :: Flag FilePath
   , cinstOverwritePolicy :: Flag OverwritePolicy
-  , cinstInstallMethod :: Flag InstallMethod
-  , cinstInstalldir :: Flag FilePath
+  , cinstInstallMethod   :: Flag InstallMethod
+  , cinstInstalldir      :: Flag FilePath
   } deriving (Eq, Show, Generic)
 
 instance Monoid ClientInstallFlags where
@@ -45,11 +45,11 @@ instance Binary ClientInstallFlags
 
 defaultClientInstallFlags :: ClientInstallFlags
 defaultClientInstallFlags = ClientInstallFlags
-  { cinstInstallLibs = toFlag False
+  { cinstInstallLibs     = toFlag False
   , cinstEnvironmentPath = mempty
-  , cinstOverwritePolicy = toFlag NeverOverwrite
-  , cinstInstallMethod = toFlag InstallMethodSymlink
-  , cinstInstalldir = mempty
+  , cinstOverwritePolicy = mempty
+  , cinstInstallMethod   = mempty
+  , cinstInstalldir      = mempty
   }
 
 clientInstallOptions :: ShowOrParseArgs -> [OptionField ClientInstallFlags]
@@ -103,4 +103,3 @@ showInstallMethodFlag :: Flag InstallMethod -> [String]
 showInstallMethodFlag (Flag InstallMethodCopy)    = ["copy"]
 showInstallMethodFlag (Flag InstallMethodSymlink) = ["symlink"]
 showInstallMethodFlag NoFlag                      = []
-
diff --git a/cabal-install/Distribution/Client/CmdRepl.hs b/cabal-install/Distribution/Client/CmdRepl.hs
index f20c2207319c29ab073e8a499f4697302046afde..3eaaab25e34307ceadf2bece66f513f95a6a7e54 100644
--- a/cabal-install/Distribution/Client/CmdRepl.hs
+++ b/cabal-install/Distribution/Client/CmdRepl.hs
@@ -50,6 +50,10 @@ import Distribution.Simple.Setup
 import Distribution.Simple.Command
          ( CommandUI(..), liftOption, usageAlternatives, option
          , ShowOrParseArgs, OptionField, reqArg )
+import Distribution.Compiler
+         ( CompilerFlavor(GHC) )
+import Distribution.Simple.Compiler
+         ( compilerCompatVersion )
 import Distribution.Package
          ( Package(..), packageName, UnitId, installedUnitId )
 import Distribution.PackageDescription.PrettyPrint
@@ -98,7 +102,7 @@ import Data.List
 import qualified Data.Map as Map
 import qualified Data.Set as Set
 import System.Directory
-         ( getTemporaryDirectory, removeDirectoryRecursive )
+         ( getCurrentDirectory, getTemporaryDirectory, removeDirectoryRecursive )
 import System.FilePath
          ( (</>) )
 
@@ -219,7 +223,7 @@ replAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags, r
       with           = withProject    cliConfig             verbosity targetStrings
       without config = withoutProject (config <> cliConfig) verbosity targetStrings
     
-    (baseCtx, targetSelectors, finalizer) <- if ignoreProject
+    (baseCtx, targetSelectors, finalizer, replType) <- if ignoreProject
       then do
         globalConfig <- runRebuild "" $ readGlobalConfig verbosity globalConfigFlag
         without globalConfig
@@ -256,7 +260,7 @@ replAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags, r
     -- In addition, to avoid a *third* trip through the solver, we are 
     -- replicating the second half of 'runProjectPreBuildPhase' by hand
     -- here.
-    (buildCtx, replFlags') <- withInstallPlan verbosity baseCtx' $ 
+    (buildCtx, replFlags'') <- withInstallPlan verbosity baseCtx' $
       \elaboratedPlan elaboratedShared' -> do
         let ProjectBaseContext{..} = baseCtx'
           
@@ -269,9 +273,6 @@ replAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags, r
                               targets
                               elaboratedPlan
           includeTransitive = fromFlagOrDefault True (envIncludeTransitive envFlags)
-          replFlags' = case originalComponent of 
-            Just oci -> generateReplFlags includeTransitive elaboratedPlan' oci
-            Nothing  -> []
         
         pkgsBuildStatus <- rebuildTargetsDryRun distDirLayout elaboratedShared'
                                           elaboratedPlan'
@@ -288,11 +289,27 @@ replAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags, r
             , pkgsBuildStatus
             , targetsMap = targets
             }
-        return (buildCtx, replFlags')
+          
+          ElaboratedSharedConfig { pkgConfigCompiler = compiler } = elaboratedShared'
+          
+          -- First version of GHC where GHCi supported the flag we need.
+          -- https://downloads.haskell.org/~ghc/7.6.1/docs/html/users_guide/release-7-6-1.html
+          minGhciScriptVersion = mkVersion [7, 6]
+
+          replFlags' = case originalComponent of 
+            Just oci -> generateReplFlags includeTransitive elaboratedPlan' oci
+            Nothing  -> []
+          replFlags'' = case replType of
+            GlobalRepl scriptPath 
+              | Just version <- compilerCompatVersion GHC compiler
+              , version >= minGhciScriptVersion -> ("-ghci-script" ++ scriptPath) : replFlags'
+            _                                   -> replFlags'
+
+        return (buildCtx, replFlags'')
 
     let buildCtx' = buildCtx
           { elaboratedShared = (elaboratedShared buildCtx)
-                { pkgConfigReplOptions = replFlags ++ replFlags' }
+                { pkgConfigReplOptions = replFlags ++ replFlags'' }
           }
     printPlan verbosity baseCtx' buildCtx'
 
@@ -335,16 +352,26 @@ data OriginalComponentInfo = OriginalComponentInfo
   }
   deriving (Show)
 
-withProject :: ProjectConfig -> Verbosity -> [String] -> IO (ProjectBaseContext, [TargetSelector], IO ())
+-- | Tracks what type of GHCi instance we're creating.
+data ReplType = ProjectRepl 
+              | GlobalRepl FilePath -- ^ The 'FilePath' argument is path to a GHCi
+                                    --   script responsible for changing to the
+                                    --   correct directory. Only works on GHC geq
+                                    --   7.6, though. 🙁
+              deriving (Show, Eq)
+
+withProject :: ProjectConfig -> Verbosity -> [String]
+            -> IO (ProjectBaseContext, [TargetSelector], IO (), ReplType)
 withProject cliConfig verbosity targetStrings = do
-  baseCtx <- establishProjectBaseContext verbosity cliConfig
+  baseCtx <- establishProjectBaseContext verbosity cliConfig OtherCommand
 
   targetSelectors <- either (reportTargetSelectorProblems verbosity) return
                  =<< readTargetSelectors (localPackages baseCtx) (Just LibKind) targetStrings
 
-  return (baseCtx, targetSelectors, return ())
+  return (baseCtx, targetSelectors, return (), ProjectRepl)
 
-withoutProject :: ProjectConfig -> Verbosity -> [String]  -> IO (ProjectBaseContext, [TargetSelector], IO ())
+withoutProject :: ProjectConfig -> Verbosity -> [String]
+               -> IO (ProjectBaseContext, [TargetSelector], IO (), ReplType)
 withoutProject config verbosity extraArgs = do
   unless (null extraArgs) $
     die' verbosity $ "'repl' doesn't take any extra arguments when outside a project: " ++ unwords extraArgs
@@ -378,18 +405,23 @@ withoutProject config verbosity extraArgs = do
 
   writeGenericPackageDescription (tempDir </> "fake-package.cabal") genericPackageDescription
   
+  let ghciScriptPath = tempDir </> "setcwd.ghci"
+  cwd <- getCurrentDirectory
+  writeFile ghciScriptPath (":cd " ++ cwd)
+
   baseCtx <- 
     establishDummyProjectBaseContext
       verbosity
       config
       tempDir
       [SpecificSourcePackage sourcePackage]
+      OtherCommand
 
   let
     targetSelectors = [TargetPackage TargetExplicitNamed [pkgId] Nothing]
     finalizer = handleDoesNotExist () (removeDirectoryRecursive tempDir)
 
-  return (baseCtx, targetSelectors, finalizer)
+  return (baseCtx, targetSelectors, finalizer, GlobalRepl ghciScriptPath)
 
 addDepsToProjectTarget :: [Dependency]
                        -> PackageId
diff --git a/cabal-install/Distribution/Client/CmdRun.hs b/cabal-install/Distribution/Client/CmdRun.hs
index e0e0d0a0e998d2d18f9a6baf8840de2701b9b05a..f02fbbfc9d947ce7e751f33cbf73b239450b3f50 100644
--- a/cabal-install/Distribution/Client/CmdRun.hs
+++ b/cabal-install/Distribution/Client/CmdRun.hs
@@ -104,7 +104,7 @@ import qualified Text.Parsec as P
 import System.Directory
          ( getTemporaryDirectory, removeDirectoryRecursive, doesFileExist )
 import System.FilePath
-         ( (</>), isValid, isPathSeparator )
+         ( (</>), isValid, isPathSeparator, takeExtension )
 
 
 runCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags, TestFlags)
@@ -162,17 +162,19 @@ runAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags)
 
     let
       with =
-        establishProjectBaseContext verbosity cliConfig
+        establishProjectBaseContext verbosity cliConfig OtherCommand
       without config =
-        establishDummyProjectBaseContext verbosity (config <> cliConfig) tempDir []
+        establishDummyProjectBaseContext verbosity (config <> cliConfig) tempDir [] OtherCommand
 
     baseCtx <- withProjectOrGlobalConfig verbosity globalConfigFlag with without
 
     let
       scriptOrError script err = do
         exists <- doesFileExist script
+        let pol | takeExtension script == ".lhs" = LiterateHaskell
+                | otherwise                      = PlainHaskell
         if exists
-          then BS.readFile script >>= handleScriptCase verbosity baseCtx tempDir
+          then BS.readFile script >>= handleScriptCase verbosity pol baseCtx tempDir
           else reportTargetSelectorProblems verbosity err
 
     (baseCtx', targetSelectors) <-
@@ -339,9 +341,9 @@ parseScriptBlock str =
 readScriptBlock :: Verbosity -> BS.ByteString -> IO Executable
 readScriptBlock verbosity = parseString parseScriptBlock verbosity "script block"
 
-readScriptBlockFromScript :: Verbosity -> BS.ByteString -> IO (Executable, BS.ByteString)
-readScriptBlockFromScript verbosity str = do
-    str' <- case extractScriptBlock str of
+readScriptBlockFromScript :: Verbosity -> PlainOrLiterate -> BS.ByteString -> IO (Executable, BS.ByteString)
+readScriptBlockFromScript verbosity pol str = do
+    str' <- case extractScriptBlock pol str of
               Left e -> die' verbosity $ "Failed extracting script block: " ++ e
               Right x -> return x
     when (BS.all isSpace str') $ warn verbosity "Empty script block"
@@ -361,34 +363,48 @@ readScriptBlockFromScript verbosity str = do
 --
 -- In case of missing or unterminated blocks a 'Left'-error is
 -- returned.
-extractScriptBlock :: BS.ByteString -> Either String BS.ByteString
-extractScriptBlock str = goPre (BS.lines str)
+extractScriptBlock :: PlainOrLiterate -> BS.ByteString -> Either String BS.ByteString
+extractScriptBlock _pol str = goPre (BS.lines str)
   where
-    isStartMarker = (== "{- cabal:") . stripTrailSpace
-    isEndMarker   = (== "-}") . stripTrailSpace
+    isStartMarker = (== startMarker) . stripTrailSpace
+    isEndMarker   = (== endMarker) . stripTrailSpace
+
     stripTrailSpace = fst . BS.spanEnd isSpace
 
     -- before start marker
     goPre ls = case dropWhile (not . isStartMarker) ls of
-                 [] -> Left "`{- cabal:` start marker not found"
+                 [] -> Left $ "`" ++ BS.unpack startMarker ++ "` start marker not found"
                  (_:ls') -> goBody [] ls'
 
-    goBody _ [] = Left "`-}` end marker not found"
+    goBody _ [] = Left $ "`" ++ BS.unpack endMarker ++ "` end marker not found"
     goBody acc (l:ls)
       | isEndMarker l = Right $! BS.unlines $ reverse acc
       | otherwise     = goBody (l:acc) ls
 
+    startMarker, endMarker :: BS.ByteString
+    startMarker = fromString "{- cabal:"
+    endMarker   = fromString "-}"
+
+data PlainOrLiterate
+    = PlainHaskell
+    | LiterateHaskell
 
-handleScriptCase :: Verbosity
-                 -> ProjectBaseContext
-                 -> FilePath
-                 -> BS.ByteString
-                 -> IO (ProjectBaseContext, [TargetSelector])
-handleScriptCase verbosity baseCtx tempDir scriptContents = do
-  (executable, contents') <- readScriptBlockFromScript verbosity scriptContents
+handleScriptCase
+  :: Verbosity
+  -> PlainOrLiterate
+  -> ProjectBaseContext
+  -> FilePath
+  -> BS.ByteString
+  -> IO (ProjectBaseContext, [TargetSelector])
+handleScriptCase verbosity pol baseCtx tempDir scriptContents = do
+  (executable, contents') <- readScriptBlockFromScript verbosity pol scriptContents
 
   -- We need to create a dummy package that lives in our dummy project.
   let
+    mainName = case pol of
+      PlainHaskell    -> "Main.hs"
+      LiterateHaskell -> "Main.lhs"
+
     sourcePackage = SourcePackage
       { packageInfoId         = pkgId
       , SP.packageDescription = genericPackageDescription
@@ -400,7 +416,7 @@ handleScriptCase verbosity baseCtx tempDir scriptContents = do
       , condExecutables        = [("script", CondNode executable' targetBuildDepends [])]
       }
     executable' = executable
-      { modulePath = "Main.hs"
+      { modulePath = mainName
       , buildInfo = binfo
         { defaultLanguage =
           case defaultLanguage of
@@ -417,7 +433,7 @@ handleScriptCase verbosity baseCtx tempDir scriptContents = do
     pkgId = fakePackageId
 
   writeGenericPackageDescription (tempDir </> "fake-package.cabal") genericPackageDescription
-  BS.writeFile (tempDir </> "Main.hs") contents'
+  BS.writeFile (tempDir </> mainName) contents'
 
   let
     baseCtx' = baseCtx
diff --git a/cabal-install/Distribution/Client/CmdSdist.hs b/cabal-install/Distribution/Client/CmdSdist.hs
index 2da3eaa39c22c3bf4e5c591c13fb6d3a9f239a8c..7c6e8a6ff51b1fff4cea2ba8c4358ba3ba722782 100644
--- a/cabal-install/Distribution/Client/CmdSdist.hs
+++ b/cabal-install/Distribution/Client/CmdSdist.hs
@@ -12,7 +12,7 @@ module Distribution.Client.CmdSdist
 import Distribution.Client.CmdErrorMessages
     ( Plural(..), renderComponentKind )
 import Distribution.Client.ProjectOrchestration
-    ( ProjectBaseContext(..), establishProjectBaseContext )
+    ( ProjectBaseContext(..), CurrentCommand(..), establishProjectBaseContext )
 import Distribution.Client.TargetSelector
     ( TargetSelector(..), ComponentKind
     , readTargetSelectors, reportTargetSelectorProblems )
@@ -155,7 +155,7 @@ sdistAction SdistFlags{..} targetStrings globalFlags = do
     let distLayout = defaultDistDirLayout projectRoot mDistDirectory
     dir <- getCurrentDirectory
     projectConfig <- runRebuild dir $ readProjectConfig verbosity globalConfig distLayout
-    baseCtx <- establishProjectBaseContext verbosity projectConfig
+    baseCtx <- establishProjectBaseContext verbosity projectConfig OtherCommand
     let localPkgs = localPackages baseCtx
 
     targetSelectors <- either (reportTargetSelectorProblems verbosity) return
diff --git a/cabal-install/Distribution/Client/CmdTest.hs b/cabal-install/Distribution/Client/CmdTest.hs
index f03f8aa118a94e6fa3fefdd8f81dab8f839f273e..490b6e2dcaa32b2fd5354e44bb27ab4a5fcab0d7 100644
--- a/cabal-install/Distribution/Client/CmdTest.hs
+++ b/cabal-install/Distribution/Client/CmdTest.hs
@@ -89,7 +89,7 @@ testAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags, TestFlags
 testAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags)
            targetStrings globalFlags = do
 
-    baseCtx <- establishProjectBaseContext verbosity cliConfig
+    baseCtx <- establishProjectBaseContext verbosity cliConfig OtherCommand
 
     targetSelectors <- either (reportTargetSelectorProblems verbosity) return
                    =<< readTargetSelectors (localPackages baseCtx) (Just TestKind) targetStrings
diff --git a/cabal-install/Distribution/Client/CmdUpdate.hs b/cabal-install/Distribution/Client/CmdUpdate.hs
index fe00fb2d010296cb1dc793b6bb579a3bdb2e1eec..ffe49ace4b844ff8b82d17168e1636223eb82c18 100644
--- a/cabal-install/Distribution/Client/CmdUpdate.hs
+++ b/cabal-install/Distribution/Client/CmdUpdate.hs
@@ -1,5 +1,9 @@
-{-# LANGUAGE CPP, LambdaCase, NamedFieldPuns, RecordWildCards, ViewPatterns,
-             TupleSections #-}
+{-# LANGUAGE CPP             #-}
+{-# LANGUAGE LambdaCase      #-}
+{-# LANGUAGE NamedFieldPuns  #-}
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TupleSections   #-}
+{-# LANGUAGE ViewPatterns    #-}
 
 -- | cabal-install CLI command: update
 --
@@ -9,7 +13,7 @@ module Distribution.Client.CmdUpdate (
   ) where
 
 import Prelude ()
-import Distribution.Client.Compat.Prelude    
+import Distribution.Client.Compat.Prelude
 
 import Distribution.Client.Compat.Directory
          ( setModificationTime )
@@ -115,7 +119,7 @@ updateAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags, TestFla
 updateAction (configFlags, configExFlags, installFlags, haddockFlags, testFlags)
              extraArgs globalFlags = do
   projectConfig <- withProjectOrGlobalConfig verbosity globalConfigFlag
-    (projectConfig <$> establishProjectBaseContext verbosity cliConfig)
+    (projectConfig <$> establishProjectBaseContext verbosity cliConfig OtherCommand)
     (\globalConfig -> return $ globalConfig <> cliConfig)
 
   projectConfigWithSolverRepoContext verbosity
diff --git a/cabal-install/Distribution/Client/Config.hs b/cabal-install/Distribution/Client/Config.hs
index 56b92babf703f912508f1e00c5601a920b9b6c0c..c3082fe1a8be372f1094eb74441ff579d4bafe18 100644
--- a/cabal-install/Distribution/Client/Config.hs
+++ b/cabal-install/Distribution/Client/Config.hs
@@ -86,7 +86,7 @@ import Distribution.Simple.InstallDirs
          ( InstallDirs(..), defaultInstallDirs
          , PathTemplate, toPathTemplate )
 import Distribution.Deprecated.ParseUtils
-         ( FieldDescr(..), liftField
+         ( FieldDescr(..), liftField, runP
          , ParseResult(..), PError(..), PWarning(..)
          , locatedErrorMsg, showPWarning
          , readFields, warning, lineNo
@@ -413,7 +413,8 @@ instance Semigroup SavedConfig where
         configExactConfiguration  = combine configExactConfiguration,
         configFlagError           = combine configFlagError,
         configRelocatable         = combine configRelocatable,
-        configUseResponseFiles    = combine configUseResponseFiles
+        configUseResponseFiles    = combine configUseResponseFiles,
+        configAllowDependingOnPrivateLibs = combine configAllowDependingOnPrivateLibs
         }
         where
           combine        = combine'        savedConfigureFlags
@@ -500,6 +501,7 @@ instance Semigroup SavedConfig where
         testMachineLog  = combine testMachineLog,
         testShowDetails = combine testShowDetails,
         testKeepTix     = combine testKeepTix,
+        testWrapper     = combine testWrapper,
         testFailWhenNoTestSuites = combine testFailWhenNoTestSuites,
         testOptions     = lastNonEmpty testOptions
         }
@@ -1095,7 +1097,7 @@ parseConfig src initial = \str -> do
         . nubBy ((==) `on` remoteRepoName)
         $ remoteRepoSections0
 
-  return config {
+  return . fixConfigMultilines $ config {
     savedGlobalFlags       = (savedGlobalFlags config) {
        globalRemoteRepos   = toNubList remoteRepoSections,
        -- the global extra prog path comes from the configure flag prog path
@@ -1121,6 +1123,28 @@ parseConfig src initial = \str -> do
     isKnownSection (ParseUtils.Section _ "program-default-options" _ _) = True
     isKnownSection _                                                    = False
 
+    -- attempt to split fields that can represent lists of paths into actual lists
+    -- on failure, leave the field untouched
+    splitMultiPath :: [String] -> [String]
+    splitMultiPath [s] = case runP 0 "" (parseOptCommaList parseTokenQ) s of
+            ParseOk _ res -> res
+            _ -> [s]
+    splitMultiPath xs = xs
+
+    -- This is a fixup, pending a full config parser rewrite, to ensure that
+    -- config fields which can be comma seperated lists actually parse as comma seperated lists
+    fixConfigMultilines conf = conf {
+         savedConfigureFlags =
+           let scf = savedConfigureFlags conf
+           in  scf {
+                     configProgramPathExtra = toNubList $ splitMultiPath (fromNubList $ configProgramPathExtra scf)
+                   , configExtraLibDirs = splitMultiPath (configExtraLibDirs scf)
+                   , configExtraFrameworkDirs = splitMultiPath (configExtraFrameworkDirs scf)
+                   , configExtraIncludeDirs = splitMultiPath (configExtraIncludeDirs scf)
+                   , configConfigureArgs = splitMultiPath (configConfigureArgs scf)
+               }
+      }
+
     parse = parseFields (configFieldDescriptions src
                       ++ deprecatedFieldDescriptions) initial
 
diff --git a/cabal-install/Distribution/Client/GenBounds.hs b/cabal-install/Distribution/Client/GenBounds.hs
index 3acff34c32277b14c0c4a6e5a2c3e490908f7cb2..553ee0827d7828753027dda8407ada500c16faca 100644
--- a/cabal-install/Distribution/Client/GenBounds.hs
+++ b/cabal-install/Distribution/Client/GenBounds.hs
@@ -51,7 +51,7 @@ import Distribution.Verbosity
          ( Verbosity )
 import Distribution.Version
          ( Version, alterVersion
-         , LowerBound(..), UpperBound(..), VersionRange(..), asVersionIntervals
+         , LowerBound(..), UpperBound(..), VersionRange, asVersionIntervals
          , orLaterVersion, earlierVersion, intersectVersionRanges )
 import System.Directory
          ( getCurrentDirectory )
@@ -112,7 +112,7 @@ genBounds verbosity packageDBs repoCtxt comp platform progdb mSandboxPkgInfo
     let cinfo = compilerInfo comp
 
     cwd <- getCurrentDirectory
-    path <- tryFindPackageDesc cwd
+    path <- tryFindPackageDesc verbosity cwd
     gpd <- readGenericPackageDescription verbosity path
     -- NB: We don't enable tests or benchmarks, since often they
     -- don't really have useful bounds.
diff --git a/cabal-install/Distribution/Client/Get.hs b/cabal-install/Distribution/Client/Get.hs
index 51ed6fcd065d4a098a4f000ade40af17bde1b47a..006eb57d6654383c971e9e42b57588da4cf5d3a0 100644
--- a/cabal-install/Distribution/Client/Get.hs
+++ b/cabal-install/Distribution/Client/Get.hs
@@ -24,7 +24,8 @@ module Distribution.Client.Get (
 
 import Prelude ()
 import Distribution.Client.Compat.Prelude hiding (get)
-
+import Distribution.Compat.Directory
+         ( listDirectory )
 import Distribution.Package
          ( PackageId, packageId, packageName )
 import Distribution.Simple.Setup
@@ -162,12 +163,16 @@ unpackPackage :: Verbosity -> FilePath -> PackageId
               -> PackageDescriptionOverride
               -> FilePath  -> IO ()
 unpackPackage verbosity prefix pkgid descOverride pkgPath = do
-    let pkgdirname = display pkgid
-        pkgdir     = prefix </> pkgdirname
-        pkgdir'    = addTrailingPathSeparator pkgdir
+    let pkgdirname               = display pkgid
+        pkgdir                   = prefix </> pkgdirname
+        pkgdir'                  = addTrailingPathSeparator pkgdir
+        emptyDirectory directory = null <$> listDirectory directory
     existsDir  <- doesDirectoryExist pkgdir
-    when existsDir $ die' verbosity $
-     "The directory \"" ++ pkgdir' ++ "\" already exists, not unpacking."
+    when existsDir $ do
+      isEmpty <- emptyDirectory pkgdir
+      unless isEmpty $
+        die' verbosity $
+        "The directory \"" ++ pkgdir' ++ "\" already exists and is not empty, not unpacking."
     existsFile  <- doesFileExist pkgdir
     when existsFile $ die' verbosity $
      "A file \"" ++ pkgdir ++ "\" is in the way, not unpacking."
diff --git a/cabal-install/Distribution/Client/IndexUtils/Timestamp.hs b/cabal-install/Distribution/Client/IndexUtils/Timestamp.hs
index 07b1084f8e202bdc7b4181e010e00b12b8640090..e6c3dd58c47b126fd90ba81be848610d14d1e377 100644
--- a/cabal-install/Distribution/Client/IndexUtils/Timestamp.hs
+++ b/cabal-install/Distribution/Client/IndexUtils/Timestamp.hs
@@ -39,7 +39,7 @@ import           GHC.Generics (Generic)
 
 -- | UNIX timestamp (expressed in seconds since unix epoch, i.e. 1970).
 newtype Timestamp = TS Int64 -- Tar.EpochTime
-                  deriving (Eq,Ord,Enum,NFData,Show)
+                  deriving (Eq,Ord,Enum,NFData,Show,Generic)
 
 epochTimeToTimestamp :: Tar.EpochTime -> Maybe Timestamp
 epochTimeToTimestamp et
diff --git a/cabal-install/Distribution/Client/Install.hs b/cabal-install/Distribution/Client/Install.hs
index 6e7da0f468ba691a5355134a076908115e038b5f..3e5dff843b4630275158ef7e7a3b0d1bfba3beff 100644
--- a/cabal-install/Distribution/Client/Install.hs
+++ b/cabal-install/Distribution/Client/Install.hs
@@ -32,6 +32,7 @@ module Distribution.Client.Install (
 import Prelude ()
 import Distribution.Client.Compat.Prelude
 
+import qualified Data.List.NonEmpty as NE
 import qualified Data.Map as Map
 import qualified Data.Set as S
 import Control.Exception as Exception
@@ -78,7 +79,8 @@ import Distribution.Client.SolverInstallPlan (SolverInstallPlan)
 import Distribution.Client.Setup
          ( GlobalFlags(..), RepoContext(..)
          , ConfigFlags(..), configureCommand, filterConfigureFlags
-         , ConfigExFlags(..), InstallFlags(..) )
+         , ConfigExFlags(..), InstallFlags(..)
+         , filterTestFlags )
 import Distribution.Client.Config
          ( getCabalDir, defaultUserInstall )
 import Distribution.Client.Sandbox.Timestamp
@@ -1490,7 +1492,7 @@ installUnpackedPackage verbosity installLock numJobs
     }
     testsEnabled = fromFlag (configTests configFlags)
                    && fromFlagOrDefault False (installRunTests installFlags)
-    testFlags' _ = testFlags {
+    testFlags' = filterTestFlags testFlags {
       Cabal.testDistPref = configDistPref configFlags
     }
     copyFlags _ = Cabal.emptyCopyFlags {
@@ -1548,7 +1550,7 @@ installUnpackedPackage verbosity installLock numJobs
     readPkgConf pkgConfDir pkgConfFile =
       (withUTF8FileContents (pkgConfDir </> pkgConfFile) $ \pkgConfText ->
         case Installed.parseInstalledPackageInfo pkgConfText of
-          Left perrors    -> pkgConfParseFailed $ unlines perrors
+          Left perrors    -> pkgConfParseFailed $ unlines $ NE.toList perrors
           Right (warns, pkgConf) -> do
             unless (null warns) $
               warn verbosity $ unlines warns
diff --git a/cabal-install/Distribution/Client/Outdated.hs b/cabal-install/Distribution/Client/Outdated.hs
index 925779cadbdcdc742d19635f743d2cdb76b5ca22..9095c70c2054153bbc635ec69c873c5f77aa1b48 100644
--- a/cabal-install/Distribution/Client/Outdated.hs
+++ b/cabal-install/Distribution/Client/Outdated.hs
@@ -149,7 +149,7 @@ depsFromNewFreezeFile verbosity mprojectFile = do
 depsFromPkgDesc :: Verbosity -> Compiler  -> Platform -> IO [Dependency]
 depsFromPkgDesc verbosity comp platform = do
   cwd  <- getCurrentDirectory
-  path <- tryFindPackageDesc cwd
+  path <- tryFindPackageDesc verbosity cwd
   gpd  <- readGenericPackageDescription verbosity path
   let cinfo = compilerInfo comp
       epd = finalizePD mempty (ComponentRequestedSpec True True)
diff --git a/cabal-install/Distribution/Client/ParseUtils.hs b/cabal-install/Distribution/Client/ParseUtils.hs
index 56eebf37569056330757acbe3ca099c5cca5c72c..23d5e32b12126a65bed2aaa322af3fe6b4272f42 100644
--- a/cabal-install/Distribution/Client/ParseUtils.hs
+++ b/cabal-install/Distribution/Client/ParseUtils.hs
@@ -1,4 +1,4 @@
-{-# LANGUAGE ExistentialQuantification, NamedFieldPuns #-}
+{-# LANGUAGE ExistentialQuantification, NamedFieldPuns, RankNTypes #-}
 
 -----------------------------------------------------------------------------
 -- |
@@ -24,6 +24,9 @@ module Distribution.Client.ParseUtils (
     SectionDescr(..),
     liftSection,
 
+    -- * FieldGrammar sections
+    FGSectionDescr(..),
+
     -- * Parsing and printing flat config
     parseFields,
     ppFields,
@@ -39,6 +42,9 @@ module Distribution.Client.ParseUtils (
   )
        where
 
+import Distribution.Client.Compat.Prelude hiding (empty, get)
+import Prelude ()
+
 import Distribution.Deprecated.ParseUtils
          ( FieldDescr(..), ParseResult(..), warning, LineNo, lineNo
          , Field(..), liftField, readFieldsFlat )
@@ -48,12 +54,22 @@ import Distribution.Deprecated.ViewAsFieldDescr
 import Distribution.Simple.Command
          ( OptionField  )
 
-import Control.Monad    ( foldM )
 import Text.PrettyPrint ( (<+>), ($+$) )
 import qualified Data.Map as Map
 import qualified Text.PrettyPrint as Disp
          ( (<>), Doc, text, colon, vcat, empty, isEmpty, nest )
 
+-- For new parser stuff
+import Distribution.CabalSpecVersion (cabalSpecLatest)
+import Distribution.FieldGrammar (FieldGrammar, partitionFields, parseFieldGrammar)
+import Distribution.Fields.ParseResult (runParseResult)
+import Distribution.Parsec.Error (showPError)
+import Distribution.Parsec.Position (Position (..))
+import Distribution.Parsec.Warning (showPWarning)
+import Distribution.Simple.Utils (fromUTF8BS, toUTF8BS)
+import qualified Distribution.Fields as F
+import qualified Distribution.FieldGrammar as FG
+
 
 -------------------------
 -- FieldDescr utilities
@@ -107,6 +123,15 @@ data SectionDescr a = forall b. SectionDescr {
        sectionEmpty       :: b
      }
 
+-- | 'FieldGrammar' section description
+data FGSectionDescr a = forall s. FGSectionDescr
+    { fgSectionName    :: String
+    , fgSectionGrammar :: forall g. (FieldGrammar g, Applicative (g s)) => g s s
+    -- todo: add subsections?
+    , fgSectionGet     :: a -> [(String, s)]
+    , fgSectionSet     :: LineNo -> String -> s -> a -> ParseResult a
+    }
+
 -- | To help construction of config file descriptions in a modular way it is
 -- useful to define fields and sections on local types and then hoist them
 -- into the parent types when combining them in bigger descriptions.
@@ -191,13 +216,18 @@ ppSection name arg fields def cur
 -- | Much like 'parseFields' but it also allows subsections. The permitted
 -- subsections are given by a list of 'SectionDescr's.
 --
-parseFieldsAndSections :: [FieldDescr a] -> [SectionDescr a] -> a
-                       -> [Field] -> ParseResult a
-parseFieldsAndSections fieldDescrs sectionDescrs =
+parseFieldsAndSections
+    :: [FieldDescr a]      -- ^ field
+    -> [SectionDescr a]    -- ^ legacy sections
+    -> [FGSectionDescr a]  -- ^ FieldGrammar sections
+    -> a
+    -> [Field] -> ParseResult a
+parseFieldsAndSections fieldDescrs sectionDescrs fgSectionDescrs =
     foldM setField
   where
-    fieldMap   = Map.fromList [ (fieldName   f, f) | f <- fieldDescrs   ]
-    sectionMap = Map.fromList [ (sectionName s, s) | s <- sectionDescrs ]
+    fieldMap     = Map.fromList [ (fieldName     f, f) | f <- fieldDescrs     ]
+    sectionMap   = Map.fromList [ (sectionName   s, s) | s <- sectionDescrs   ]
+    fgSectionMap = Map.fromList [ (fgSectionName s, s) | s <- fgSectionDescrs ]
 
     setField a (F line name value) =
       case Map.lookup name fieldMap of
@@ -208,10 +238,25 @@ parseFieldsAndSections fieldDescrs sectionDescrs =
           return a
 
     setField a (Section line name param fields) =
-      case Map.lookup name sectionMap of
-        Just (SectionDescr _ fieldDescrs' sectionDescrs' _ set sectionEmpty) -> do
-          b <- parseFieldsAndSections fieldDescrs' sectionDescrs' sectionEmpty fields
+      case Left <$> Map.lookup name sectionMap <|> Right <$> Map.lookup name fgSectionMap of
+        Just (Left (SectionDescr _ fieldDescrs' sectionDescrs' _ set sectionEmpty)) -> do
+          b <- parseFieldsAndSections fieldDescrs' sectionDescrs' [] sectionEmpty fields
           set line param b a
+        Just (Right (FGSectionDescr _ grammar _getter setter)) -> do
+          let fields1 = mapMaybe convertField fields
+              (fields2, sections) = partitionFields fields1
+          -- TODO: recurse into sections
+          for_ (concat sections) $ \(FG.MkSection (F.Name (Position line' _) name') _ _) ->
+            warning $ "Unrecognized section '" ++ fromUTF8BS name'
+              ++ "' on line " ++ show line'
+          case runParseResult $ parseFieldGrammar cabalSpecLatest fields2 grammar of
+            (warnings, Right b) -> do
+              for_ warnings $ \w -> warning $ showPWarning "???" w
+              setter line param b a
+            (warnings, Left (_, errs)) -> do
+              for_ warnings $ \w -> warning $ showPWarning "???" w
+              case errs of
+                err :| _errs -> fail $ showPError "???" err
         Nothing -> do
           warning $ "Unrecognized section '" ++ name
                  ++ "' on line " ++ show line
@@ -221,17 +266,31 @@ parseFieldsAndSections fieldDescrs sectionDescrs =
       warning $ "Unrecognized stanza on line " ++ show (lineNo block)
       return accum
 
+convertField :: Field -> Maybe (F.Field Position)
+convertField (F line name str) = Just $
+    F.Field (F.Name pos (toUTF8BS name)) [ F.FieldLine pos $ toUTF8BS str ]
+  where
+    pos = Position line 0
+-- arguments omitted
+convertField (Section line name _arg fields) = Just $
+    F.Section (F.Name pos (toUTF8BS name)) [] (mapMaybe convertField fields)
+  where
+    pos = Position line 0
+-- silently omitted.
+convertField IfBlock {} = Nothing
+
+
 -- | Much like 'ppFields' but also pretty prints any subsections. Subsection
 -- are only shown if they are non-empty.
 --
 -- Note that unlike 'ppFields', at present it does not support printing
 -- default values. If needed, adding such support would be quite reasonable.
 --
-ppFieldsAndSections :: [FieldDescr a] -> [SectionDescr a] -> a -> Disp.Doc
-ppFieldsAndSections fieldDescrs sectionDescrs val =
+ppFieldsAndSections :: [FieldDescr a] -> [SectionDescr a] -> [FGSectionDescr a] -> a -> Disp.Doc
+ppFieldsAndSections fieldDescrs sectionDescrs fgSectionDescrs val =
     ppFields fieldDescrs Nothing val
       $+$
-    Disp.vcat
+    Disp.vcat (
       [ Disp.text "" $+$ sectionDoc
       | SectionDescr {
           sectionName, sectionGet,
@@ -240,24 +299,57 @@ ppFieldsAndSections fieldDescrs sectionDescrs val =
       , (param, x) <- sectionGet val
       , let sectionDoc = ppSectionAndSubsections
                            sectionName param
-                           sectionFields sectionSubsections x
+                           sectionFields sectionSubsections [] x
+      , not (Disp.isEmpty sectionDoc)
+      ] ++
+      [ Disp.text "" $+$ sectionDoc
+      | FGSectionDescr { fgSectionName, fgSectionGrammar, fgSectionGet } <- fgSectionDescrs
+      , (param, x) <- fgSectionGet val
+      , let sectionDoc = ppFgSection fgSectionName param fgSectionGrammar x
       , not (Disp.isEmpty sectionDoc)
-      ]
+      ])
 
 -- | Unlike 'ppSection' which has to be called directly, this gets used via
 -- 'ppFieldsAndSections' and so does not need to be exported.
 --
 ppSectionAndSubsections :: String -> String
-                        -> [FieldDescr a] -> [SectionDescr a] -> a -> Disp.Doc
-ppSectionAndSubsections name arg fields sections cur
+                        -> [FieldDescr a] -> [SectionDescr a] -> [FGSectionDescr a] -> a -> Disp.Doc
+ppSectionAndSubsections name arg fields sections fgSections cur
   | Disp.isEmpty fieldsDoc = Disp.empty
   | otherwise              = Disp.text name <+> argDoc
                              $+$ (Disp.nest 2 fieldsDoc)
   where
-    fieldsDoc = showConfig fields sections cur
+    fieldsDoc = showConfig fields sections fgSections cur
     argDoc | arg == "" = Disp.empty
            | otherwise = Disp.text arg
 
+-- |
+--
+-- TODO: subsections
+-- TODO: this should simply build 'PrettyField'
+ppFgSection
+    :: String  -- ^ section name
+    -> String  -- ^ parameter
+    -> FG.PrettyFieldGrammar a a
+    -> a
+    -> Disp.Doc
+ppFgSection secName arg grammar x
+    | null prettyFields = Disp.empty
+    | otherwise         =
+        Disp.text secName <+> argDoc
+        $+$ (Disp.nest 2 fieldsDoc)
+  where
+    prettyFields = FG.prettyFieldGrammar cabalSpecLatest grammar x
+
+    argDoc | arg == "" = Disp.empty
+           | otherwise = Disp.text arg
+
+    fieldsDoc = Disp.vcat
+        [ Disp.text fname' <<>> Disp.colon <<>> doc
+        | F.PrettyField _ fname doc <- prettyFields -- TODO: this skips sections
+        , let fname' = fromUTF8BS fname
+        ]
+
 
 -----------------------------------------------
 -- Top level config file parsing and printing
@@ -268,15 +360,15 @@ ppSectionAndSubsections name arg fields sections cur
 --
 -- It accumulates the result on top of a given initial (typically empty) value.
 --
-parseConfig :: [FieldDescr a] -> [SectionDescr a] -> a
+parseConfig :: [FieldDescr a] -> [SectionDescr a] -> [FGSectionDescr a] -> a
             -> String -> ParseResult a
-parseConfig fieldDescrs sectionDescrs empty str =
-      parseFieldsAndSections fieldDescrs sectionDescrs empty
+parseConfig fieldDescrs sectionDescrs fgSectionDescrs empty str =
+      parseFieldsAndSections fieldDescrs sectionDescrs fgSectionDescrs empty
   =<< readFieldsFlat str
 
 -- | Render a value in the config file syntax, based on a description of the
 -- configuration file in terms of its fields and sections.
 --
-showConfig :: [FieldDescr a] -> [SectionDescr a] -> a -> Disp.Doc
+showConfig :: [FieldDescr a] -> [SectionDescr a] -> [FGSectionDescr a] -> a -> Disp.Doc
 showConfig = ppFieldsAndSections
 
diff --git a/cabal-install/Distribution/Client/ProjectBuilding.hs b/cabal-install/Distribution/Client/ProjectBuilding.hs
index 6f9020b9c14753df1582404232e083d5c7bde5a7..52fc8c3ea9821a4f7e8e31e36399d795a7becb25 100644
--- a/cabal-install/Distribution/Client/ProjectBuilding.hs
+++ b/cabal-install/Distribution/Client/ProjectBuilding.hs
@@ -65,15 +65,14 @@ import           Distribution.Client.GlobalFlags (RepoContext)
 import qualified Distribution.Client.Tar as Tar
 import           Distribution.Client.Setup
                    ( filterConfigureFlags, filterHaddockArgs
-                   , filterHaddockFlags )
+                   , filterHaddockFlags, filterTestFlags )
 import           Distribution.Client.SourceFiles
 import           Distribution.Client.SrcDist (allPackageSourceFiles)
 import           Distribution.Client.Utils
                    ( ProgressPhase(..), progressMessage, removeExistingFile )
 
 import           Distribution.Compat.Lens
-import           Distribution.Package hiding
-                   (InstalledPackageId, installedPackageId)
+import           Distribution.Package
 import qualified Distribution.PackageDescription as PD
 import           Distribution.InstalledPackageInfo (InstalledPackageInfo)
 import qualified Distribution.InstalledPackageInfo as Installed
@@ -96,6 +95,7 @@ import           Distribution.Verbosity
 import           Distribution.Pretty
 import           Distribution.Compat.Graph (IsNode(..))
 
+import qualified Data.List.NonEmpty as NE
 import           Data.Map (Map)
 import qualified Data.Map as Map
 import           Data.Set (Set)
@@ -1370,7 +1370,8 @@ buildInplaceUnpackedPackage verbosity
     buildArgs     _  = setupHsBuildArgs  pkg
 
     testCommand      = Cabal.testCommand -- defaultProgramDb
-    testFlags    _   = setupHsTestFlags pkg pkgshared
+    testFlags      v = flip filterTestFlags v $
+                       setupHsTestFlags pkg pkgshared
                                          verbosity builddir
     testArgs      _  = setupHsTestArgs  pkg
 
@@ -1444,7 +1445,7 @@ withTempInstalledPackageInfoFile verbosity tempdir action =
       (warns, ipkg) <-
         withUTF8FileContents (pkgConfDir </> pkgConfFile) $ \pkgConfStr ->
         case Installed.parseInstalledPackageInfo pkgConfStr of
-          Left perrors -> pkgConfParseFailed $ unlines perrors
+          Left perrors -> pkgConfParseFailed $ unlines $ NE.toList perrors
           Right (warns, ipkg) -> return (warns, ipkg)
 
       unless (null warns) $
diff --git a/cabal-install/Distribution/Client/ProjectConfig.hs b/cabal-install/Distribution/Client/ProjectConfig.hs
index a8b17131f40e7ca9233ff4b16d423aee0bfbd79b..23e3cd987e74f63804b3f39936fb2c34190f630d 100644
--- a/cabal-install/Distribution/Client/ProjectConfig.hs
+++ b/cabal-install/Distribution/Client/ProjectConfig.hs
@@ -1,4 +1,9 @@
-{-# LANGUAGE CPP, BangPatterns, RecordWildCards, NamedFieldPuns, DeriveDataTypeable, LambdaCase #-}
+{-# LANGUAGE BangPatterns       #-}
+{-# LANGUAGE CPP                #-}
+{-# LANGUAGE DeriveDataTypeable #-}
+{-# LANGUAGE LambdaCase         #-}
+{-# LANGUAGE NamedFieldPuns     #-}
+{-# LANGUAGE RecordWildCards    #-}
 
 -- | Handling project configuration.
 --
@@ -155,10 +160,10 @@ import Network.URI
 -- 'PackageName'. This returns the configuration that applies to all local
 -- packages plus any package-specific configuration for this package.
 --
-lookupLocalPackageConfig :: (Semigroup a, Monoid a)
-                         => (PackageConfig -> a)
-                         -> ProjectConfig
-                         -> PackageName -> a
+lookupLocalPackageConfig
+  :: (Semigroup a, Monoid a)
+  => (PackageConfig -> a) -> ProjectConfig -> PackageName
+  -> a
 lookupLocalPackageConfig field ProjectConfig {
                            projectConfigLocalPackages,
                            projectConfigSpecificPackage
@@ -189,10 +194,10 @@ projectConfigWithBuilderRepoContext verbosity BuildTimeSettings{..} =
 -- that doesn't have an http transport. And that avoids having to have access
 -- to the 'BuildTimeSettings'
 --
-projectConfigWithSolverRepoContext :: Verbosity
-                                   -> ProjectConfigShared
-                                   -> ProjectConfigBuildOnly
-                                   -> (RepoContext -> IO a) -> IO a
+projectConfigWithSolverRepoContext
+  :: Verbosity -> ProjectConfigShared -> ProjectConfigBuildOnly
+  -> (RepoContext -> IO a)
+  -> IO a
 projectConfigWithSolverRepoContext verbosity
                                    ProjectConfigShared{..}
                                    ProjectConfigBuildOnly{..} =
@@ -200,8 +205,10 @@ projectConfigWithSolverRepoContext verbosity
       verbosity
       (fromNubList projectConfigRemoteRepos)
       (fromNubList projectConfigLocalRepos)
-      (fromFlagOrDefault (error "projectConfigWithSolverRepoContext: projectConfigCacheDir")
-                         projectConfigCacheDir)
+      (fromFlagOrDefault
+                   (error
+                    "projectConfigWithSolverRepoContext: projectConfigCacheDir")
+                   projectConfigCacheDir)
       (flagToMaybe projectConfigHttpTransport)
       (flagToMaybe projectConfigIgnoreExpiry)
       (fromNubList projectConfigProgPathExtra)
@@ -444,7 +451,7 @@ renderBadProjectRoot :: BadProjectRoot -> String
 renderBadProjectRoot (BadProjectRootExplicitFile projectFile) =
     "The given project file '" ++ projectFile ++ "' does not exist."
 
-withProjectOrGlobalConfig :: Verbosity 
+withProjectOrGlobalConfig :: Verbosity
                           -> Flag FilePath
                           -> IO a
                           -> (ProjectConfig -> IO a)
@@ -455,9 +462,9 @@ withProjectOrGlobalConfig verbosity globalConfigFlag with without = do
   let
     res' = catch with
       $ \case
-        (BadPackageLocations prov locs) 
+        (BadPackageLocations prov locs)
           | prov == Set.singleton Implicit
-          , let 
+          , let
             isGlobErr (BadLocGlobEmptyMatch _) = True
             isGlobErr _ = False
           , any isGlobErr locs ->
@@ -1182,8 +1189,8 @@ syncAndReadSourcePackagesRemoteRepos verbosity
         entries <- liftIO $ getDirectoryContents packageDir
         --TODO: wrap exceptions
         case filter (\e -> takeExtension e == ".cabal") entries of
-          []       -> liftIO $ throwIO NoCabalFileFound
-          (_:_:_)  -> liftIO $ throwIO MultipleCabalFilesFound
+          []       -> liftIO $ throwIO $ NoCabalFileFound packageDir
+          (_:_:_)  -> liftIO $ throwIO $ MultipleCabalFilesFound packageDir
           [cabalFileName] -> do
             monitorFiles [monitorFileHashed cabalFilePath]
             liftIO $ fmap (mkSpecificSourcePackage location)
@@ -1222,11 +1229,11 @@ mkSpecificSourcePackage location pkg =
 -- | Errors reported upon failing to parse a @.cabal@ file.
 --
 data CabalFileParseError = CabalFileParseError
-    FilePath        -- ^ @.cabal@ file path
-    BS.ByteString   -- ^ @.cabal@ file contents
-    [PError]        -- ^ errors
-    (Maybe Version) -- ^ We might discover the spec version the package needs
-    [PWarning]      -- ^ warnings
+    FilePath           -- ^ @.cabal@ file path
+    BS.ByteString      -- ^ @.cabal@ file contents
+    (NonEmpty PError)  -- ^ errors
+    (Maybe Version)    -- ^ We might discover the spec version the package needs
+    [PWarning]         -- ^ warnings
   deriving (Typeable)
 
 -- | Manual instance which skips file contentes
@@ -1275,9 +1282,9 @@ readSourcePackageCabalFile verbosity pkgfilename content =
 -- | When looking for a package's @.cabal@ file we can find none, or several,
 -- both of which are failures.
 --
-data CabalFileSearchFailure =
-     NoCabalFileFound
-   | MultipleCabalFilesFound
+data CabalFileSearchFailure
+   = NoCabalFileFound FilePath
+   | MultipleCabalFilesFound FilePath
   deriving (Show, Typeable)
 
 instance Exception CabalFileSearchFailure
@@ -1291,7 +1298,7 @@ extractTarballPackageCabalFile :: FilePath -> IO (FilePath, BS.ByteString)
 extractTarballPackageCabalFile tarballFile =
     withBinaryFile tarballFile ReadMode $ \hnd -> do
       content <- LBS.hGetContents hnd
-      case extractTarballPackageCabalFilePure content of
+      case extractTarballPackageCabalFilePure tarballFile content of
         Left (Left  e) -> throwIO e
         Left (Right e) -> throwIO e
         Right (fileName, fileContent) ->
@@ -1300,11 +1307,12 @@ extractTarballPackageCabalFile tarballFile =
 
 -- | Scan through a tar file stream and collect the @.cabal@ file, or fail.
 --
-extractTarballPackageCabalFilePure :: LBS.ByteString
+extractTarballPackageCabalFilePure :: FilePath
+                                   -> LBS.ByteString
                                    -> Either (Either Tar.FormatError
                                                      CabalFileSearchFailure)
                                              (FilePath, LBS.ByteString)
-extractTarballPackageCabalFilePure =
+extractTarballPackageCabalFilePure tarballFile =
       check
     . accumEntryMap
     . Tar.filterEntries isCabalFile
@@ -1317,11 +1325,11 @@ extractTarballPackageCabalFilePure =
 
     check (Left (e, _m)) = Left (Left e)
     check (Right m) = case Map.elems m of
-        []     -> Left (Right NoCabalFileFound)
+        []     -> Left (Right $ NoCabalFileFound tarballFile)
         [file] -> case Tar.entryContent file of
           Tar.NormalFile content _ -> Right (Tar.entryPath file, content)
-          _                        -> Left (Right NoCabalFileFound)
-        _files -> Left (Right MultipleCabalFilesFound)
+          _                        -> Left (Right $ NoCabalFileFound tarballFile)
+        _files -> Left (Right $ MultipleCabalFilesFound tarballFile)
 
     isCabalFile e = case splitPath (Tar.entryPath e) of
       [     _dir, file] -> takeExtension file == ".cabal"
diff --git a/cabal-install/Distribution/Client/ProjectConfig/Legacy.hs b/cabal-install/Distribution/Client/ProjectConfig/Legacy.hs
index 620839cb7a43a74ad45e0bdde7e21daa5bfe53d5..1904d51be9d72d1432314a436e4cadfea247bc14 100644
--- a/cabal-install/Distribution/Client/ProjectConfig/Legacy.hs
+++ b/cabal-install/Distribution/Client/ProjectConfig/Legacy.hs
@@ -43,8 +43,7 @@ import Distribution.Package
 import Distribution.PackageDescription
          ( SourceRepo(..), RepoKind(..)
          , dispFlagAssignment )
-import Distribution.Client.SourceRepoParse
-         ( sourceRepoFieldDescrs )
+import Distribution.PackageDescription.FieldGrammar (sourceRepoFieldGrammar)
 import Distribution.Simple.Compiler
          ( OptimisationLevel(..), DebugInfoLevel(..) )
 import Distribution.Simple.InstallDirs ( CopyDest (NoCopyDest) )
@@ -73,16 +72,15 @@ import Distribution.Simple.LocalBuildInfo
 import Distribution.Deprecated.Text
 import qualified Distribution.Deprecated.ReadP as Parse
 import Distribution.Deprecated.ReadP
-         ( ReadP, (+++), (<++) )
-import qualified Text.Read as Read
+         ( ReadP, (+++) )
 import qualified Text.PrettyPrint as Disp
 import Text.PrettyPrint
          ( Doc, ($+$) )
 import qualified Distribution.Deprecated.ParseUtils as ParseUtils (field)
 import Distribution.Deprecated.ParseUtils
          ( ParseResult(..), PError(..), syntaxError, PWarning(..), warning
-         , simpleField, commaNewLineListField
-         , showToken )
+         , simpleField, commaNewLineListField, newLineListField, parseTokenQ
+         , parseHaskellString, showToken )
 import Distribution.Client.ParseUtils
 import Distribution.Simple.Command
          ( CommandUI(commandOptions), ShowOrParseArgs(..)
@@ -242,11 +240,11 @@ convertLegacyGlobalConfig
   where
     --TODO: [code cleanup] eliminate use of default*Flags here and specify the
     -- defaults in the various resolve functions in terms of the new types.
-    configExFlags' = defaultConfigExFlags <> configExFlags
-    installFlags'  = defaultInstallFlags  <> installFlags
-    clientInstallFlags'  = defaultClientInstallFlags  <> clientInstallFlags
-    haddockFlags'  = defaultHaddockFlags  <> haddockFlags
-    testFlags'     = defaultTestFlags     <> testFlags
+    configExFlags'      = defaultConfigExFlags      <> configExFlags
+    installFlags'       = defaultInstallFlags       <> installFlags
+    clientInstallFlags' = defaultClientInstallFlags <> clientInstallFlags
+    haddockFlags'       = defaultHaddockFlags       <> haddockFlags
+    testFlags'          = defaultTestFlags          <> testFlags
 
     configAllPackages   = convertLegacyPerPackageFlags
                             configFlags installFlags' haddockFlags' testFlags'
@@ -450,6 +448,7 @@ convertLegacyPerPackageFlags configFlags installFlags haddockFlags testFlags =
       testMachineLog            = packageConfigTestMachineLog,
       testShowDetails           = packageConfigTestShowDetails,
       testKeepTix               = packageConfigTestKeepTix,
+      testWrapper               = packageConfigTestWrapper,
       testFailWhenNoTestSuites  = packageConfigTestFailWhenNoTestSuites,
       testOptions               = packageConfigTestTestOptions
     } = testFlags
@@ -686,7 +685,8 @@ convertToLegacyAllPackageConfig
       configFlagError           = mempty,                --TODO: ???
       configRelocatable         = mempty,
       configDebugInfo           = mempty,
-      configUseResponseFiles    = mempty
+      configUseResponseFiles    = mempty,
+      configAllowDependingOnPrivateLibs = mempty
     }
 
     haddockFlags = mempty {
@@ -756,7 +756,8 @@ convertToLegacyPerPackageConfig PackageConfig {..} =
       configFlagError           = mempty,                --TODO: ???
       configRelocatable         = packageConfigRelocatable,
       configDebugInfo           = packageConfigDebugInfo,
-      configUseResponseFiles    = mempty
+      configUseResponseFiles    = mempty,
+      configAllowDependingOnPrivateLibs = mempty
     }
 
     installFlags = mempty {
@@ -795,6 +796,7 @@ convertToLegacyPerPackageConfig PackageConfig {..} =
       testMachineLog  = packageConfigTestMachineLog,
       testShowDetails = packageConfigTestShowDetails,
       testKeepTix     = packageConfigTestKeepTix,
+      testWrapper     = packageConfigTestWrapper,
       testFailWhenNoTestSuites = packageConfigTestFailWhenNoTestSuites,
       testOptions     = packageConfigTestTestOptions
     }
@@ -808,6 +810,7 @@ parseLegacyProjectConfig :: String -> ParseResult LegacyProjectConfig
 parseLegacyProjectConfig =
     parseConfig legacyProjectConfigFieldDescrs
                 legacyPackageConfigSectionDescrs
+                legacyPackageConfigFGSectionDescrs
                 mempty
 
 showLegacyProjectConfig :: LegacyProjectConfig -> String
@@ -815,6 +818,7 @@ showLegacyProjectConfig config =
     Disp.render $
     showConfig  legacyProjectConfigFieldDescrs
                 legacyPackageConfigSectionDescrs
+                legacyPackageConfigFGSectionDescrs
                 config
   $+$
     Disp.text ""
@@ -1090,7 +1094,8 @@ legacyPackageConfigFieldDescrs =
           (\v conf -> conf { testOptions = v })
       ]
   . filterFields
-      [ "log", "machine-log", "show-details", "keep-tix-files", "fail-when-no-test-suites" ]
+      [ "log", "machine-log", "show-details", "keep-tix-files"
+      , "fail-when-no-test-suites", "test-wrapper" ]
   . commandOptionsToFields
   ) (testOptions' ParseArgs)
 
@@ -1161,10 +1166,14 @@ legacyPackageConfigFieldDescrs =
                     | otherwise = "test-" ++ name
 
 
+legacyPackageConfigFGSectionDescrs :: [FGSectionDescr LegacyProjectConfig]
+legacyPackageConfigFGSectionDescrs =
+    [ packageRepoSectionDescr
+    ]
+
 legacyPackageConfigSectionDescrs :: [SectionDescr LegacyProjectConfig]
 legacyPackageConfigSectionDescrs =
-    [ packageRepoSectionDescr
-    , packageSpecificOptionsSectionDescr
+    [ packageSpecificOptionsSectionDescr
     , liftSection
         legacyLocalConfig
         (\flags conf -> conf { legacyLocalConfig = flags })
@@ -1182,31 +1191,19 @@ legacyPackageConfigSectionDescrs =
         remoteRepoSectionDescr
     ]
 
-packageRepoSectionDescr :: SectionDescr LegacyProjectConfig
-packageRepoSectionDescr =
-    SectionDescr {
-      sectionName        = "source-repository-package",
-      sectionFields      = sourceRepoFieldDescrs,
-      sectionSubsections = [],
-      sectionGet         = map (\x->("", x))
-                         . legacyPackagesRepo,
-      sectionSet         =
+packageRepoSectionDescr :: FGSectionDescr LegacyProjectConfig
+packageRepoSectionDescr = FGSectionDescr
+  { fgSectionName        = "source-repository-package"
+  , fgSectionGrammar     = sourceRepoFieldGrammar (RepoKindUnknown "unused")
+  , fgSectionGet         = map (\x->("", x)) . legacyPackagesRepo
+  , fgSectionSet         =
         \lineno unused pkgrepo projconf -> do
           unless (null unused) $
             syntaxError lineno "the section 'source-repository-package' takes no arguments"
           return projconf {
             legacyPackagesRepo = legacyPackagesRepo projconf ++ [pkgrepo]
-          },
-      sectionEmpty       = SourceRepo {
-                             repoKind     = RepoThis, -- hopefully unused
-                             repoType     = Nothing,
-                             repoLocation = Nothing,
-                             repoModule   = Nothing,
-                             repoBranch   = Nothing,
-                             repoTag      = Nothing,
-                             repoSubdir   = Nothing
-                           }
-    }
+          }
+  }
 
 -- | The definitions of all the fields that can appear in the @package pkgfoo@
 -- and @package *@ sections of the @cabal.project@-format files.
@@ -1388,26 +1385,6 @@ remoteRepoSectionDescr =
 -- Local field utils
 --
 
---TODO: [code cleanup] all these utils should move to Distribution.Deprecated.ParseUtils
--- either augmenting or replacing the ones there
-
---TODO: [code cleanup] this is a different definition from listField, like
--- commaNewLineListField it pretty prints on multiple lines
-newLineListField :: String -> (a -> Doc) -> ReadP [a] a
-                 -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
-newLineListField = listFieldWithSep Disp.sep
-
---TODO: [code cleanup] local copy purely so we can use the fixed version
--- of parseOptCommaList below
-listFieldWithSep :: ([Doc] -> Doc) -> String -> (a -> Doc) -> ReadP [a] a
-                 -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
-listFieldWithSep separator name showF readF get' set =
-  liftField get' set' $
-    ParseUtils.field name showF' (parseOptCommaList readF)
-  where
-    set' xs b = set (get' b ++ xs) b
-    showF'    = separator . map showF
-
 -- | Parser combinator for simple fields which uses the field type's
 -- 'Monoid' instance for combining multiple occurences of the field.
 monoidField :: Monoid a => String -> (a -> Doc) -> ReadP a a
@@ -1417,15 +1394,6 @@ monoidField name showF readF get' set =
   where
     set' xs b = set (get' b `mappend` xs) b
 
---TODO: [code cleanup] local redefinition that should replace the version in
--- D.ParseUtils. This version avoid parse ambiguity for list element parsers
--- that have multiple valid parses of prefixes.
-parseOptCommaList :: ReadP r a -> ReadP r [a]
-parseOptCommaList p = Parse.sepBy p sep
-  where
-    -- The separator must not be empty or it introduces ambiguity
-    sep = (Parse.skipSpaces >> Parse.char ',' >> Parse.skipSpaces)
-      +++ (Parse.satisfy isSpace >> Parse.skipSpaces)
 
 --TODO: [code cleanup] local redefinition that should replace the version in
 -- D.ParseUtils called showFilePath. This version escapes "." and "--" which
@@ -1436,19 +1404,6 @@ showTokenQ x@('-':'-':_) = Disp.text (show x)
 showTokenQ x@('.':[])    = Disp.text (show x)
 showTokenQ x             = showToken x
 
--- This is just a copy of parseTokenQ, using the fixed parseHaskellString
-parseTokenQ :: ReadP r String
-parseTokenQ = parseHaskellString
-          <++ Parse.munch1 (\x -> not (isSpace x) && x /= ',')
-
---TODO: [code cleanup] use this to replace the parseHaskellString in
--- Distribution.Deprecated.ParseUtils. It turns out Read instance for String accepts
--- the ['a', 'b'] syntax, which we do not want. In particular it messes
--- up any token starting with [].
-parseHaskellString :: ReadP r String
-parseHaskellString =
-  Parse.readS_to_P $
-    Read.readPrec_to_S (do Read.String s <- Read.lexP; return s) 0
 
 -- Handy util
 addFields :: [FieldDescr a]
diff --git a/cabal-install/Distribution/Client/ProjectConfig/Types.hs b/cabal-install/Distribution/Client/ProjectConfig/Types.hs
index 137f73dbabb901f3c7eda12047aa120be09760e1..7472102c9b3b92e54df6c07def1fcee8fb374705 100644
--- a/cabal-install/Distribution/Client/ProjectConfig/Types.hs
+++ b/cabal-install/Distribution/Client/ProjectConfig/Types.hs
@@ -291,6 +291,7 @@ data PackageConfig
        packageConfigTestMachineLog      :: Flag PathTemplate,
        packageConfigTestShowDetails     :: Flag TestShowDetails,
        packageConfigTestKeepTix         :: Flag Bool,
+       packageConfigTestWrapper         :: Flag FilePath,
        packageConfigTestFailWhenNoTestSuites :: Flag Bool,
        packageConfigTestTestOptions     :: [PathTemplate]
      }
diff --git a/cabal-install/Distribution/Client/ProjectOrchestration.hs b/cabal-install/Distribution/Client/ProjectOrchestration.hs
index 86d38baf887eee8f96ec1bb5321a31e566c7fd43..5c35118ecd02e1f9a6c8994e9f0d0f6f993f3357 100644
--- a/cabal-install/Distribution/Client/ProjectOrchestration.hs
+++ b/cabal-install/Distribution/Client/ProjectOrchestration.hs
@@ -41,6 +41,7 @@
 --
 module Distribution.Client.ProjectOrchestration (
     -- * Discovery phase: what is in the project?
+    CurrentCommand(..),
     establishProjectBaseContext,
     ProjectBaseContext(..),
     BuildTimeSettings(..),
@@ -135,7 +136,6 @@ import           Distribution.Types.UnqualComponentName
 import           Distribution.Solver.Types.OptionalStanza
 
 import           Distribution.Package
-                   hiding (InstalledPackageId, installedPackageId)
 import           Distribution.PackageDescription
                    ( FlagAssignment, unFlagAssignment, showFlagValue
                    , diffFlagAssignment )
@@ -169,6 +169,11 @@ import           System.Posix.Signals (sigKILL, sigSEGV)
 #endif
 
 
+-- | Tracks what command is being executed, because we need to hide this somewhere
+-- for cases that need special handling (usually for error reporting).
+data CurrentCommand = InstallCommand | HaddockCommand | OtherCommand
+                    deriving (Show, Eq)
+
 -- | This holds the context of a project prior to solving: the content of the
 -- @cabal.project@ and all the local package @.cabal@ files.
 --
@@ -177,13 +182,15 @@ data ProjectBaseContext = ProjectBaseContext {
        cabalDirLayout :: CabalDirLayout,
        projectConfig  :: ProjectConfig,
        localPackages  :: [PackageSpecifier UnresolvedSourcePackage],
-       buildSettings  :: BuildTimeSettings
+       buildSettings  :: BuildTimeSettings,
+       currentCommand :: CurrentCommand
      }
 
 establishProjectBaseContext :: Verbosity
                             -> ProjectConfig
+                            -> CurrentCommand
                             -> IO ProjectBaseContext
-establishProjectBaseContext verbosity cliConfig = do
+establishProjectBaseContext verbosity cliConfig currentCommand = do
 
     cabalDir <- getCabalDir
     projectRoot <- either throwIO return =<<
@@ -219,7 +226,8 @@ establishProjectBaseContext verbosity cliConfig = do
       cabalDirLayout,
       projectConfig,
       localPackages,
-      buildSettings
+      buildSettings,
+      currentCommand
     }
   where
     mdistDirectory = Setup.flagToMaybe projectConfigDistDir
@@ -423,7 +431,7 @@ runProjectPostBuildPhase verbosity
 
     -- Finally if there were any build failures then report them and throw
     -- an exception to terminate the program
-    dieOnBuildFailures verbosity elaboratedPlanToExecute buildOutcomes
+    dieOnBuildFailures verbosity currentCommand elaboratedPlanToExecute buildOutcomes
 
     -- Note that it is a deliberate design choice that the 'buildTargets' is
     -- not passed to phase 1, and the various bits of input config is not
@@ -972,9 +980,9 @@ printPlan verbosity
 
 -- | If there are build failures then report them and throw an exception.
 --
-dieOnBuildFailures :: Verbosity
+dieOnBuildFailures :: Verbosity -> CurrentCommand
                    -> ElaboratedInstallPlan -> BuildOutcomes -> IO ()
-dieOnBuildFailures verbosity plan buildOutcomes
+dieOnBuildFailures verbosity currentCommand plan buildOutcomes
   | null failures = return ()
 
   | isSimpleCase  = exitFailure
@@ -1022,6 +1030,7 @@ dieOnBuildFailures verbosity plan buildOutcomes
       ]
 
     dieIfNotHaddockFailure
+      | currentCommand == HaddockCommand            = die'
       | all isHaddockFailure failuresClassification = warn
       | otherwise                                   = die'
       where
@@ -1061,6 +1070,7 @@ dieOnBuildFailures verbosity plan buildOutcomes
       , [pkg]              <- rootpkgs
       , installedUnitId pkg == pkgid
       , isFailureSelfExplanatory (buildFailureReason failure)
+      , currentCommand /= InstallCommand
       = True
       | otherwise
       = False
diff --git a/cabal-install/Distribution/Client/ProjectPlanning.hs b/cabal-install/Distribution/Client/ProjectPlanning.hs
index 1ee366532b46aa538192b3969cafffe8d1024bfd..a0a6b1835476aa1bc10feb2d73704fa9d32564fc 100644
--- a/cabal-install/Distribution/Client/ProjectPlanning.hs
+++ b/cabal-install/Distribution/Client/ProjectPlanning.hs
@@ -110,8 +110,7 @@ import           Distribution.Solver.Types.SourcePackage
 import           Distribution.Solver.Types.Settings
 
 import           Distribution.ModuleName
-import           Distribution.Package hiding
-  (InstalledPackageId, installedPackageId)
+import           Distribution.Package
 import           Distribution.Types.AnnotatedId
 import           Distribution.Types.ComponentName
 import           Distribution.Types.LibraryName
@@ -1884,6 +1883,7 @@ elaborateInstallPlan verbosity platform compiler compilerprogdb pkgConfigDB
         elabTestHumanLog        = perPkgOptionMaybe pkgid packageConfigTestHumanLog
         elabTestShowDetails     = perPkgOptionMaybe pkgid packageConfigTestShowDetails
         elabTestKeepTix         = perPkgOptionFlag pkgid False packageConfigTestKeepTix
+        elabTestWrapper         = perPkgOptionMaybe pkgid packageConfigTestWrapper
         elabTestFailWhenNoTestSuites = perPkgOptionFlag pkgid False packageConfigTestFailWhenNoTestSuites
         elabTestTestOptions     = perPkgOptionList pkgid packageConfigTestTestOptions
 
@@ -3390,6 +3390,9 @@ setupHsConfigureFlags (ReadyPackage elab@ElaboratedConfiguredPackage{..})
     configUserInstall         = mempty -- don't rely on defaults
     configPrograms_           = mempty -- never use, shouldn't exist
     configUseResponseFiles    = mempty
+    -- TODO set to true when the solver can prevent private-library-deps by itself
+    -- (issue #6039)
+    configAllowDependingOnPrivateLibs = mempty
 
 setupHsConfigureArgs :: ElaboratedConfiguredPackage
                      -> [String]
@@ -3440,6 +3443,7 @@ setupHsTestFlags (ElaboratedConfiguredPackage{..}) _ verbosity builddir = Cabal.
     , testHumanLog    = maybe mempty toFlag elabTestHumanLog
     , testShowDetails = maybe (Flag Cabal.Always) toFlag elabTestShowDetails
     , testKeepTix     = toFlag elabTestKeepTix
+    , testWrapper     = maybe mempty toFlag elabTestWrapper
     , testFailWhenNoTestSuites = toFlag elabTestFailWhenNoTestSuites
     , testOptions     = elabTestTestOptions
     }
diff --git a/cabal-install/Distribution/Client/ProjectPlanning/Types.hs b/cabal-install/Distribution/Client/ProjectPlanning/Types.hs
index 60959532d0595e9b3b2e19194b71f893b353e9bf..af2ed744db11f4692aa7b3b47038ac02fa14a292 100644
--- a/cabal-install/Distribution/Client/ProjectPlanning/Types.hs
+++ b/cabal-install/Distribution/Client/ProjectPlanning/Types.hs
@@ -81,7 +81,6 @@ import           Distribution.Types.ComponentRequestedSpec
 import           Distribution.Types.PkgconfigVersion
 import           Distribution.Types.PackageDescription (PackageDescription(..))
 import           Distribution.Package
-                   hiding (InstalledPackageId, installedPackageId)
 import           Distribution.System
 import qualified Distribution.PackageDescription as Cabal
 import           Distribution.InstalledPackageInfo (InstalledPackageInfo)
@@ -294,6 +293,7 @@ data ElaboratedConfiguredPackage
        elabTestHumanLog          :: Maybe PathTemplate,
        elabTestShowDetails       :: Maybe TestShowDetails,
        elabTestKeepTix           :: Bool,
+       elabTestWrapper           :: Maybe FilePath,
        elabTestFailWhenNoTestSuites :: Bool,
        elabTestTestOptions       :: [PathTemplate],
 
diff --git a/cabal-install/Distribution/Client/Security/HTTP.hs b/cabal-install/Distribution/Client/Security/HTTP.hs
index d91ba1f4f073b32a0528a37718d172a088efdf5d..f9c8bb99d0df6db9db6ecc16fe453037c19eddeb 100644
--- a/cabal-install/Distribution/Client/Security/HTTP.hs
+++ b/cabal-install/Distribution/Client/Security/HTTP.hs
@@ -153,7 +153,7 @@ data UnexpectedResponse = UnexpectedResponse URI Int
 
 instance Pretty UnexpectedResponse where
   pretty (UnexpectedResponse uri code) = "Unexpected response " ++ show code
-                                      ++ "for " ++ show uri
+                                      ++ " for " ++ show uri
 
 #if MIN_VERSION_base(4,8,0)
 deriving instance Show UnexpectedResponse
diff --git a/cabal-install/Distribution/Client/Setup.hs b/cabal-install/Distribution/Client/Setup.hs
index 327e4f4611a144cc640d50234dca096df961d791..230c42ebd69baed1593b0d1768ff5e2e7075e60c 100644
--- a/cabal-install/Distribution/Client/Setup.hs
+++ b/cabal-install/Distribution/Client/Setup.hs
@@ -22,6 +22,7 @@ module Distribution.Client.Setup
     , configPackageDB', configCompilerAux'
     , configureExCommand, ConfigExFlags(..), defaultConfigExFlags
     , buildCommand, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..)
+    , filterTestFlags
     , replCommand, testCommand, benchmarkCommand, testOptions
                         , configureExOptions, reconfigureCommand
     , installCommand, InstallFlags(..), installOptions, defaultInstallFlags
@@ -829,6 +830,37 @@ instance Monoid BuildExFlags where
 instance Semigroup BuildExFlags where
   (<>) = gmappend
 
+-- ------------------------------------------------------------
+-- * Test flags
+-- ------------------------------------------------------------
+
+-- | Given some 'TestFlags' for the version of Cabal that
+-- cabal-install was built with, and a target older 'Version' of
+-- Cabal that we want to pass these flags to, convert the
+-- flags into a form that will be accepted by the older
+-- Setup script.  Generally speaking, this just means filtering
+-- out flags that the old Cabal library doesn't understand, but
+-- in some cases it may also mean "emulating" a feature using
+-- some more legacy flags.
+filterTestFlags :: TestFlags -> Version -> TestFlags
+filterTestFlags flags cabalLibVersion
+  -- NB: we expect the latest version to be the most common case,
+  -- so test it first.
+  | cabalLibVersion >= mkVersion [3,0,0] = flags_latest
+  -- The naming convention is that flags_version gives flags with
+  -- all flags *introduced* in version eliminated.
+  -- It is NOT the latest version of Cabal library that
+  -- these flags work for; version of introduction is a more
+  -- natural metric.
+  | cabalLibVersion <  mkVersion [3,0,0] = flags_3_0_0
+  | otherwise = error "the impossible just happened" -- see first guard
+  where
+    flags_latest = flags
+    flags_3_0_0  = flags_latest {
+      -- Cabal < 3.0 doesn't know about --test-wrapper
+      Cabal.testWrapper = NoFlag
+      }
+
 -- ------------------------------------------------------------
 -- * Repl command
 -- ------------------------------------------------------------
@@ -1233,7 +1265,7 @@ outdatedCommand = CommandUI {
      outdatedFreezeFile (\v flags -> flags { outdatedFreezeFile = v })
      trueArg
 
-    ,option [] ["new-freeze-file", "v2-freeze-file"]
+    ,option [] ["v2-freeze-file", "new-freeze-file"]
      "Act on the new-style freeze file (default: cabal.project.freeze)"
      outdatedNewFreezeFile (\v flags -> flags { outdatedNewFreezeFile = v })
      trueArg
@@ -1929,7 +1961,8 @@ testOptions showOrParseArgs
     | opt <- commandOptions Cabal.testCommand showOrParseArgs
     , let name = optionName opt
     , name `elem` ["log", "machine-log", "show-details", "keep-tix-files"
-                  ,"fail-when-no-test-suites", "test-options", "test-option"]
+                  ,"fail-when-no-test-suites", "test-options", "test-option"
+                  ,"test-wrapper"]
     ]
   where
     prefixTest name | "test-" `isPrefixOf` name = name
diff --git a/cabal-install/Distribution/Client/SetupWrapper.hs b/cabal-install/Distribution/Client/SetupWrapper.hs
index df4c4e37bfbf2c0c6aae589af608761c933928a6..d422a2fddfb7afe1bf81469ef016b2de46f23f84 100644
--- a/cabal-install/Distribution/Client/SetupWrapper.hs
+++ b/cabal-install/Distribution/Client/SetupWrapper.hs
@@ -311,7 +311,7 @@ getSetup verbosity options mpkg = do
                , setupPackage = pkg
                }
   where
-    getPkg = tryFindPackageDesc (fromMaybe "." (useWorkingDir options))
+    getPkg = tryFindPackageDesc verbosity (fromMaybe "." (useWorkingDir options))
          >>= readGenericPackageDescription verbosity
          >>= return . packageDescription
 
diff --git a/cabal-install/Distribution/Client/TargetSelector.hs b/cabal-install/Distribution/Client/TargetSelector.hs
index 6949f6a5f9ab7f0e84bcb3b4b5c219010a459851..bb39376f26913e791b202e2fc7767c3ebdda8f24 100644
--- a/cabal-install/Distribution/Client/TargetSelector.hs
+++ b/cabal-install/Distribution/Client/TargetSelector.hs
@@ -102,6 +102,7 @@ import System.FilePath
 import Text.EditDistance
          ( defaultEditCosts, restrictedDamerauLevenshteinDistance )
 
+import qualified Prelude (foldr1)
 
 -- ------------------------------------------------------------
 -- * Target selector terms
@@ -930,8 +931,8 @@ syntaxForms KnownTargets {
       , syntaxForm7MetaNamespacePackageKindComponentNamespaceFile   pinfo
       ]
   where
-    ambiguousAlternatives = foldr1 AmbiguousAlternatives
-    shadowingAlternatives = foldr1 ShadowingAlternatives
+    ambiguousAlternatives = Prelude.foldr1 AmbiguousAlternatives
+    shadowingAlternatives = Prelude.foldr1 ShadowingAlternatives
 
 
 -- | Syntax: "all" to select all packages in the project
diff --git a/cabal-install/Distribution/Client/Utils/Parsec.hs b/cabal-install/Distribution/Client/Utils/Parsec.hs
index c55a428e19a4c37dcb737c59f6f32a37f65cf189..b0afe8f57671166eb49659856bb59544631b1e12 100644
--- a/cabal-install/Distribution/Client/Utils/Parsec.hs
+++ b/cabal-install/Distribution/Client/Utils/Parsec.hs
@@ -16,7 +16,7 @@ import Distribution.Simple.Utils (fromUTF8BS)
 renderParseError
     :: FilePath
     -> BS.ByteString
-    -> [PError]
+    -> NonEmpty PError
     -> [PWarning]
     -> String
 renderParseError filepath contents errors warnings = unlines $
diff --git a/cabal-install/Distribution/Deprecated/ParseUtils.hs b/cabal-install/Distribution/Deprecated/ParseUtils.hs
index f6c5c45878408a6e82105bb4b22c645013d66d2c..cda1e5bde7ca561b659ce0397cf2e3b81d983704 100644
--- a/cabal-install/Distribution/Deprecated/ParseUtils.hs
+++ b/cabal-install/Distribution/Deprecated/ParseUtils.hs
@@ -28,14 +28,14 @@ module Distribution.Deprecated.ParseUtils (
         FieldDescr(..), ppField, ppFields, readFields, readFieldsFlat,
         showFields, showSingleNamedField, showSimpleSingleNamedField,
         parseFields, parseFieldsFlat,
-        parseFilePathQ, parseTokenQ, parseTokenQ',
+        parseHaskellString, parseFilePathQ, parseTokenQ, parseTokenQ',
         parseModuleNameQ,
         parseFlagAssignment,
         parseOptVersion, parsePackageName,
         parseSepList, parseCommaList, parseOptCommaList,
         showFilePath, showToken, showTestedWith, showFreeText, parseFreeText,
         field, simpleField, listField, listFieldWithSep, spaceListField,
-        commaListField, commaListFieldWithSep, commaNewLineListField,
+        commaListField, commaListFieldWithSep, commaNewLineListField, newLineListField,
         optsField, liftField, boolField, parseQuoted, parseMaybeQuoted,
         readPToMaybe,
 
@@ -58,13 +58,13 @@ import Distribution.Utils.Generic
 import Distribution.Version
 import Distribution.PackageDescription (FlagAssignment, mkFlagAssignment)
 
-import Data.Tree        as Tree (Tree (..), flatten)
+import Data.Tree as Tree (Tree (..), flatten)
 import System.FilePath  (normalise)
 import Text.PrettyPrint
        (Doc, Mode (..), colon, comma, fsep, hsep, isEmpty, mode, nest, punctuate, render,
        renderStyle, sep, style, text, vcat, ($+$), (<+>))
-
-import qualified Data.Map                      as Map
+import qualified Text.Read as Read
+import qualified Data.Map  as Map
 
 import qualified Control.Monad.Fail as Fail
 
@@ -231,6 +231,12 @@ spaceListField name showF readF get set =
     set' xs b = set (get b ++ xs) b
     showF'    = fsep . map showF
 
+-- this is a different definition from listField, like
+-- commaNewLineListField it pretty prints on multiple lines
+newLineListField :: String -> (a -> Doc) -> ReadP [a] a
+                 -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
+newLineListField = listFieldWithSep sep
+
 listFieldWithSep :: Separator -> String -> (a -> Doc) -> ReadP [a] a
                  -> (b -> [a]) -> ([a] -> b -> b) -> FieldDescr b
 listFieldWithSep separator name showF readF get set =
@@ -622,8 +628,13 @@ parseOptVersion = parseMaybeQuoted ver
 -- particular, the type of <++ is ReadP r r -> ReadP r a -> ReadP r a
 -- Hence the trick above to make 'lic' polymorphic.
 
+-- Different than the naive version. it turns out Read instance for String accepts
+-- the ['a', 'b'] syntax, which we do not want. In particular it messes
+-- up any token starting with [].
 parseHaskellString :: ReadP r String
-parseHaskellString = readS_to_P reads
+parseHaskellString =
+  readS_to_P $
+    Read.readPrec_to_S (do Read.String s <- Read.lexP; return s) 0
 
 parseTokenQ :: ReadP r String
 parseTokenQ = parseHaskellString <++ munch1 (\x -> not (isSpace x) && x /= ',')
@@ -645,9 +656,14 @@ parseCommaList :: ReadP r a -- ^The parser for the stuff between commas
                -> ReadP r [a]
 parseCommaList = parseSepList (ReadP.char ',')
 
-parseOptCommaList :: ReadP r a -- ^The parser for the stuff between commas
-                  -> ReadP r [a]
-parseOptCommaList = parseSepList (optional (ReadP.char ','))
+-- This version avoid parse ambiguity for list element parsers
+-- that have multiple valid parses of prefixes.
+parseOptCommaList :: ReadP r a -> ReadP r [a]
+parseOptCommaList p = sepBy p localSep
+  where
+    -- The separator must not be empty or it introduces ambiguity
+    localSep = (skipSpaces >> char ',' >> skipSpaces)
+      +++ (satisfy isSpace >> skipSpaces)
 
 parseQuoted :: ReadP r a -> ReadP r a
 parseQuoted = between (ReadP.char '"') (ReadP.char '"')
@@ -705,4 +721,4 @@ parseFlagAssignment = mkFlagAssignment <$>
 -------------------------------------------------------------------------------
 
 showTestedWith :: (CompilerFlavor, VersionRange) -> Doc
-showTestedWith = pretty . pack' TestedWith
+showTestedWith = pretty . pack' TestedWith
\ No newline at end of file
diff --git a/cabal-install/Distribution/Deprecated/Text.hs b/cabal-install/Distribution/Deprecated/Text.hs
index b685f8128c7ae651048919566a60dea80f569ebe..44f2d8996372fd14ed84ed1b391350e42a9a7088 100644
--- a/cabal-install/Distribution/Deprecated/Text.hs
+++ b/cabal-install/Distribution/Deprecated/Text.hs
@@ -48,6 +48,7 @@ import qualified Distribution.Types.PackageVersionConstraint as D
 import qualified Distribution.Types.SourceRepo               as D
 import qualified Distribution.Types.UnqualComponentName      as D
 import qualified Distribution.Version                        as D
+import qualified Distribution.Types.VersionRange.Internal    as D
 import qualified Language.Haskell.Extension                  as E
 
 -- | /Note:/ this class will soon be deprecated.
diff --git a/cabal-install/Distribution/Solver/Types/ComponentDeps.hs b/cabal-install/Distribution/Solver/Types/ComponentDeps.hs
index d1beb401cb8dab427df394739e5501b960e6f75d..87d5d65f2c1bc5d582f3ed07fc0ed7d571fa30d6 100644
--- a/cabal-install/Distribution/Solver/Types/ComponentDeps.hs
+++ b/cabal-install/Distribution/Solver/Types/ComponentDeps.hs
@@ -119,9 +119,9 @@ insert comp a = ComponentDeps . Map.alter aux comp . unComponentDeps
 
 -- | Zip two 'ComponentDeps' together by 'Component', using 'mempty'
 -- as the neutral element when a 'Component' is present only in one.
-zip :: (Monoid a, Monoid b) => ComponentDeps a -> ComponentDeps b -> ComponentDeps (a, b)
-{- TODO/FIXME: Once we can expect containers>=0.5, switch to the more efficient version below:
-
+zip
+  :: (Monoid a, Monoid b)
+  => ComponentDeps a -> ComponentDeps b -> ComponentDeps (a, b)
 zip (ComponentDeps d1) (ComponentDeps d2) =
     ComponentDeps $
       Map.mergeWithKey
@@ -130,15 +130,6 @@ zip (ComponentDeps d1) (ComponentDeps d2) =
         (fmap (\b -> (mempty, b)))
         d1 d2
 
--}
-zip (ComponentDeps d1) (ComponentDeps d2) =
-    ComponentDeps $
-      Map.unionWith
-        mappend
-        (Map.map (\a -> (a, mempty)) d1)
-        (Map.map (\b -> (mempty, b)) d2)
-
-
 -- | Keep only selected components (and their associated deps info).
 filterDeps :: (Component -> a -> Bool) -> ComponentDeps a -> ComponentDeps a
 filterDeps p = ComponentDeps . Map.filterWithKey p . unComponentDeps
diff --git a/cabal-install/Distribution/Solver/Types/PackageIndex.hs b/cabal-install/Distribution/Solver/Types/PackageIndex.hs
index 9946ba26b814fa09665035c60a108811a7f9be37..c7a1ce0c0e6c5bd92315dec1dd8bf80566bc68bc 100644
--- a/cabal-install/Distribution/Solver/Types/PackageIndex.hs
+++ b/cabal-install/Distribution/Solver/Types/PackageIndex.hs
@@ -60,6 +60,7 @@ import Distribution.Version
 import Distribution.Simple.Utils
          ( lowercase, comparing )
 
+import qualified Prelude (foldr1)
 
 -- | The collection of information about packages from one or more 'PackageDB's.
 --
@@ -85,7 +86,7 @@ instance Package pkg => Monoid (PackageIndex pkg) where
   mappend = (<>)
   --save one mappend with empty in the common case:
   mconcat [] = mempty
-  mconcat xs = foldr1 mappend xs
+  mconcat xs = Prelude.foldr1 mappend xs
 
 instance Binary pkg => Binary (PackageIndex pkg)
 
diff --git a/cabal-install/bash-completion/cabal b/cabal-install/bash-completion/cabal
index 30acefaed3ef0858d375fbf3d1c2a7701ba93c1f..800579ad5aff00814896d6974a542e659b30dc7f 100644
--- a/cabal-install/bash-completion/cabal
+++ b/cabal-install/bash-completion/cabal
@@ -1,16 +1,52 @@
 #!/bin/bash
 
-### -*- mode: shell-script; -*-
-
 ##################################################
 
 # cabal command line completion
 #
 # Copyright 2007-2008 "Lennart Kolmodin" <kolmodin@gentoo.org>
 #                     "Duncan Coutts"    <dcoutts@gentoo.org>
-#                     "Sam Boosalis"     <samboosalis@gmail.com>
+# Copyright 2019-     "Sam Boosalis"     <samboosalis@gmail.com>
+#
+
+# Compatibility — Bash 3.
+#
+# OSX won't update Bash 3 (last updated circa 2009) to Bash 4,
+# and we'd like this completion script to work on both Linux and Mac.
+#
+# For example, OSX Yosemite (released circa 2014) ships with Bash 3:
+#
+#  $ echo $BASH_VERSION
+#  3.2
+#
+# While Ubuntu LTS 14.04 (a.k.a. Trusty, also released circa 2016)
+# ships with the latest version, Bash 4 (updated circa 2016):
+#
+#  $ echo $BASH_VERSION
+#  4.3
+#
+
+# Testing
+#
+# (1) Invoke « shellcheck »
+#
+#     * source: « https://github.com/koalaman/shellcheck »
+#     * run:    « shellcheck ./cabal-install/bash-completion/cabal »
+#
+# (2) Interpret via Bash 3
+#
+#     * source: « https://ftp.gnu.org/gnu/bash/bash-3.2.tar.gz »
+#     * run:    « bash --noprofile --norc --posix ./cabal-install/bash-completion/cabal »
+#
 #
 
+##################################################
+# Dependencies:
+
+command -v cabal  >/dev/null
+command -v grep   >/dev/null
+command -v sed    >/dev/null
+
 ##################################################
 
 # List project-specific (/ internal) packages:
@@ -45,7 +81,6 @@ function _cabal_list_packages ()
 
 ##################################################
 
-
 # List cabal targets by type, pass:
 #
 #   - ‹test-suite› for test suites
@@ -98,27 +133,6 @@ function _cabal_list_targets ()
 
 ##################################################
 
-# List known (/ external) packages:
-#
-function _cabal_list_external_packages ()
-{
-
-    cabal list --simple-output
-
-}
-
-# NOTES
-#
-# [1] this is slow.
-#     e.g. « cabal list --simple-output » output ~100,000 lines,
-#          given multiple versions and different « repository »'s
-#          (which took several seconds to print out).
-#
-# [2]
-#
-
-##################################################
-
 # List possible targets depending on the command supplied as parameter.  The
 # ideal option would be to implement this via --list-options on cabal directly.
 # This is a temporary workaround.
@@ -137,7 +151,8 @@ function _cabal_targets ()
         [ "$Completion" == new-bench   ] && _cabal_list_targets "benchmark"  && break
         [ "$Completion" == new-haddock ] && _cabal_list_targets              && break
 
-        [ "$Completion" == new-install ] && _cabal_list_external_packages && break
+        [ "$Completion" == new-install ] && _cabal_list_targets "executable" && break
+        # ^ Only complete for local packages (not all 1000s of remote packages).
 
         [ "$Completion" == build     ] && _cabal_list_targets "executable|test-suite|benchmark" && break
         [ "$Completion" == repl      ] && _cabal_list_targets "executable|test-suite|benchmark" && break
diff --git a/cabal-install/bootstrap.sh b/cabal-install/bootstrap.sh
index 79d50da2bdfee0382968836ad129cb099d528f9b..35930a9c1a139806a7ce0e3e63853d927b548661 100755
--- a/cabal-install/bootstrap.sh
+++ b/cabal-install/bootstrap.sh
@@ -224,7 +224,7 @@ NETWORK_URI_VER="2.6.1.0"; NETWORK_URI_VER_REGEXP="2\.6\.(0\.[2-9]|[1-9])"
                        # >= 2.6.0.2 && < 2.7
 NETWORK_VER="2.7.0.0"; NETWORK_VER_REGEXP="2\.[0-7]\."
                        # >= 2.0 && < 2.7
-CABAL_VER="3.0.0.0";   CABAL_VER_REGEXP="3\.0\.[0-9]"
+CABAL_VER="3.1.0.0";   CABAL_VER_REGEXP="3\.1\.[0-9]"
                        # >= 2.5 && < 2.6
 TRANS_VER="0.5.5.0";   TRANS_VER_REGEXP="0\.[45]\."
                        # >= 0.2.* && < 0.6
@@ -521,7 +521,7 @@ install_pkg "cabal-install"
 # legit cabal sandbox. This works because 'cabal sandbox init' will
 # reuse the already existing package database and other files if they
 # are in the expected locations.
-[ ! -z "$SANDBOX" ] && $SANDBOX/bin/cabal sandbox init --sandbox $SANDBOX
+[ ! -z "$SANDBOX" ] && $SANDBOX/bin/cabal v1-sandbox init --sandbox $SANDBOX
 
 echo
 echo "==========================================="
diff --git a/cabal-install/cabal-install.cabal b/cabal-install/cabal-install.cabal
index 5606dc67b7e19b5223ca706ab2e07ce75e00e645..d50e9348996bad231593b97570a7494e5b1c1d3e 100644
--- a/cabal-install/cabal-install.cabal
+++ b/cabal-install/cabal-install.cabal
@@ -4,7 +4,7 @@ Cabal-Version:      >= 1.10
 -- To update this file, edit 'cabal-install.cabal.pp' and run
 -- 'make cabal-install-prod' in the project's root folder.
 Name:               cabal-install
-Version:            3.0.0.0
+Version:            3.1.0.0
 Synopsis:           The command-line interface for Cabal and Hackage.
 Description:
     The \'cabal\' command-line program simplifies the process of managing
@@ -312,7 +312,7 @@ executable cabal
         base16-bytestring >= 0.1.1 && < 0.2,
         binary     >= 0.7.3    && < 0.9,
         bytestring >= 0.10.6.0 && < 0.11,
-        Cabal      == 3.0.*,
+        Cabal      == 3.1.*,
         containers >= 0.5.6.2  && < 0.7,
         cryptohash-sha256 >= 0.11 && < 0.12,
         deepseq    >= 1.4.1.1  && < 1.5,
@@ -320,11 +320,11 @@ executable cabal
         echo       >= 0.1.3    && < 0.2,
         edit-distance >= 0.2.2 && < 0.3,
         filepath   >= 1.4.0.0  && < 1.5,
-        hashable   >= 1.0      && < 1.3,
+        hashable   >= 1.0      && < 1.4,
         HTTP       >= 4000.1.5 && < 4000.4,
         mtl        >= 2.0      && < 2.3,
         network-uri >= 2.6.0.2 && < 2.7,
-        network    >= 2.6      && < 3.1,
+        network    >= 2.6      && < 3.2,
         pretty     >= 1.1      && < 1.2,
         process    >= 1.2.3.0  && < 1.7,
         random     >= 1        && < 1.2,
@@ -338,6 +338,7 @@ executable cabal
 
     if !impl(ghc >= 8.0)
         build-depends: fail        == 4.9.*
+        build-depends: semigroups  >= 0.18.3 && <0.20
 
     if flag(native-dns)
       if os(windows)
diff --git a/cabal-install/cabal-install.cabal.pp b/cabal-install/cabal-install.cabal.pp
index fd72746fc7d02aac5fb411923d2f4798729ee9fb..0f4d208b02d3caa87084abc667a6f47cf309a2d5 100644
--- a/cabal-install/cabal-install.cabal.pp
+++ b/cabal-install/cabal-install.cabal.pp
@@ -10,7 +10,7 @@ Cabal-Version:      >= 1.10
 -- To update this file, edit 'cabal-install.cabal.pp' and run
 -- 'make cabal-install-prod' in the project's root folder.
 Name:               cabal-install
-Version:            3.0.0.0
+Version:            3.1.0.0
 #
 # NOTE: when updating build-depends, don't forget to update version regexps in bootstrap.sh.
 #
@@ -22,7 +22,7 @@ Version:            3.0.0.0
         base16-bytestring >= 0.1.1 && < 0.2,
         binary     >= 0.7.3    && < 0.9,
         bytestring >= 0.10.6.0 && < 0.11,
-        Cabal      == 3.0.*,
+        Cabal      == 3.1.*,
         containers >= 0.5.6.2  && < 0.7,
         cryptohash-sha256 >= 0.11 && < 0.12,
         deepseq    >= 1.4.1.1  && < 1.5,
@@ -30,11 +30,11 @@ Version:            3.0.0.0
         echo       >= 0.1.3    && < 0.2,
         edit-distance >= 0.2.2 && < 0.3,
         filepath   >= 1.4.0.0  && < 1.5,
-        hashable   >= 1.0      && < 1.3,
+        hashable   >= 1.0      && < 1.4,
         HTTP       >= 4000.1.5 && < 4000.4,
         mtl        >= 2.0      && < 2.3,
         network-uri >= 2.6.0.2 && < 2.7,
-        network    >= 2.6      && < 3.1,
+        network    >= 2.6      && < 3.2,
         pretty     >= 1.1      && < 1.2,
         process    >= 1.2.3.0  && < 1.7,
         random     >= 1        && < 1.2,
@@ -48,6 +48,7 @@ Version:            3.0.0.0
 
     if !impl(ghc >= 8.0)
         build-depends: fail        == 4.9.*
+        build-depends: semigroups  >= 0.18.3 && <0.20
 
     if flag(native-dns)
       if os(windows)
@@ -447,6 +448,7 @@ executable cabal
         UnitTests.Distribution.Client.ArbitraryInstances
         UnitTests.Distribution.Client.FileMonitor
         UnitTests.Distribution.Client.Get
+        UnitTests.Distribution.Client.GenericInstances
         UnitTests.Distribution.Client.GZipUtils
         UnitTests.Distribution.Client.Glob
         UnitTests.Distribution.Client.IndexUtils.Timestamp
@@ -458,6 +460,7 @@ executable cabal
         UnitTests.Distribution.Client.Store
         UnitTests.Distribution.Client.Tar
         UnitTests.Distribution.Client.Targets
+        UnitTests.Distribution.Client.TreeDiffInstances
         UnitTests.Distribution.Client.UserConfig
         UnitTests.Distribution.Client.VCS
         UnitTests.Distribution.Solver.Modular.Builder
@@ -473,7 +476,7 @@ executable cabal
 
     cpp-options: -DMONOLITHIC
     build-depends:
-        Cabal      == 3.0.*,
+        Cabal      == 3.1.*,
         cabal-install-solver-dsl,
         QuickCheck >= 2.8.2,
         array,
@@ -495,6 +498,7 @@ executable cabal
         tasty >= 1.1.0.3 && < 1.2,
         tasty-hunit >= 0.10,
         tasty-quickcheck,
+        tree-diff,
         time,
         zlib
 %endif
@@ -517,12 +521,14 @@ Test-Suite unit-tests
     UnitTests.Distribution.Client.Targets
     UnitTests.Distribution.Client.FileMonitor
     UnitTests.Distribution.Client.Get
+    UnitTests.Distribution.Client.GenericInstances
     UnitTests.Distribution.Client.Glob
     UnitTests.Distribution.Client.GZipUtils
     UnitTests.Distribution.Client.Sandbox
     UnitTests.Distribution.Client.Sandbox.Timestamp
     UnitTests.Distribution.Client.Store
     UnitTests.Distribution.Client.Tar
+    UnitTests.Distribution.Client.TreeDiffInstances
     UnitTests.Distribution.Client.UserConfig
     UnitTests.Distribution.Client.ProjectConfig
     UnitTests.Distribution.Client.JobControl
@@ -553,12 +559,13 @@ Test-Suite unit-tests
         tar,
         time,
         zlib,
-        network-uri,
+        network-uri < 2.6.2.0,
         network,
         tasty >= 1.1.0.3 && < 1.2,
         tasty-hunit >= 0.10,
         tasty-quickcheck,
         tagged,
+        tree-diff,
         QuickCheck >= 2.8.2
 
   ghc-options: -threaded
diff --git a/cabal-install/changelog b/cabal-install/changelog
index a2c4670e05fb18c4f9f4ad862a996b618c367a14..8a939cec1779f3fb501455123cf67eec780c0952 100644
--- a/cabal-install/changelog
+++ b/cabal-install/changelog
@@ -1,6 +1,18 @@
 -*-change-log-*-
 
-3.0.0.0 (current development version)
+3.1.0.0 (current development version)
+
+	* `v2-haddock` fails on `haddock` failures (#5977)
+	* `v2-run` works when given `File.lhs` literate file. (#6134)
+
+3.0.0.0 TBD
+        * Parses comma-seperated lists for extra-prog-path, extra-lib-dirs, extra-framework-dirs, 
+	  and extra-include-dirs as actual lists. (#5420)
+	* `v2-repl` no longer changes directory to a randomized temporary folder
+	  when used outside of a project. (#5544)
+	* `install-method` and `overwrite-policy` in `.cabal/config` now actually work. (#5942)
+	* `v2-install` now reports the error when a package fails to build. (#5641)
+	* `v2-install` now has a default when called in a project (#5978, #6014, #6092)
 	* '--write-ghc-environment-files' now defaults to 'never' (#4242)
 	* Fix `sdist`'s output when sent to stdout. (#5874)
 	* Allow a list of dependencies to be provided for `repl --build-depends`. (#5845)
@@ -28,6 +40,9 @@
 	* --symlink-bindir no longer controls the symlinking directory of
 	  v2-install (installdir controls both symlinking and copying now)
 	* Default to non-interactive init.
+	* Add --test-wrapper that allows a prebuild script to set the test environment.
+	* Add filterTestFlags: filter test-wrapper for Cabal < 3.0.0.
+	* Cabal now only builds the minimum of a package for `v2-install` (#5754, #6091)
 
 2.4.1.0 Mikhail Glushenkov <mikhail.glushenkov@gmail.com> November 2018
 	* Add message to alert user to potential package casing errors. (#5635)
diff --git a/cabal-install/main/Main.hs b/cabal-install/main/Main.hs
index 3b634472aee58377d0f005d8ae24d9725bcc2a88..9c0cb8e30845e433775d3f8c40042485ea612e9c 100644
--- a/cabal-install/main/Main.hs
+++ b/cabal-install/main/Main.hs
@@ -183,6 +183,7 @@ import Distribution.Version
          ( Version, mkVersion, orLaterVersion )
 import qualified Paths_cabal_install (version)
 
+import Distribution.Compat.ResponseFile
 import System.Environment       (getArgs, getProgName)
 import System.Exit              (exitFailure, exitSuccess)
 import System.FilePath          ( dropExtension, splitExtension
@@ -230,7 +231,8 @@ main' = do
   -- when writing to stderr and stdout.
   relaxEncodingErrors stdout
   relaxEncodingErrors stderr
-  getArgs >>= mainWorker
+  (args0, args1) <- break (== "--") <$> getArgs
+  mainWorker =<< (++ args1) <$> expandResponse args0
 
 mainWorker :: [String] -> IO ()
 mainWorker args = do
@@ -1046,7 +1048,7 @@ formatAction verbosityFlag extraArgs _globalFlags = do
   let verbosity = fromFlag verbosityFlag
   path <- case extraArgs of
     [] -> do cwd <- getCurrentDirectory
-             tryFindPackageDesc cwd
+             tryFindPackageDesc verbosity cwd
     (p:_) -> return p
   pkgDesc <- readGenericPackageDescription verbosity path
   -- Uses 'writeFileAtomic' under the hood.
diff --git a/cabal-install/tests/UnitTests/Distribution/Client/ArbitraryInstances.hs b/cabal-install/tests/UnitTests/Distribution/Client/ArbitraryInstances.hs
index b82f0f5ad821b05c07830b0698982140d89a03de..6379b1a639b8e7339d78c71059528b14ba566c59 100644
--- a/cabal-install/tests/UnitTests/Distribution/Client/ArbitraryInstances.hs
+++ b/cabal-install/tests/UnitTests/Distribution/Client/ArbitraryInstances.hs
@@ -21,6 +21,7 @@ import Control.Applicative
 import Control.Monad
 
 import Distribution.Version
+import Distribution.Types.VersionRange.Internal
 import Distribution.Types.Dependency
 import Distribution.Types.PackageVersionConstraint
 import Distribution.Types.UnqualComponentName
@@ -123,7 +124,10 @@ instance Arbitrary PackageName where
         packageChars  = filter isAlphaNum ['\0'..'\127']
 
 instance Arbitrary Dependency where
-    arbitrary = Dependency <$> arbitrary <*> arbitrary <*> fmap getNonMEmpty arbitrary
+    arbitrary = Dependency
+                <$> arbitrary
+                <*> arbitrary
+                <*> fmap getNonMEmpty arbitrary
 
 instance Arbitrary PackageVersionConstraint where
     arbitrary = PackageVersionConstraint <$> arbitrary <*> arbitrary
@@ -133,7 +137,10 @@ instance Arbitrary UnqualComponentName where
     arbitrary = packageNameToUnqualComponentName <$> arbitrary
 
 instance Arbitrary LibraryName where
-    arbitrary = elements =<< sequenceA [LSubLibName <$> arbitrary, pure LMainLibName]
+    arbitrary =
+      elements
+      =<< sequenceA [ LSubLibName <$> arbitrary
+                    , pure LMainLibName ]
 
 instance Arbitrary OS where
     arbitrary = elements knownOSs
@@ -168,7 +175,9 @@ instance Arbitrary Verbosity where
 
 instance Arbitrary PathTemplate where
     arbitrary = toPathTemplate <$> arbitraryShortToken
-    shrink t  = [ toPathTemplate s | s <- shrink (fromPathTemplate t), not (null s) ]
+    shrink t  = [ toPathTemplate s
+                | s <- shrink (fromPathTemplate t)
+                , not (null s) ]
 
 
 newtype NonMEmpty a = NonMEmpty { getNonMEmpty :: a }
diff --git a/cabal-install/tests/UnitTests/Distribution/Client/GenericInstances.hs b/cabal-install/tests/UnitTests/Distribution/Client/GenericInstances.hs
new file mode 100644
index 0000000000000000000000000000000000000000..78569ab01a0dd7730ea8fe26363fbd13b57385ca
--- /dev/null
+++ b/cabal-install/tests/UnitTests/Distribution/Client/GenericInstances.hs
@@ -0,0 +1,10 @@
+{-# LANGUAGE DeriveGeneric        #-}
+{-# LANGUAGE StandaloneDeriving   #-}
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+
+module UnitTests.Distribution.Client.GenericInstances () where
+
+import Network.URI
+import GHC.Generics
+
+deriving instance Generic URIAuth
diff --git a/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs b/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs
index e9e8304a293f4888565823a3687dd5259f7e9ace..f8c4969d2e7b2dca23781e6cdf4c500db9f97b0f 100644
--- a/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs
+++ b/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs
@@ -45,7 +45,10 @@ import Distribution.Client.ProjectConfig
 import Distribution.Client.ProjectConfig.Legacy
 
 import UnitTests.Distribution.Client.ArbitraryInstances
+import UnitTests.Distribution.Client.TreeDiffInstances ()
 
+import Data.TreeDiff.Class
+import Data.TreeDiff.QuickCheck
 import Test.Tasty
 import Test.Tasty.QuickCheck
 
@@ -93,10 +96,10 @@ tests =
 -- Round trip: conversion to/from legacy types
 --
 
-roundtrip :: (Eq a, Show a) => (a -> b) -> (b -> a) -> a -> Property
+roundtrip :: (Eq a, ToExpr a) => (a -> b) -> (b -> a) -> a -> Property
 roundtrip f f_inv x =
     let y = f x
-    in f_inv y === x -- no counterexample with y, as they not have Show
+    in f_inv y `ediffEq` x -- no counterexample with y, as they not have ToExpr
 
 roundtrip_legacytypes :: ProjectConfig -> Property
 roundtrip_legacytypes =
@@ -154,8 +157,8 @@ roundtrip_printparse config =
         . showLegacyProjectConfig
         . convertToLegacyProjectConfig)
           config of
-      ParseOk _ x -> x === config { projectConfigProvenance = mempty }
-      ParseFailed err           -> counterexample (show err) False
+      ParseOk _ x     -> x `ediffEq` config { projectConfigProvenance = mempty }
+      ParseFailed err -> counterexample (show err) False
 
 
 prop_roundtrip_printparse_all :: ProjectConfig -> Property
@@ -260,12 +263,12 @@ prop_roundtrip_printparse_RelaxedDep rdep =
 prop_roundtrip_printparse_RelaxDeps :: RelaxDeps -> Property
 prop_roundtrip_printparse_RelaxDeps rdep =
     counterexample (Text.display rdep) $
-    runReadP Text.parse (Text.display rdep) === Just rdep
+    runReadP Text.parse (Text.display rdep) `ediffEq` Just rdep
 
 prop_roundtrip_printparse_RelaxDeps' :: RelaxDeps -> Property
 prop_roundtrip_printparse_RelaxDeps' rdep =
     counterexample rdep' $
-    runReadP Text.parse rdep' === Just rdep
+    runReadP Text.parse rdep' `ediffEq` Just rdep
   where
     rdep' = go (Text.display rdep)
 
@@ -597,6 +600,7 @@ instance Arbitrary PackageConfig where
         <*> arbitrary
         <*> arbitrary
         <*> arbitrary
+        <*> arbitraryFlag arbitraryShortToken
         <*> arbitrary
         <*> shortListOf 5 arbitrary
       where
@@ -656,8 +660,9 @@ instance Arbitrary PackageConfig where
                          , packageConfigTestMachineLog = x45
                          , packageConfigTestShowDetails = x46
                          , packageConfigTestKeepTix = x47
-                         , packageConfigTestFailWhenNoTestSuites = x48
-                         , packageConfigTestTestOptions = x49 } =
+                         , packageConfigTestWrapper = x48
+                         , packageConfigTestFailWhenNoTestSuites = x49
+                         , packageConfigTestTestOptions = x51 } =
       [ PackageConfig { packageConfigProgramPaths = postShrink_Paths x00'
                       , packageConfigProgramArgs = postShrink_Args x01'
                       , packageConfigProgramPathExtra = x02'
@@ -709,8 +714,9 @@ instance Arbitrary PackageConfig where
                       , packageConfigTestMachineLog = x45'
                       , packageConfigTestShowDetails = x46'
                       , packageConfigTestKeepTix = x47'
-                      , packageConfigTestFailWhenNoTestSuites = x48'
-                      , packageConfigTestTestOptions = x49' }
+                      , packageConfigTestWrapper = x48'
+                      , packageConfigTestFailWhenNoTestSuites = x49'
+                      , packageConfigTestTestOptions = x51' }
       |  (((x00', x01', x02', x03', x04'),
           (x05', x42', x06', x50', x07', x08', x09'),
           (x10', x11', x12', x13', x14'),
@@ -720,7 +726,7 @@ instance Arbitrary PackageConfig where
           (x30', x31', x32', (x33', x33_1'), x34'),
           (x35', x36', x37', x38', x43', x39'),
           (x40', x41'),
-          (x44', x45', x46', x47', x48', x49')))
+          (x44', x45', x46', x47', x48', x49', x51')))
           <- shrink
              (((preShrink_Paths x00, preShrink_Args x01, x02, x03, x04),
                 (x05, x42, x06, x50, x07, x08, x09),
@@ -734,7 +740,7 @@ instance Arbitrary PackageConfig where
                  (x30, x31, x32, (x33, x33_1), x34),
                  (x35, x36, fmap NonEmpty x37, x38, x43, fmap NonEmpty x39),
                  (x40, x41),
-                 (x44, x45, x46, x47, x48, x49)))
+                 (x44, x45, x46, x47, x48, x49, x51)))
       ]
       where
         preShrink_Paths  = Map.map NonEmpty
@@ -757,14 +763,16 @@ instance Arbitrary TestShowDetails where
     arbitrary = arbitraryBoundedEnum
 
 instance Arbitrary SourceRepo where
-    arbitrary = (SourceRepo RepoThis
+    arbitrary = (SourceRepo kind
                            <$> arbitrary
                            <*> (fmap getShortToken <$> arbitrary)
                            <*> (fmap getShortToken <$> arbitrary)
                            <*> (fmap getShortToken <$> arbitrary)
                            <*> (fmap getShortToken <$> arbitrary)
                            <*> (fmap getShortToken <$> arbitrary))
-                `suchThat` (/= emptySourceRepo RepoThis)
+                `suchThat` (/= emptySourceRepo kind)
+      where
+        kind = RepoKindUnknown "unused"
 
     shrink (SourceRepo _ x1 x2 x3 x4 x5 x6) =
       [ repo
diff --git a/cabal-install/tests/UnitTests/Distribution/Client/TreeDiffInstances.hs b/cabal-install/tests/UnitTests/Distribution/Client/TreeDiffInstances.hs
new file mode 100644
index 0000000000000000000000000000000000000000..49c9a925ffec635dbdac43a2b4755df2a944f6c0
--- /dev/null
+++ b/cabal-install/tests/UnitTests/Distribution/Client/TreeDiffInstances.hs
@@ -0,0 +1,106 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+
+module UnitTests.Distribution.Client.TreeDiffInstances () where
+
+import Distribution.Compiler
+import Distribution.Simple.Compiler
+  ( ProfDetailLevel, OptimisationLevel, DebugInfoLevel )
+import Distribution.Simple.Flag
+import Distribution.Simple.InstallDirs
+import Distribution.Simple.InstallDirs.Internal
+import Distribution.Simple.Setup (HaddockTarget, TestShowDetails)
+import Distribution.Types.GenericPackageDescription (FlagName, FlagAssignment)
+import Distribution.Types.PackageId
+import Distribution.Types.PackageName
+import Distribution.Types.PackageVersionConstraint
+import Distribution.Types.SourceRepo
+import Distribution.Types.Version
+import Distribution.Types.VersionRange.Internal
+import Distribution.Utils.NubList
+import Distribution.Utils.ShortText
+import Distribution.Verbosity
+import Distribution.Verbosity.Internal
+
+import Distribution.Solver.Types.ConstraintSource
+import Distribution.Solver.Types.OptionalStanza
+import Distribution.Solver.Types.PackageConstraint
+import Distribution.Solver.Types.Settings
+
+import Distribution.Client.BuildReports.Types
+import Distribution.Client.CmdInstall.ClientInstallFlags
+import Distribution.Client.Dependency.Types
+import Distribution.Client.IndexUtils.Timestamp
+import Distribution.Client.InstallSymlink
+import Distribution.Client.ProjectConfig.Types
+import Distribution.Client.Targets
+import Distribution.Client.Types
+
+import UnitTests.Distribution.Client.GenericInstances ()
+
+import Network.URI
+import Data.TreeDiff.Class
+
+instance (ToExpr k, ToExpr v) => ToExpr (MapMappend k v)
+instance (ToExpr k, ToExpr v) => ToExpr (MapLast k v)
+instance (ToExpr a) => ToExpr (NubList a)
+instance (ToExpr a) => ToExpr (Flag a)
+
+instance ToExpr AllowBootLibInstalls
+instance ToExpr AllowNewer
+instance ToExpr AllowOlder
+instance ToExpr ClientInstallFlags
+instance ToExpr CompilerFlavor
+instance ToExpr ConstraintSource
+instance ToExpr CountConflicts
+instance ToExpr DebugInfoLevel
+instance ToExpr FlagAssignment
+instance ToExpr FlagName where toExpr = defaultExprViaShow
+instance ToExpr HaddockTarget
+instance ToExpr IndependentGoals
+instance ToExpr IndexState
+instance ToExpr InstallMethod
+instance ToExpr MinimizeConflictSet
+instance ToExpr OnlyConstrained
+instance ToExpr OptimisationLevel
+instance ToExpr OptionalStanza
+instance ToExpr OverwritePolicy
+instance ToExpr PackageConfig
+instance ToExpr PackageIdentifier
+instance ToExpr PackageName where toExpr = defaultExprViaShow
+instance ToExpr PackageProperty
+instance ToExpr PackageVersionConstraint
+instance ToExpr PathComponent
+instance ToExpr PathTemplate
+instance ToExpr PathTemplateVariable
+instance ToExpr PreSolver
+instance ToExpr ProfDetailLevel
+instance ToExpr ProjectConfig
+instance ToExpr ProjectConfigBuildOnly
+instance ToExpr ProjectConfigProvenance
+instance ToExpr ProjectConfigShared
+instance ToExpr RelaxDepMod
+instance ToExpr RelaxDepScope
+instance ToExpr RelaxDepSubject
+instance ToExpr RelaxDeps
+instance ToExpr RelaxedDep
+instance ToExpr RemoteRepo
+instance ToExpr ReorderGoals
+instance ToExpr RepoKind
+instance ToExpr RepoType
+instance ToExpr ReportLevel
+instance ToExpr ShortText
+instance ToExpr SourceRepo
+instance ToExpr StrongFlags
+instance ToExpr TestShowDetails
+instance ToExpr Timestamp
+instance ToExpr URI
+instance ToExpr URIAuth
+instance ToExpr UserConstraint
+instance ToExpr UserConstraintScope
+instance ToExpr UserQualifier
+instance ToExpr Verbosity
+instance ToExpr VerbosityFlag
+instance ToExpr VerbosityLevel
+instance ToExpr Version where toExpr = defaultExprViaShow
+instance ToExpr VersionRange
+instance ToExpr WriteGhcEnvironmentFilesPolicy
diff --git a/cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit-fail.out b/cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit-fail.out
index f5ef78b9875077c890ffc5f27571d3d0821dfb6a..b84252dcd0080a411bb37e42179a4a12a2cb3bfa 100644
--- a/cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit-fail.out
+++ b/cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit-fail.out
@@ -9,5 +9,5 @@ Installing internal library sublib in <PATH>
 Registering library 'sublib' for Lib-0.1.0.0..
 # Setup configure
 Configuring executable 'exe' for Lib-0.1.0.0..
-setup: Encountered missing dependencies:
+setup: Encountered missing or private dependencies:
     sublib -any
diff --git a/cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit.test.hs b/cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit.test.hs
index 2afa4025caf12d56a8c06e7c55feb576663bf038..5e34ae953e80a0c7b67ce95ffda45b5ab7ac83a1 100644
--- a/cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit.test.hs
+++ b/cabal-testsuite/PackageTests/ConfigureComponent/SubLib/setup-explicit.test.hs
@@ -5,6 +5,6 @@ main = setupTest $ do
         base_id <- getIPID "base"
         setup_install ["sublib", "--cid", "sublib-0.1-abc"]
         setup_install [ "exe", "--exact-configuration"
-                      , "--dependency", "sublib=sublib-0.1-abc"
+                      , "--dependency", "sublib:sublib=sublib-0.1-abc"
                       , "--dependency", "base=" ++ base_id ]
         runExe' "exe" [] >>= assertOutputContains "OK"
diff --git a/cabal-testsuite/PackageTests/MultipleLibraries/cabal.out b/cabal-testsuite/PackageTests/MultipleLibraries/cabal.out
new file mode 100644
index 0000000000000000000000000000000000000000..7e51c00ef041efef4289af30248ad301673f3ada
--- /dev/null
+++ b/cabal-testsuite/PackageTests/MultipleLibraries/cabal.out
@@ -0,0 +1,12 @@
+# cabal v2-build
+Resolving dependencies...
+Build profile: -w ghc-<GHCVER> -O1
+In order, the following will be built:
+ - d-0.1.0.0 (lib:privatelib) (first run)
+ - p-0.1.0.0 (lib) (first run)
+Configuring library 'privatelib' for d-0.1.0.0..
+Preprocessing library 'privatelib' for d-0.1.0.0..
+Building library 'privatelib' for d-0.1.0.0..
+Configuring library for p-0.1.0.0..
+cabal: Encountered missing or private dependencies:
+    d : {privatelib} ==0.1.0.0
diff --git a/cabal-testsuite/PackageTests/MultipleLibraries/cabal.project b/cabal-testsuite/PackageTests/MultipleLibraries/cabal.project
new file mode 100644
index 0000000000000000000000000000000000000000..0cdfff2f0540b042ef5f95954f8444ac782874f2
--- /dev/null
+++ b/cabal-testsuite/PackageTests/MultipleLibraries/cabal.project
@@ -0,0 +1,4 @@
+packages:
+  d
+  p
+
diff --git a/cabal-testsuite/PackageTests/MultipleLibraries/cabal.test.hs b/cabal-testsuite/PackageTests/MultipleLibraries/cabal.test.hs
new file mode 100644
index 0000000000000000000000000000000000000000..44f25b88d8acdf672557e4adca51cfb98f4e6f9f
--- /dev/null
+++ b/cabal-testsuite/PackageTests/MultipleLibraries/cabal.test.hs
@@ -0,0 +1,4 @@
+import Test.Cabal.Prelude
+main = cabalTest $
+    void $ fails (cabal' "v2-build" ["p"])
+
diff --git a/cabal-testsuite/PackageTests/MultipleLibraries/d/d.cabal b/cabal-testsuite/PackageTests/MultipleLibraries/d/d.cabal
new file mode 100644
index 0000000000000000000000000000000000000000..8410ab97c32eae69a63eafd5e0dee888229ebd35
--- /dev/null
+++ b/cabal-testsuite/PackageTests/MultipleLibraries/d/d.cabal
@@ -0,0 +1,12 @@
+cabal-version: 3.0
+name: d
+version: 0.1.0.0
+
+-- See issue #6038
+library
+  default-language: Haskell2010
+
+library privatelib
+  visibility: private
+  default-language: Haskell2010
+
diff --git a/cabal-testsuite/PackageTests/MultipleLibraries/p/p.cabal b/cabal-testsuite/PackageTests/MultipleLibraries/p/p.cabal
new file mode 100644
index 0000000000000000000000000000000000000000..b7bbe480bfd5d38878865f241cb20fc0bf4cf186
--- /dev/null
+++ b/cabal-testsuite/PackageTests/MultipleLibraries/p/p.cabal
@@ -0,0 +1,8 @@
+cabal-version: 3.0
+name: p
+version: 0.1.0.0
+
+library
+  build-depends: d:privatelib
+  default-language: Haskell2010
+
diff --git a/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/cabal.out b/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/cabal.out
new file mode 100644
index 0000000000000000000000000000000000000000..31d7de3ca732c25d1b9181bcb6cacb09116db808
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/cabal.out
@@ -0,0 +1,8 @@
+# cabal v2-run
+Resolving dependencies...
+Build profile: -w ghc-<GHCVER> -O1
+In order, the following will be built:
+ - fake-package-0 (exe:script) (first run)
+Configuring executable 'script' for fake-package-0..
+Preprocessing executable 'script' for fake-package-0..
+Building executable 'script' for fake-package-0..
diff --git a/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/cabal.test.hs b/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/cabal.test.hs
index ed08629c1a7017f3a23075a5826b22b3d1666378..ee9110853e8d2d007f91d1fa9497249c06559875 100644
--- a/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/cabal.test.hs
+++ b/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/cabal.test.hs
@@ -1,5 +1,5 @@
 import Test.Cabal.Prelude
 
 main = cabalTest $ do
-    expectBroken 5775 $ cabal' "v2-run" ["script.hs"]
-    return ()
+    res <- cabal' "v2-run" ["script.hs"]
+    assertOutputContains "Hello World" res
diff --git a/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/script.hs b/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/script.hs
index 4217ec46e8581babdd4eb4fc822b9d947a9f1a2f..ac92e735b8780713e10ba8e3526350a431375ab9 100644
--- a/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/script.hs
+++ b/cabal-testsuite/PackageTests/NewBuild/CmdRun/Script/script.hs
@@ -1,6 +1,6 @@
 #! /usr/bin/env cabal
 {- cabal:
-build-depends: base ^>= 4.0
+build-depends: base >= 4.3 && <5
 -}
 {-# LANGUAGE BangPatterns #-}
 {-# LANGUAGE ScopedTypeVariables #-}
@@ -8,4 +8,4 @@ build-depends: base ^>= 4.0
 import Prelude
 
 main :: IO ()
-main = return ()
+main = putStrLn "Hello World"
diff --git a/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.out b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.out
new file mode 100644
index 0000000000000000000000000000000000000000..31d7de3ca732c25d1b9181bcb6cacb09116db808
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.out
@@ -0,0 +1,8 @@
+# cabal v2-run
+Resolving dependencies...
+Build profile: -w ghc-<GHCVER> -O1
+In order, the following will be built:
+ - fake-package-0 (exe:script) (first run)
+Configuring executable 'script' for fake-package-0..
+Preprocessing executable 'script' for fake-package-0..
+Building executable 'script' for fake-package-0..
diff --git a/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.project b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.project
new file mode 100644
index 0000000000000000000000000000000000000000..5356e76f67c76ea1cf221ce38a73edef1002225e
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.project
@@ -0,0 +1 @@
+packages: .
\ No newline at end of file
diff --git a/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.test.hs b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.test.hs
new file mode 100644
index 0000000000000000000000000000000000000000..64c858e8d0da597c7884dbfadc658e9ce172a3a3
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/cabal.test.hs
@@ -0,0 +1,5 @@
+import Test.Cabal.Prelude
+
+main = cabalTest $ do
+    res <- cabal' "v2-run" ["script.lhs"]
+    assertOutputContains "Hello World" res
diff --git a/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/script.cabal b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/script.cabal
new file mode 100644
index 0000000000000000000000000000000000000000..56b2e9feb604141879dacfe9061ee423bed1ba3c
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/script.cabal
@@ -0,0 +1,4 @@
+name: script
+version: 1.0
+build-type: Simple
+cabal-version: >= 1.10
diff --git a/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/script.lhs b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/script.lhs
new file mode 100644
index 0000000000000000000000000000000000000000..f0365393f526b38e9638821327e22ae9b1e1fdb2
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewBuild/CmdRun/ScriptLiterate/script.lhs
@@ -0,0 +1,18 @@
+\iffalse
+{- cabal:
+build-depends: base >= 4.3 && <5
+-}
+\fi
+\documentclass{article}
+\begin{document}
+\begin{code}
+
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+import Prelude
+
+main :: IO ()
+main = putStrLn "Hello World"
+\end{code}
+\end{document}
diff --git a/cabal-testsuite/PackageTests/NewHaddock/Fails/Example.hs b/cabal-testsuite/PackageTests/NewHaddock/Fails/Example.hs
new file mode 100644
index 0000000000000000000000000000000000000000..76287b43f72e789d9784c034f5e2ab0063798e52
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewHaddock/Fails/Example.hs
@@ -0,0 +1,6 @@
+module Example where
+
+import Prelude
+
+example :: Int
+example = False
diff --git a/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.out b/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.out
new file mode 100644
index 0000000000000000000000000000000000000000..cbfc470cbba6e6e4426f13be65f3595dd3273634
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.out
@@ -0,0 +1,15 @@
+# cabal v2-build
+Resolving dependencies...
+Build profile: -w ghc-<GHCVER> -O1
+In order, the following will be built:
+ - example-1.0 (lib) (first run)
+Configuring library for example-1.0..
+Preprocessing library for example-1.0..
+Building library for example-1.0..
+# cabal v2-haddock
+Build profile: -w ghc-<GHCVER> -O1
+In order, the following will be built:
+ - example-1.0 (lib) (first run)
+Preprocessing library for example-1.0..
+Running Haddock on library for example-1.0..
+cabal: Failed to build documentation for example-1.0-inplace.
diff --git a/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.project b/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.project
new file mode 100644
index 0000000000000000000000000000000000000000..5356e76f67c76ea1cf221ce38a73edef1002225e
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.project
@@ -0,0 +1 @@
+packages: .
\ No newline at end of file
diff --git a/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.test.hs b/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.test.hs
new file mode 100644
index 0000000000000000000000000000000000000000..e872b3164598fa2933161fce9127dd4e91c66b31
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewHaddock/Fails/cabal.test.hs
@@ -0,0 +1,6 @@
+import Test.Cabal.Prelude
+import System.Exit (ExitCode (..))
+
+main = cabalTest $ do
+    fails $ cabal "v2-build" ["example"]
+    fails $ cabal "v2-haddock" ["example"]
diff --git a/cabal-testsuite/PackageTests/NewHaddock/Fails/example.cabal b/cabal-testsuite/PackageTests/NewHaddock/Fails/example.cabal
new file mode 100644
index 0000000000000000000000000000000000000000..5096de78b5daf2c99c523261a71ee7a10ac0fa50
--- /dev/null
+++ b/cabal-testsuite/PackageTests/NewHaddock/Fails/example.cabal
@@ -0,0 +1,9 @@
+name:          example
+version:       1.0
+build-type:    Simple
+cabal-version: >=1.10
+
+library
+  default-language: Haskell2010
+  build-depends:    base
+  exposed-modules:  Example
diff --git a/cabal-testsuite/PackageTests/Regression/T6125/Main.hs b/cabal-testsuite/PackageTests/Regression/T6125/Main.hs
new file mode 100644
index 0000000000000000000000000000000000000000..b3549c2fe3d794dddfdf687ed1163ff5302f20e8
--- /dev/null
+++ b/cabal-testsuite/PackageTests/Regression/T6125/Main.hs
@@ -0,0 +1 @@
+main = return ()
diff --git a/cabal-testsuite/PackageTests/Regression/T6125/data/foo/bar.html b/cabal-testsuite/PackageTests/Regression/T6125/data/foo/bar.html
new file mode 100644
index 0000000000000000000000000000000000000000..99fd1d469d9c8b81291de9cea58da18631c07157
--- /dev/null
+++ b/cabal-testsuite/PackageTests/Regression/T6125/data/foo/bar.html
@@ -0,0 +1 @@
+<!DOCTYPE html>Some random data.
diff --git a/cabal-testsuite/PackageTests/Regression/T6125/myprog.cabal b/cabal-testsuite/PackageTests/Regression/T6125/myprog.cabal
new file mode 100644
index 0000000000000000000000000000000000000000..935cdb8b8c3ba9bd1afd2cfd5300dd316db9e516
--- /dev/null
+++ b/cabal-testsuite/PackageTests/Regression/T6125/myprog.cabal
@@ -0,0 +1,9 @@
+cabal-version: 2.4
+name: myprog
+version: 0
+data-files: data/**/*.html
+
+executable myprog
+  build-depends: base
+  main-is: Main.hs
+  default-language: Haskell2010
diff --git a/cabal-testsuite/PackageTests/Regression/T6125/setup.cabal.out b/cabal-testsuite/PackageTests/Regression/T6125/setup.cabal.out
new file mode 100644
index 0000000000000000000000000000000000000000..64e8312ccddeb35814d6a79d6a93a137afab9e3a
--- /dev/null
+++ b/cabal-testsuite/PackageTests/Regression/T6125/setup.cabal.out
@@ -0,0 +1,9 @@
+# Setup configure
+Resolving dependencies...
+Configuring myprog-0...
+# Setup build
+Preprocessing executable 'myprog' for myprog-0..
+Building executable 'myprog' for myprog-0..
+# Setup copy
+Installing executable myprog in <PATH>
+Warning: The directory <ROOT>/setup.cabal.dist/usr/bin is not in the system search path.
diff --git a/cabal-testsuite/PackageTests/Regression/T6125/setup.out b/cabal-testsuite/PackageTests/Regression/T6125/setup.out
new file mode 100644
index 0000000000000000000000000000000000000000..b982a76eccdf43a05b484559e397b866437067ed
--- /dev/null
+++ b/cabal-testsuite/PackageTests/Regression/T6125/setup.out
@@ -0,0 +1,8 @@
+# Setup configure
+Configuring myprog-0...
+# Setup build
+Preprocessing executable 'myprog' for myprog-0..
+Building executable 'myprog' for myprog-0..
+# Setup copy
+Installing executable myprog in <PATH>
+Warning: The directory <ROOT>/setup.dist/usr/bin is not in the system search path.
diff --git a/cabal-testsuite/PackageTests/Regression/T6125/setup.test.hs b/cabal-testsuite/PackageTests/Regression/T6125/setup.test.hs
new file mode 100644
index 0000000000000000000000000000000000000000..aeb2587e70c28cec947c3c0381dda5eed4389ab8
--- /dev/null
+++ b/cabal-testsuite/PackageTests/Regression/T6125/setup.test.hs
@@ -0,0 +1,6 @@
+import Test.Cabal.Prelude
+main = setupAndCabalTest $ do
+    withPackageDb $ do
+        setup "configure" []
+        setup "build" ["myprog"]
+        setup "copy" ["myprog"]
diff --git a/cabal-testsuite/PackageTests/UserConfig/cabal.out b/cabal-testsuite/PackageTests/UserConfig/cabal.out
index 7887050e85c2812c798e53e7bb8baa414e1eb2da..8dc64f170e1c4946cdbe43790a952f15c24a3186 100644
--- a/cabal-testsuite/PackageTests/UserConfig/cabal.out
+++ b/cabal-testsuite/PackageTests/UserConfig/cabal.out
@@ -6,3 +6,9 @@ cabal: <ROOT>/cabal.dist/cabal-config already exists.
 Writing default configuration to <ROOT>/cabal.dist/cabal-config
 # cabal user-config
 Writing default configuration to <ROOT>/cabal.dist/cabal-config2
+# cabal user-config
+Renaming <ROOT>/cabal.dist/cabal-config to <ROOT>/cabal.dist/cabal-config.backup.
+Writing merged config to <ROOT>/cabal.dist/cabal-config.
+# cabal user-config
+Renaming <ROOT>/cabal.dist/cabal-config to <ROOT>/cabal.dist/cabal-config.backup.
+Writing merged config to <ROOT>/cabal.dist/cabal-config.
diff --git a/cabal-testsuite/PackageTests/UserConfig/cabal.test.hs b/cabal-testsuite/PackageTests/UserConfig/cabal.test.hs
index 32ad84982e1a35575b0dace40f4ce4df1dc1cee9..85d67212d4ced80f618208784cdaaab3df23dc1f 100644
--- a/cabal-testsuite/PackageTests/UserConfig/cabal.test.hs
+++ b/cabal-testsuite/PackageTests/UserConfig/cabal.test.hs
@@ -11,3 +11,7 @@ main = cabalTest $ do
     withEnv [("CABAL_CONFIG", Just conf2)] $ do
         cabal "user-config" ["init"]
         shouldExist conf2
+    cabalG ["--config-file", conf] "user-config" ["update", "-f", "-a", "extra-prog-path: foo", "-a", "extra-prog-path: bar"]
+    assertFileDoesContain conf "foo,bar"
+    cabalG ["--config-file", conf] "user-config" ["update", "-f", "-a", "extra-prog-path: foo, bar"]
+    assertFileDoesContain conf "foo,bar"
diff --git a/cabal-testsuite/Test/Cabal/Prelude.hs b/cabal-testsuite/Test/Cabal/Prelude.hs
index 135f8d3830907f43f203bd6c20f6dd8d15c60d71..f5fe61919223b6385c9395a8294d0a72d7bb3257 100644
--- a/cabal-testsuite/Test/Cabal/Prelude.hs
+++ b/cabal-testsuite/Test/Cabal/Prelude.hs
@@ -161,11 +161,11 @@ setup'' prefix cmd args = do
     defaultRecordMode RecordMarked $ do
     recordHeader ["Setup", cmd]
     if testCabalInstallAsSetup env
-        then 
+        then
             -- `cabal` and `Setup` no longer have the same interface.
             -- A bit of fettling is required to hide this fact.
-            let 
-                legacyCmds = 
+            let
+                legacyCmds =
                     [ "build"
                     , "configure"
                     , "repl"
@@ -188,7 +188,8 @@ setup'' prefix cmd args = do
                 full_args' = if a `elem` legacyCmds then ("v1-" ++ a) : as else a:as
             in runProgramM cabalProgram full_args'
         else do
-            pdfile <- liftIO $ tryFindPackageDesc (testCurrentDir env </> prefix)
+            pdfile <- liftIO $ tryFindPackageDesc (testVerbosity env)
+                      (testCurrentDir env </> prefix)
             pdesc <- liftIO $ readGenericPackageDescription (testVerbosity env) pdfile
             if buildType (packageDescription pdesc) == Simple
                 then runM (testSetupPath env) full_args
diff --git a/cabal-testsuite/cabal-testsuite.cabal b/cabal-testsuite/cabal-testsuite.cabal
index 166abd2f3da2d8353131e5c335a2eb0a66c79162..ad76c95d9de5cbc6aa984108bb0cff68309b4993 100644
--- a/cabal-testsuite/cabal-testsuite.cabal
+++ b/cabal-testsuite/cabal-testsuite.cabal
@@ -1,6 +1,6 @@
 cabal-version: 2.2
 name:          cabal-testsuite
-version:       3.0.0.0
+version:       3.1.0.0
 copyright:     2003-2019, Cabal Development Team (see AUTHORS file)
 license:       BSD-3-Clause
 license-file:  LICENSE
@@ -28,7 +28,7 @@ common shared
   build-depends:
     , base >= 4.6 && <4.13
     -- this needs to match the in-tree lib:Cabal version
-    , Cabal == 3.0.0.0
+    , Cabal == 3.1.0.0
 
   ghc-options: -Wall -fwarn-tabs
 
@@ -102,5 +102,5 @@ executable setup
 
 custom-setup
   -- we only depend on even stable releases of lib:Cabal
-  setup-depends: Cabal == 2.2.* || == 2.4.* || == 3.0.*,
+  setup-depends: Cabal == 2.2.* || == 2.4.* || == 3.0.* || ==3.1.*,
                  base, filepath, directory
diff --git a/license-list-data/exceptions-3.5.json b/license-list-data/exceptions-3.6.json
similarity index 93%
rename from license-list-data/exceptions-3.5.json
rename to license-list-data/exceptions-3.6.json
index 906beba9d168bf81ba0ccbdf21f296432f30138e..0f77cd372e91178c79dd4322bb65d6f28da78f87 100644
--- a/license-list-data/exceptions-3.5.json
+++ b/license-list-data/exceptions-3.6.json
@@ -1,6 +1,6 @@
 {
-  "licenseListVersion": "3.5-1-g1266c6b",
-  "releaseDate": "2019-04-02",
+  "licenseListVersion": "3.6",
+  "releaseDate": "2019-07-10",
   "exceptions": [
     {
       "reference": "./Libtool-exception.html",
@@ -75,7 +75,7 @@
       "referenceNumber": "7",
       "name": "OpenJDK Assembly exception 1.0",
       "seeAlso": [
-        "http://openjdk.java.net/legal/assembly-exception.html\n         "
+        "http://openjdk.java.net/legal/assembly-exception.html"
       ],
       "licenseExceptionId": "OpenJDK-assembly-exception-1.0"
     },
@@ -101,11 +101,22 @@
       ],
       "licenseExceptionId": "i2p-gpl-java-exception"
     },
+    {
+      "reference": "./Universal-FOSS-exception-1.0.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/Universal-FOSS-exception-1.0.json",
+      "referenceNumber": "10",
+      "name": "Universal FOSS Exception, Version 1.0",
+      "seeAlso": [
+        "https://oss.oracle.com/licenses/universal-foss-exception/"
+      ],
+      "licenseExceptionId": "Universal-FOSS-exception-1.0"
+    },
     {
       "reference": "./Qt-LGPL-exception-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Qt-LGPL-exception-1.1.json",
-      "referenceNumber": "10",
+      "referenceNumber": "11",
       "name": "Qt LGPL exception 1.1",
       "seeAlso": [
         "http://code.qt.io/cgit/qt/qtbase.git/tree/LGPL_EXCEPTION.txt"
@@ -116,7 +127,7 @@
       "reference": "./389-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/389-exception.json",
-      "referenceNumber": "11",
+      "referenceNumber": "12",
       "name": "389 Directory Server Exception",
       "seeAlso": [
         "http://directory.fedoraproject.org/wiki/GPL_Exception_License_Text"
@@ -127,7 +138,7 @@
       "reference": "./Classpath-exception-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Classpath-exception-2.0.json",
-      "referenceNumber": "12",
+      "referenceNumber": "13",
       "name": "Classpath exception 2.0",
       "seeAlso": [
         "http://www.gnu.org/software/classpath/license.html",
@@ -139,7 +150,7 @@
       "reference": "./Fawkes-Runtime-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Fawkes-Runtime-exception.json",
-      "referenceNumber": "13",
+      "referenceNumber": "14",
       "name": "Fawkes Runtime Exception",
       "seeAlso": [
         "http://www.fawkesrobotics.org/about/license/"
@@ -150,7 +161,7 @@
       "reference": "./PS-or-PDF-font-exception-20170817.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/PS-or-PDF-font-exception-20170817.json",
-      "referenceNumber": "14",
+      "referenceNumber": "15",
       "name": "PS/PDF font exception (2017-08-17)",
       "seeAlso": [
         "https://github.com/ArtifexSoftware/urw-base35-fonts/blob/65962e27febc3883a17e651cdb23e783668c996f/LICENSE"
@@ -161,7 +172,7 @@
       "reference": "./Qt-GPL-exception-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Qt-GPL-exception-1.0.json",
-      "referenceNumber": "15",
+      "referenceNumber": "16",
       "name": "Qt GPL exception 1.0",
       "seeAlso": [
         "http://code.qt.io/cgit/qt/qtbase.git/tree/LICENSE.GPL3-EXCEPT"
@@ -172,7 +183,7 @@
       "reference": "./LZMA-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LZMA-exception.json",
-      "referenceNumber": "16",
+      "referenceNumber": "17",
       "name": "LZMA exception",
       "seeAlso": [
         "http://nsis.sourceforge.net/Docs/AppendixI.html#I.6"
@@ -183,7 +194,7 @@
       "reference": "./freertos-exception-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/freertos-exception-2.0.json",
-      "referenceNumber": "17",
+      "referenceNumber": "18",
       "name": "FreeRTOS Exception 2.0",
       "seeAlso": [
         "https://web.archive.org/web/20060809182744/http://www.freertos.org/a00114.html"
@@ -194,7 +205,7 @@
       "reference": "./Qwt-exception-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Qwt-exception-1.0.json",
-      "referenceNumber": "18",
+      "referenceNumber": "19",
       "name": "Qwt exception 1.0",
       "seeAlso": [
         "http://qwt.sourceforge.net/qwtlicense.html"
@@ -205,7 +216,7 @@
       "reference": "./CLISP-exception-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CLISP-exception-2.0.json",
-      "referenceNumber": "19",
+      "referenceNumber": "20",
       "name": "CLISP exception 2.0",
       "seeAlso": [
         "http://sourceforge.net/p/clisp/clisp/ci/default/tree/COPYRIGHT"
@@ -216,7 +227,7 @@
       "reference": "./FLTK-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/FLTK-exception.json",
-      "referenceNumber": "20",
+      "referenceNumber": "21",
       "name": "FLTK exception",
       "seeAlso": [
         "http://www.fltk.org/COPYING.php"
@@ -227,7 +238,7 @@
       "reference": "./Bootloader-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Bootloader-exception.json",
-      "referenceNumber": "21",
+      "referenceNumber": "22",
       "name": "Bootloader Distribution Exception",
       "seeAlso": [
         "https://github.com/pyinstaller/pyinstaller/blob/develop/COPYING.txt"
@@ -238,7 +249,7 @@
       "reference": "./Nokia-Qt-exception-1.1.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/Nokia-Qt-exception-1.1.json",
-      "referenceNumber": "22",
+      "referenceNumber": "23",
       "name": "Nokia Qt LGPL exception 1.1",
       "seeAlso": [
         "https://www.keepassx.org/dev/projects/keepassx/repository/revisions/b8dfb9cc4d5133e0f09cd7533d15a4f1c19a40f2/entry/LICENSE.NOKIA-LGPL-EXCEPTION"
@@ -249,7 +260,7 @@
       "reference": "./LLVM-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LLVM-exception.json",
-      "referenceNumber": "23",
+      "referenceNumber": "24",
       "name": "LLVM Exception",
       "seeAlso": [
         "http://llvm.org/foundation/relicensing/LICENSE.txt"
@@ -260,7 +271,7 @@
       "reference": "./WxWindows-exception-3.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/WxWindows-exception-3.1.json",
-      "referenceNumber": "24",
+      "referenceNumber": "25",
       "name": "WxWindows Library Exception 3.1",
       "seeAlso": [
         "http://www.opensource.org/licenses/WXwindows"
@@ -271,18 +282,30 @@
       "reference": "./DigiRule-FOSS-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/DigiRule-FOSS-exception.json",
-      "referenceNumber": "25",
+      "referenceNumber": "26",
       "name": "DigiRule FOSS License Exception",
       "seeAlso": [
         "http://www.digirulesolutions.com/drupal/foss"
       ],
       "licenseExceptionId": "DigiRule-FOSS-exception"
     },
+    {
+      "reference": "./Swift-exception.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/Swift-exception.json",
+      "referenceNumber": "27",
+      "name": "Swift Exception",
+      "seeAlso": [
+        "https://swift.org/LICENSE.txt",
+        "https://github.com/apple/swift-package-manager/blob/7ab2275f447a5eb37497ed63a9340f8a6d1e488b/LICENSE.txt#L205"
+      ],
+      "licenseExceptionId": "Swift-exception"
+    },
     {
       "reference": "./GCC-exception-3.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/GCC-exception-3.1.json",
-      "referenceNumber": "26",
+      "referenceNumber": "28",
       "name": "GCC Runtime Library exception 3.1",
       "seeAlso": [
         "http://www.gnu.org/licenses/gcc-exception-3.1.html"
@@ -293,7 +316,7 @@
       "reference": "./eCos-exception-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/eCos-exception-2.0.json",
-      "referenceNumber": "27",
+      "referenceNumber": "29",
       "name": "eCos exception 2.0",
       "seeAlso": [
         "http://ecos.sourceware.org/license-overview.html"
@@ -304,7 +327,7 @@
       "reference": "./Autoconf-exception-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Autoconf-exception-2.0.json",
-      "referenceNumber": "28",
+      "referenceNumber": "30",
       "name": "Autoconf exception 2.0",
       "seeAlso": [
         "http://ac-archive.sourceforge.net/doc/copyright.html",
@@ -316,7 +339,7 @@
       "reference": "./GPL-CC-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/GPL-CC-1.0.json",
-      "referenceNumber": "29",
+      "referenceNumber": "31",
       "name": "GPL Cooperation Commitment 1.0",
       "seeAlso": [
         "https://github.com/gplcc/gplcc/blob/master/Project/COMMITMENT",
@@ -328,7 +351,7 @@
       "reference": "./Font-exception-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Font-exception-2.0.json",
-      "referenceNumber": "30",
+      "referenceNumber": "32",
       "name": "Font exception 2.0",
       "seeAlso": [
         "http://www.gnu.org/licenses/gpl-faq.html#FontException"
@@ -339,7 +362,7 @@
       "reference": "./u-boot-exception-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/u-boot-exception-2.0.json",
-      "referenceNumber": "31",
+      "referenceNumber": "33",
       "name": "U-Boot exception 2.0",
       "seeAlso": [
         "http://git.denx.de/?p\u003du-boot.git;a\u003dblob;f\u003dLicenses/Exceptions"
@@ -350,7 +373,7 @@
       "reference": "./GCC-exception-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/GCC-exception-2.0.json",
-      "referenceNumber": "32",
+      "referenceNumber": "34",
       "name": "GCC Runtime Library exception 2.0",
       "seeAlso": [
         "https://gcc.gnu.org/git/?p\u003dgcc.git;a\u003dblob;f\u003dgcc/libgcc1.c;h\u003d762f5143fc6eed57b6797c82710f3538aa52b40b;hb\u003dcb143a3ce4fb417c68f5fa2691a1b1b1053dfba9#l10"
@@ -361,7 +384,7 @@
       "reference": "./mif-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/mif-exception.json",
-      "referenceNumber": "33",
+      "referenceNumber": "35",
       "name": "Macros and Inline Functions Exception",
       "seeAlso": [
         "http://www.scs.stanford.edu/histar/src/lib/cppsup/exception",
@@ -374,7 +397,7 @@
       "reference": "./OCaml-LGPL-linking-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OCaml-LGPL-linking-exception.json",
-      "referenceNumber": "34",
+      "referenceNumber": "36",
       "name": "OCaml LGPL Linking Exception",
       "seeAlso": [
         "https://caml.inria.fr/ocaml/license.en.html"
diff --git a/license-list-data/licenses-3.5.json b/license-list-data/licenses-3.6.json
similarity index 97%
rename from license-list-data/licenses-3.5.json
rename to license-list-data/licenses-3.6.json
index 72a64e9b51a79ba282b7fa3dd604e1c5bdc182db..10550cbd44e1d6975db3eb2584b01dca000189c7 100644
--- a/license-list-data/licenses-3.5.json
+++ b/license-list-data/licenses-3.6.json
@@ -1,11 +1,11 @@
 {
-  "licenseListVersion": "3.5-1-g1266c6b",
+  "licenseListVersion": "3.6",
   "licenses": [
     {
       "reference": "./0BSD.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/0BSD.json",
-      "referenceNumber": "315",
+      "referenceNumber": "319",
       "name": "BSD Zero Clause License",
       "licenseId": "0BSD",
       "seeAlso": [
@@ -42,7 +42,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AFL-1.1.json",
-      "referenceNumber": "115",
+      "referenceNumber": "118",
       "name": "Academic Free License v1.1",
       "licenseId": "AFL-1.1",
       "seeAlso": [
@@ -56,7 +56,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AFL-1.2.json",
-      "referenceNumber": "133",
+      "referenceNumber": "136",
       "name": "Academic Free License v1.2",
       "licenseId": "AFL-1.2",
       "seeAlso": [
@@ -70,7 +70,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AFL-2.0.json",
-      "referenceNumber": "112",
+      "referenceNumber": "115",
       "name": "Academic Free License v2.0",
       "licenseId": "AFL-2.0",
       "seeAlso": [
@@ -83,7 +83,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AFL-2.1.json",
-      "referenceNumber": "248",
+      "referenceNumber": "251",
       "name": "Academic Free License v2.1",
       "licenseId": "AFL-2.1",
       "seeAlso": [
@@ -96,7 +96,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AFL-3.0.json",
-      "referenceNumber": "213",
+      "referenceNumber": "216",
       "name": "Academic Free License v3.0",
       "licenseId": "AFL-3.0",
       "seeAlso": [
@@ -110,7 +110,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AGPL-1.0.json",
-      "referenceNumber": "330",
+      "referenceNumber": "335",
       "name": "Affero General Public License v1.0",
       "licenseId": "AGPL-1.0",
       "seeAlso": [
@@ -122,7 +122,7 @@
       "reference": "./AGPL-1.0-only.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/AGPL-1.0-only.json",
-      "referenceNumber": "376",
+      "referenceNumber": "384",
       "name": "Affero General Public License v1.0 only",
       "licenseId": "AGPL-1.0-only",
       "seeAlso": [
@@ -134,7 +134,7 @@
       "reference": "./AGPL-1.0-or-later.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/AGPL-1.0-or-later.json",
-      "referenceNumber": "327",
+      "referenceNumber": "332",
       "name": "Affero General Public License v1.0 or later",
       "licenseId": "AGPL-1.0-or-later",
       "seeAlso": [
@@ -147,7 +147,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AGPL-3.0.json",
-      "referenceNumber": "226",
+      "referenceNumber": "229",
       "name": "GNU Affero General Public License v3.0",
       "licenseId": "AGPL-3.0",
       "seeAlso": [
@@ -161,7 +161,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AGPL-3.0-only.json",
-      "referenceNumber": "92",
+      "referenceNumber": "95",
       "name": "GNU Affero General Public License v3.0 only",
       "licenseId": "AGPL-3.0-only",
       "seeAlso": [
@@ -175,7 +175,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/AGPL-3.0-or-later.json",
-      "referenceNumber": "152",
+      "referenceNumber": "155",
       "name": "GNU Affero General Public License v3.0 or later",
       "licenseId": "AGPL-3.0-or-later",
       "seeAlso": [
@@ -188,7 +188,7 @@
       "reference": "./AMDPLPA.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/AMDPLPA.json",
-      "referenceNumber": "32",
+      "referenceNumber": "33",
       "name": "AMD\u0027s plpa_map.c License",
       "licenseId": "AMDPLPA",
       "seeAlso": [
@@ -200,7 +200,7 @@
       "reference": "./AML.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/AML.json",
-      "referenceNumber": "145",
+      "referenceNumber": "148",
       "name": "Apple MIT License",
       "licenseId": "AML",
       "seeAlso": [
@@ -212,7 +212,7 @@
       "reference": "./AMPAS.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/AMPAS.json",
-      "referenceNumber": "188",
+      "referenceNumber": "191",
       "name": "Academy of Motion Picture Arts and Sciences BSD",
       "licenseId": "AMPAS",
       "seeAlso": [
@@ -224,7 +224,7 @@
       "reference": "./ANTLR-PD.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/ANTLR-PD.json",
-      "referenceNumber": "387",
+      "referenceNumber": "395",
       "name": "ANTLR Software Rights Notice",
       "licenseId": "ANTLR-PD",
       "seeAlso": [
@@ -236,7 +236,7 @@
       "reference": "./APAFML.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/APAFML.json",
-      "referenceNumber": "192",
+      "referenceNumber": "195",
       "name": "Adobe Postscript AFM License",
       "licenseId": "APAFML",
       "seeAlso": [
@@ -248,7 +248,7 @@
       "reference": "./APL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/APL-1.0.json",
-      "referenceNumber": "249",
+      "referenceNumber": "252",
       "name": "Adaptive Public License 1.0",
       "licenseId": "APL-1.0",
       "seeAlso": [
@@ -260,7 +260,7 @@
       "reference": "./APSL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/APSL-1.0.json",
-      "referenceNumber": "348",
+      "referenceNumber": "354",
       "name": "Apple Public Source License 1.0",
       "licenseId": "APSL-1.0",
       "seeAlso": [
@@ -272,7 +272,7 @@
       "reference": "./APSL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/APSL-1.1.json",
-      "referenceNumber": "320",
+      "referenceNumber": "324",
       "name": "Apple Public Source License 1.1",
       "licenseId": "APSL-1.1",
       "seeAlso": [
@@ -284,7 +284,7 @@
       "reference": "./APSL-1.2.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/APSL-1.2.json",
-      "referenceNumber": "33",
+      "referenceNumber": "34",
       "name": "Apple Public Source License 1.2",
       "licenseId": "APSL-1.2",
       "seeAlso": [
@@ -297,7 +297,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/APSL-2.0.json",
-      "referenceNumber": "106",
+      "referenceNumber": "109",
       "name": "Apple Public Source License 2.0",
       "licenseId": "APSL-2.0",
       "seeAlso": [
@@ -309,7 +309,7 @@
       "reference": "./Abstyles.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Abstyles.json",
-      "referenceNumber": "78",
+      "referenceNumber": "80",
       "name": "Abstyles License",
       "licenseId": "Abstyles",
       "seeAlso": [
@@ -321,7 +321,7 @@
       "reference": "./Adobe-2006.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Adobe-2006.json",
-      "referenceNumber": "282",
+      "referenceNumber": "285",
       "name": "Adobe Systems Incorporated Source Code License Agreement",
       "licenseId": "Adobe-2006",
       "seeAlso": [
@@ -333,7 +333,7 @@
       "reference": "./Adobe-Glyph.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Adobe-Glyph.json",
-      "referenceNumber": "104",
+      "referenceNumber": "107",
       "name": "Adobe Glyph List License",
       "licenseId": "Adobe-Glyph",
       "seeAlso": [
@@ -345,7 +345,7 @@
       "reference": "./Afmparse.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Afmparse.json",
-      "referenceNumber": "41",
+      "referenceNumber": "42",
       "name": "Afmparse License",
       "licenseId": "Afmparse",
       "seeAlso": [
@@ -357,7 +357,7 @@
       "reference": "./Aladdin.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Aladdin.json",
-      "referenceNumber": "255",
+      "referenceNumber": "258",
       "name": "Aladdin Free Public License",
       "licenseId": "Aladdin",
       "seeAlso": [
@@ -370,7 +370,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Apache-1.0.json",
-      "referenceNumber": "234",
+      "referenceNumber": "237",
       "name": "Apache License 1.0",
       "licenseId": "Apache-1.0",
       "seeAlso": [
@@ -383,7 +383,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Apache-1.1.json",
-      "referenceNumber": "82",
+      "referenceNumber": "84",
       "name": "Apache License 1.1",
       "licenseId": "Apache-1.1",
       "seeAlso": [
@@ -397,7 +397,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Apache-2.0.json",
-      "referenceNumber": "25",
+      "referenceNumber": "26",
       "name": "Apache License 2.0",
       "licenseId": "Apache-2.0",
       "seeAlso": [
@@ -410,7 +410,7 @@
       "reference": "./Artistic-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Artistic-1.0.json",
-      "referenceNumber": "162",
+      "referenceNumber": "165",
       "name": "Artistic License 1.0",
       "licenseId": "Artistic-1.0",
       "seeAlso": [
@@ -422,7 +422,7 @@
       "reference": "./Artistic-1.0-Perl.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Artistic-1.0-Perl.json",
-      "referenceNumber": "369",
+      "referenceNumber": "377",
       "name": "Artistic License 1.0 (Perl)",
       "licenseId": "Artistic-1.0-Perl",
       "seeAlso": [
@@ -447,7 +447,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Artistic-2.0.json",
-      "referenceNumber": "186",
+      "referenceNumber": "189",
       "name": "Artistic License 2.0",
       "licenseId": "Artistic-2.0",
       "seeAlso": [
@@ -460,7 +460,7 @@
       "reference": "./BSD-1-Clause.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-1-Clause.json",
-      "referenceNumber": "351",
+      "referenceNumber": "358",
       "name": "BSD 1-Clause License",
       "licenseId": "BSD-1-Clause",
       "seeAlso": [
@@ -472,7 +472,7 @@
       "reference": "./BSD-2-Clause.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-2-Clause.json",
-      "referenceNumber": "321",
+      "referenceNumber": "325",
       "name": "BSD 2-Clause \"Simplified\" License",
       "licenseId": "BSD-2-Clause",
       "seeAlso": [
@@ -485,7 +485,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/BSD-2-Clause-FreeBSD.json",
-      "referenceNumber": "118",
+      "referenceNumber": "121",
       "name": "BSD 2-Clause FreeBSD License",
       "licenseId": "BSD-2-Clause-FreeBSD",
       "seeAlso": [
@@ -497,7 +497,7 @@
       "reference": "./BSD-2-Clause-NetBSD.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-2-Clause-NetBSD.json",
-      "referenceNumber": "373",
+      "referenceNumber": "381",
       "name": "BSD 2-Clause NetBSD License",
       "licenseId": "BSD-2-Clause-NetBSD",
       "seeAlso": [
@@ -509,7 +509,7 @@
       "reference": "./BSD-2-Clause-Patent.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-2-Clause-Patent.json",
-      "referenceNumber": "166",
+      "referenceNumber": "169",
       "name": "BSD-2-Clause Plus Patent License",
       "licenseId": "BSD-2-Clause-Patent",
       "seeAlso": [
@@ -522,7 +522,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/BSD-3-Clause.json",
-      "referenceNumber": "267",
+      "referenceNumber": "270",
       "name": "BSD 3-Clause \"New\" or \"Revised\" License",
       "licenseId": "BSD-3-Clause",
       "seeAlso": [
@@ -534,7 +534,7 @@
       "reference": "./BSD-3-Clause-Attribution.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-3-Clause-Attribution.json",
-      "referenceNumber": "38",
+      "referenceNumber": "39",
       "name": "BSD with attribution",
       "licenseId": "BSD-3-Clause-Attribution",
       "seeAlso": [
@@ -547,7 +547,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/BSD-3-Clause-Clear.json",
-      "referenceNumber": "209",
+      "referenceNumber": "212",
       "name": "BSD 3-Clause Clear License",
       "licenseId": "BSD-3-Clause-Clear",
       "seeAlso": [
@@ -559,13 +559,13 @@
       "reference": "./BSD-3-Clause-LBNL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-3-Clause-LBNL.json",
-      "referenceNumber": "332",
+      "referenceNumber": "337",
       "name": "Lawrence Berkeley National Labs BSD variant license",
       "licenseId": "BSD-3-Clause-LBNL",
       "seeAlso": [
         "https://fedoraproject.org/wiki/Licensing/LBNLBSD"
       ],
-      "isOsiApproved": false
+      "isOsiApproved": true
     },
     {
       "reference": "./BSD-3-Clause-No-Nuclear-License.html",
@@ -583,7 +583,7 @@
       "reference": "./BSD-3-Clause-No-Nuclear-License-2014.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-3-Clause-No-Nuclear-License-2014.json",
-      "referenceNumber": "134",
+      "referenceNumber": "137",
       "name": "BSD 3-Clause No Nuclear License 2014",
       "licenseId": "BSD-3-Clause-No-Nuclear-License-2014",
       "seeAlso": [
@@ -595,7 +595,7 @@
       "reference": "./BSD-3-Clause-No-Nuclear-Warranty.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-3-Clause-No-Nuclear-Warranty.json",
-      "referenceNumber": "43",
+      "referenceNumber": "44",
       "name": "BSD 3-Clause No Nuclear Warranty",
       "licenseId": "BSD-3-Clause-No-Nuclear-Warranty",
       "seeAlso": [
@@ -603,12 +603,25 @@
       ],
       "isOsiApproved": false
     },
+    {
+      "reference": "./BSD-3-Clause-Open-MPI.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/BSD-3-Clause-Open-MPI.json",
+      "referenceNumber": "349",
+      "name": "BSD 3-Clause Open MPI variant",
+      "licenseId": "BSD-3-Clause-Open-MPI",
+      "seeAlso": [
+        "https://www.open-mpi.org/community/license.php",
+        "http://www.netlib.org/lapack/LICENSE.txt"
+      ],
+      "isOsiApproved": false
+    },
     {
       "reference": "./BSD-4-Clause.html",
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/BSD-4-Clause.json",
-      "referenceNumber": "159",
+      "referenceNumber": "162",
       "name": "BSD 4-Clause \"Original\" or \"Old\" License",
       "licenseId": "BSD-4-Clause",
       "seeAlso": [
@@ -620,7 +633,7 @@
       "reference": "./BSD-4-Clause-UC.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-4-Clause-UC.json",
-      "referenceNumber": "200",
+      "referenceNumber": "203",
       "name": "BSD-4-Clause (University of California-Specific)",
       "licenseId": "BSD-4-Clause-UC",
       "seeAlso": [
@@ -632,7 +645,7 @@
       "reference": "./BSD-Protection.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-Protection.json",
-      "referenceNumber": "116",
+      "referenceNumber": "119",
       "name": "BSD Protection License",
       "licenseId": "BSD-Protection",
       "seeAlso": [
@@ -644,7 +657,7 @@
       "reference": "./BSD-Source-Code.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BSD-Source-Code.json",
-      "referenceNumber": "305",
+      "referenceNumber": "308",
       "name": "BSD Source Code Attribution",
       "licenseId": "BSD-Source-Code",
       "seeAlso": [
@@ -657,7 +670,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/BSL-1.0.json",
-      "referenceNumber": "221",
+      "referenceNumber": "224",
       "name": "Boost Software License 1.0",
       "licenseId": "BSL-1.0",
       "seeAlso": [
@@ -670,7 +683,7 @@
       "reference": "./Bahyph.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Bahyph.json",
-      "referenceNumber": "359",
+      "referenceNumber": "366",
       "name": "Bahyph License",
       "licenseId": "Bahyph",
       "seeAlso": [
@@ -682,7 +695,7 @@
       "reference": "./Barr.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Barr.json",
-      "referenceNumber": "328",
+      "referenceNumber": "333",
       "name": "Barr License",
       "licenseId": "Barr",
       "seeAlso": [
@@ -707,7 +720,7 @@
       "reference": "./BitTorrent-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/BitTorrent-1.0.json",
-      "referenceNumber": "215",
+      "referenceNumber": "218",
       "name": "BitTorrent Open Source License v1.0",
       "licenseId": "BitTorrent-1.0",
       "seeAlso": [
@@ -720,7 +733,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/BitTorrent-1.1.json",
-      "referenceNumber": "176",
+      "referenceNumber": "179",
       "name": "BitTorrent Open Source License v1.1",
       "licenseId": "BitTorrent-1.1",
       "seeAlso": [
@@ -728,11 +741,23 @@
       ],
       "isOsiApproved": false
     },
+    {
+      "reference": "./BlueOak-1.0.0.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/BlueOak-1.0.0.json",
+      "referenceNumber": "23",
+      "name": "Blue Oak Model License 1.0.0",
+      "licenseId": "BlueOak-1.0.0",
+      "seeAlso": [
+        "https://blueoakcouncil.org/license/1.0.0"
+      ],
+      "isOsiApproved": false
+    },
     {
       "reference": "./Borceux.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Borceux.json",
-      "referenceNumber": "308",
+      "referenceNumber": "311",
       "name": "Borceux license",
       "licenseId": "Borceux",
       "seeAlso": [
@@ -744,7 +769,7 @@
       "reference": "./CATOSL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CATOSL-1.1.json",
-      "referenceNumber": "259",
+      "referenceNumber": "262",
       "name": "Computer Associates Trusted Open Source License 1.1",
       "licenseId": "CATOSL-1.1",
       "seeAlso": [
@@ -756,7 +781,7 @@
       "reference": "./CC-BY-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-1.0.json",
-      "referenceNumber": "125",
+      "referenceNumber": "128",
       "name": "Creative Commons Attribution 1.0 Generic",
       "licenseId": "CC-BY-1.0",
       "seeAlso": [
@@ -768,7 +793,7 @@
       "reference": "./CC-BY-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-2.0.json",
-      "referenceNumber": "229",
+      "referenceNumber": "232",
       "name": "Creative Commons Attribution 2.0 Generic",
       "licenseId": "CC-BY-2.0",
       "seeAlso": [
@@ -780,7 +805,7 @@
       "reference": "./CC-BY-2.5.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-2.5.json",
-      "referenceNumber": "126",
+      "referenceNumber": "129",
       "name": "Creative Commons Attribution 2.5 Generic",
       "licenseId": "CC-BY-2.5",
       "seeAlso": [
@@ -792,7 +817,7 @@
       "reference": "./CC-BY-3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-3.0.json",
-      "referenceNumber": "253",
+      "referenceNumber": "256",
       "name": "Creative Commons Attribution 3.0 Unported",
       "licenseId": "CC-BY-3.0",
       "seeAlso": [
@@ -805,7 +830,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-4.0.json",
-      "referenceNumber": "326",
+      "referenceNumber": "330",
       "name": "Creative Commons Attribution 4.0 International",
       "licenseId": "CC-BY-4.0",
       "seeAlso": [
@@ -817,7 +842,7 @@
       "reference": "./CC-BY-NC-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-1.0.json",
-      "referenceNumber": "127",
+      "referenceNumber": "130",
       "name": "Creative Commons Attribution Non Commercial 1.0 Generic",
       "licenseId": "CC-BY-NC-1.0",
       "seeAlso": [
@@ -829,7 +854,7 @@
       "reference": "./CC-BY-NC-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-2.0.json",
-      "referenceNumber": "241",
+      "referenceNumber": "244",
       "name": "Creative Commons Attribution Non Commercial 2.0 Generic",
       "licenseId": "CC-BY-NC-2.0",
       "seeAlso": [
@@ -853,7 +878,7 @@
       "reference": "./CC-BY-NC-3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-3.0.json",
-      "referenceNumber": "252",
+      "referenceNumber": "255",
       "name": "Creative Commons Attribution Non Commercial 3.0 Unported",
       "licenseId": "CC-BY-NC-3.0",
       "seeAlso": [
@@ -865,7 +890,7 @@
       "reference": "./CC-BY-NC-4.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-4.0.json",
-      "referenceNumber": "183",
+      "referenceNumber": "186",
       "name": "Creative Commons Attribution Non Commercial 4.0 International",
       "licenseId": "CC-BY-NC-4.0",
       "seeAlso": [
@@ -877,7 +902,7 @@
       "reference": "./CC-BY-NC-ND-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-ND-1.0.json",
-      "referenceNumber": "58",
+      "referenceNumber": "59",
       "name": "Creative Commons Attribution Non Commercial No Derivatives 1.0 Generic",
       "licenseId": "CC-BY-NC-ND-1.0",
       "seeAlso": [
@@ -889,7 +914,7 @@
       "reference": "./CC-BY-NC-ND-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-ND-2.0.json",
-      "referenceNumber": "35",
+      "referenceNumber": "36",
       "name": "Creative Commons Attribution Non Commercial No Derivatives 2.0 Generic",
       "licenseId": "CC-BY-NC-ND-2.0",
       "seeAlso": [
@@ -901,7 +926,7 @@
       "reference": "./CC-BY-NC-ND-2.5.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-ND-2.5.json",
-      "referenceNumber": "155",
+      "referenceNumber": "158",
       "name": "Creative Commons Attribution Non Commercial No Derivatives 2.5 Generic",
       "licenseId": "CC-BY-NC-ND-2.5",
       "seeAlso": [
@@ -913,7 +938,7 @@
       "reference": "./CC-BY-NC-ND-3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-ND-3.0.json",
-      "referenceNumber": "47",
+      "referenceNumber": "48",
       "name": "Creative Commons Attribution Non Commercial No Derivatives 3.0 Unported",
       "licenseId": "CC-BY-NC-ND-3.0",
       "seeAlso": [
@@ -925,7 +950,7 @@
       "reference": "./CC-BY-NC-ND-4.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-ND-4.0.json",
-      "referenceNumber": "278",
+      "referenceNumber": "281",
       "name": "Creative Commons Attribution Non Commercial No Derivatives 4.0 International",
       "licenseId": "CC-BY-NC-ND-4.0",
       "seeAlso": [
@@ -937,7 +962,7 @@
       "reference": "./CC-BY-NC-SA-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-SA-1.0.json",
-      "referenceNumber": "175",
+      "referenceNumber": "178",
       "name": "Creative Commons Attribution Non Commercial Share Alike 1.0 Generic",
       "licenseId": "CC-BY-NC-SA-1.0",
       "seeAlso": [
@@ -949,7 +974,7 @@
       "reference": "./CC-BY-NC-SA-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-SA-2.0.json",
-      "referenceNumber": "79",
+      "referenceNumber": "81",
       "name": "Creative Commons Attribution Non Commercial Share Alike 2.0 Generic",
       "licenseId": "CC-BY-NC-SA-2.0",
       "seeAlso": [
@@ -961,7 +986,7 @@
       "reference": "./CC-BY-NC-SA-2.5.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-SA-2.5.json",
-      "referenceNumber": "61",
+      "referenceNumber": "62",
       "name": "Creative Commons Attribution Non Commercial Share Alike 2.5 Generic",
       "licenseId": "CC-BY-NC-SA-2.5",
       "seeAlso": [
@@ -985,7 +1010,7 @@
       "reference": "./CC-BY-NC-SA-4.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-NC-SA-4.0.json",
-      "referenceNumber": "46",
+      "referenceNumber": "47",
       "name": "Creative Commons Attribution Non Commercial Share Alike 4.0 International",
       "licenseId": "CC-BY-NC-SA-4.0",
       "seeAlso": [
@@ -997,7 +1022,7 @@
       "reference": "./CC-BY-ND-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-ND-1.0.json",
-      "referenceNumber": "49",
+      "referenceNumber": "50",
       "name": "Creative Commons Attribution No Derivatives 1.0 Generic",
       "licenseId": "CC-BY-ND-1.0",
       "seeAlso": [
@@ -1009,7 +1034,7 @@
       "reference": "./CC-BY-ND-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-ND-2.0.json",
-      "referenceNumber": "284",
+      "referenceNumber": "287",
       "name": "Creative Commons Attribution No Derivatives 2.0 Generic",
       "licenseId": "CC-BY-ND-2.0",
       "seeAlso": [
@@ -1021,7 +1046,7 @@
       "reference": "./CC-BY-ND-2.5.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-ND-2.5.json",
-      "referenceNumber": "67",
+      "referenceNumber": "68",
       "name": "Creative Commons Attribution No Derivatives 2.5 Generic",
       "licenseId": "CC-BY-ND-2.5",
       "seeAlso": [
@@ -1033,7 +1058,7 @@
       "reference": "./CC-BY-ND-3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-ND-3.0.json",
-      "referenceNumber": "385",
+      "referenceNumber": "393",
       "name": "Creative Commons Attribution No Derivatives 3.0 Unported",
       "licenseId": "CC-BY-ND-3.0",
       "seeAlso": [
@@ -1045,7 +1070,7 @@
       "reference": "./CC-BY-ND-4.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-ND-4.0.json",
-      "referenceNumber": "129",
+      "referenceNumber": "132",
       "name": "Creative Commons Attribution No Derivatives 4.0 International",
       "licenseId": "CC-BY-ND-4.0",
       "seeAlso": [
@@ -1057,7 +1082,7 @@
       "reference": "./CC-BY-SA-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-SA-1.0.json",
-      "referenceNumber": "318",
+      "referenceNumber": "322",
       "name": "Creative Commons Attribution Share Alike 1.0 Generic",
       "licenseId": "CC-BY-SA-1.0",
       "seeAlso": [
@@ -1069,7 +1094,7 @@
       "reference": "./CC-BY-SA-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-SA-2.0.json",
-      "referenceNumber": "139",
+      "referenceNumber": "142",
       "name": "Creative Commons Attribution Share Alike 2.0 Generic",
       "licenseId": "CC-BY-SA-2.0",
       "seeAlso": [
@@ -1081,7 +1106,7 @@
       "reference": "./CC-BY-SA-2.5.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-SA-2.5.json",
-      "referenceNumber": "303",
+      "referenceNumber": "306",
       "name": "Creative Commons Attribution Share Alike 2.5 Generic",
       "licenseId": "CC-BY-SA-2.5",
       "seeAlso": [
@@ -1093,7 +1118,7 @@
       "reference": "./CC-BY-SA-3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-SA-3.0.json",
-      "referenceNumber": "386",
+      "referenceNumber": "394",
       "name": "Creative Commons Attribution Share Alike 3.0 Unported",
       "licenseId": "CC-BY-SA-3.0",
       "seeAlso": [
@@ -1106,7 +1131,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CC-BY-SA-4.0.json",
-      "referenceNumber": "31",
+      "referenceNumber": "32",
       "name": "Creative Commons Attribution Share Alike 4.0 International",
       "licenseId": "CC-BY-SA-4.0",
       "seeAlso": [
@@ -1114,12 +1139,24 @@
       ],
       "isOsiApproved": false
     },
+    {
+      "reference": "./CC-PDDC.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/CC-PDDC.json",
+      "referenceNumber": "371",
+      "name": "Creative Commons Public Domain Dedication and Certification",
+      "licenseId": "CC-PDDC",
+      "seeAlso": [
+        "https://creativecommons.org/licenses/publicdomain/"
+      ],
+      "isOsiApproved": false
+    },
     {
       "reference": "./CC0-1.0.html",
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CC0-1.0.json",
-      "referenceNumber": "210",
+      "referenceNumber": "213",
       "name": "Creative Commons Zero v1.0 Universal",
       "licenseId": "CC0-1.0",
       "seeAlso": [
@@ -1132,7 +1169,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CDDL-1.0.json",
-      "referenceNumber": "135",
+      "referenceNumber": "138",
       "name": "Common Development and Distribution License 1.0",
       "licenseId": "CDDL-1.0",
       "seeAlso": [
@@ -1144,7 +1181,7 @@
       "reference": "./CDDL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CDDL-1.1.json",
-      "referenceNumber": "368",
+      "referenceNumber": "376",
       "name": "Common Development and Distribution License 1.1",
       "licenseId": "CDDL-1.1",
       "seeAlso": [
@@ -1157,7 +1194,7 @@
       "reference": "./CDLA-Permissive-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CDLA-Permissive-1.0.json",
-      "referenceNumber": "247",
+      "referenceNumber": "250",
       "name": "Community Data License Agreement Permissive 1.0",
       "licenseId": "CDLA-Permissive-1.0",
       "seeAlso": [
@@ -1169,7 +1206,7 @@
       "reference": "./CDLA-Sharing-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CDLA-Sharing-1.0.json",
-      "referenceNumber": "307",
+      "referenceNumber": "310",
       "name": "Community Data License Agreement Sharing 1.0",
       "licenseId": "CDLA-Sharing-1.0",
       "seeAlso": [
@@ -1181,7 +1218,7 @@
       "reference": "./CECILL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CECILL-1.0.json",
-      "referenceNumber": "220",
+      "referenceNumber": "223",
       "name": "CeCILL Free Software License Agreement v1.0",
       "licenseId": "CECILL-1.0",
       "seeAlso": [
@@ -1193,7 +1230,7 @@
       "reference": "./CECILL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CECILL-1.1.json",
-      "referenceNumber": "297",
+      "referenceNumber": "300",
       "name": "CeCILL Free Software License Agreement v1.1",
       "licenseId": "CECILL-1.1",
       "seeAlso": [
@@ -1206,7 +1243,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CECILL-2.0.json",
-      "referenceNumber": "346",
+      "referenceNumber": "352",
       "name": "CeCILL Free Software License Agreement v2.0",
       "licenseId": "CECILL-2.0",
       "seeAlso": [
@@ -1218,7 +1255,7 @@
       "reference": "./CECILL-2.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CECILL-2.1.json",
-      "referenceNumber": "117",
+      "referenceNumber": "120",
       "name": "CeCILL Free Software License Agreement v2.1",
       "licenseId": "CECILL-2.1",
       "seeAlso": [
@@ -1231,7 +1268,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CECILL-B.json",
-      "referenceNumber": "335",
+      "referenceNumber": "340",
       "name": "CeCILL-B Free Software License Agreement",
       "licenseId": "CECILL-B",
       "seeAlso": [
@@ -1244,11 +1281,11 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CECILL-C.json",
-      "referenceNumber": "75",
+      "referenceNumber": "77",
       "name": "CeCILL-C Free Software License Agreement",
       "licenseId": "CECILL-C",
       "seeAlso": [
-        "http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html\n    "
+        "http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html"
       ],
       "isOsiApproved": false
     },
@@ -1256,11 +1293,11 @@
       "reference": "./CERN-OHL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CERN-OHL-1.1.json",
-      "referenceNumber": "336",
+      "referenceNumber": "341",
       "name": "CERN Open Hardware License v1.1",
       "licenseId": "CERN-OHL-1.1",
       "seeAlso": [
-        "\nhttps://www.ohwr.org/project/licenses/wikis/cern-ohl-v1.1"
+        "https://www.ohwr.org/project/licenses/wikis/cern-ohl-v1.1"
       ],
       "isOsiApproved": false
     },
@@ -1272,7 +1309,7 @@
       "name": "CERN Open Hardware Licence v1.2",
       "licenseId": "CERN-OHL-1.2",
       "seeAlso": [
-        "\nhttps://www.ohwr.org/project/licenses/wikis/cern-ohl-v1.2"
+        "https://www.ohwr.org/project/licenses/wikis/cern-ohl-v1.2"
       ],
       "isOsiApproved": false
     },
@@ -1280,7 +1317,7 @@
       "reference": "./CNRI-Jython.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CNRI-Jython.json",
-      "referenceNumber": "91",
+      "referenceNumber": "94",
       "name": "CNRI Jython License",
       "licenseId": "CNRI-Jython",
       "seeAlso": [
@@ -1292,7 +1329,7 @@
       "reference": "./CNRI-Python.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CNRI-Python.json",
-      "referenceNumber": "44",
+      "referenceNumber": "45",
       "name": "CNRI Python License",
       "licenseId": "CNRI-Python",
       "seeAlso": [
@@ -1304,7 +1341,7 @@
       "reference": "./CNRI-Python-GPL-Compatible.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CNRI-Python-GPL-Compatible.json",
-      "referenceNumber": "199",
+      "referenceNumber": "202",
       "name": "CNRI Python Open Source GPL Compatible License Agreement",
       "licenseId": "CNRI-Python-GPL-Compatible",
       "seeAlso": [
@@ -1317,7 +1354,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CPAL-1.0.json",
-      "referenceNumber": "167",
+      "referenceNumber": "170",
       "name": "Common Public Attribution License 1.0",
       "licenseId": "CPAL-1.0",
       "seeAlso": [
@@ -1330,7 +1367,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/CPL-1.0.json",
-      "referenceNumber": "169",
+      "referenceNumber": "172",
       "name": "Common Public License 1.0",
       "licenseId": "CPL-1.0",
       "seeAlso": [
@@ -1342,7 +1379,7 @@
       "reference": "./CPOL-1.02.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CPOL-1.02.json",
-      "referenceNumber": "27",
+      "referenceNumber": "28",
       "name": "Code Project Open License 1.02",
       "licenseId": "CPOL-1.02",
       "seeAlso": [
@@ -1354,7 +1391,7 @@
       "reference": "./CUA-OPL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CUA-OPL-1.0.json",
-      "referenceNumber": "358",
+      "referenceNumber": "365",
       "name": "CUA Office Public License v1.0",
       "licenseId": "CUA-OPL-1.0",
       "seeAlso": [
@@ -1366,7 +1403,7 @@
       "reference": "./Caldera.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Caldera.json",
-      "referenceNumber": "105",
+      "referenceNumber": "108",
       "name": "Caldera License",
       "licenseId": "Caldera",
       "seeAlso": [
@@ -1379,7 +1416,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/ClArtistic.json",
-      "referenceNumber": "268",
+      "referenceNumber": "271",
       "name": "Clarified Artistic License",
       "licenseId": "ClArtistic",
       "seeAlso": [
@@ -1393,7 +1430,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Condor-1.1.json",
-      "referenceNumber": "304",
+      "referenceNumber": "307",
       "name": "Condor Public License v1.1",
       "licenseId": "Condor-1.1",
       "seeAlso": [
@@ -1406,7 +1443,7 @@
       "reference": "./Crossword.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Crossword.json",
-      "referenceNumber": "356",
+      "referenceNumber": "363",
       "name": "Crossword License",
       "licenseId": "Crossword",
       "seeAlso": [
@@ -1418,7 +1455,7 @@
       "reference": "./CrystalStacker.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/CrystalStacker.json",
-      "referenceNumber": "165",
+      "referenceNumber": "168",
       "name": "CrystalStacker License",
       "licenseId": "CrystalStacker",
       "seeAlso": [
@@ -1430,7 +1467,7 @@
       "reference": "./Cube.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Cube.json",
-      "referenceNumber": "363",
+      "referenceNumber": "370",
       "name": "Cube License",
       "licenseId": "Cube",
       "seeAlso": [
@@ -1442,7 +1479,7 @@
       "reference": "./D-FSL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/D-FSL-1.0.json",
-      "referenceNumber": "179",
+      "referenceNumber": "182",
       "name": "Deutsche Freie Software Lizenz",
       "licenseId": "D-FSL-1.0",
       "seeAlso": [
@@ -1461,7 +1498,7 @@
       "reference": "./DOC.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/DOC.json",
-      "referenceNumber": "157",
+      "referenceNumber": "160",
       "name": "DOC License",
       "licenseId": "DOC",
       "seeAlso": [
@@ -1473,7 +1510,7 @@
       "reference": "./DSDP.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/DSDP.json",
-      "referenceNumber": "138",
+      "referenceNumber": "141",
       "name": "DSDP License",
       "licenseId": "DSDP",
       "seeAlso": [
@@ -1485,7 +1522,7 @@
       "reference": "./Dotseqn.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Dotseqn.json",
-      "referenceNumber": "382",
+      "referenceNumber": "390",
       "name": "Dotseqn License",
       "licenseId": "Dotseqn",
       "seeAlso": [
@@ -1497,7 +1534,7 @@
       "reference": "./ECL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/ECL-1.0.json",
-      "referenceNumber": "388",
+      "referenceNumber": "396",
       "name": "Educational Community License v1.0",
       "licenseId": "ECL-1.0",
       "seeAlso": [
@@ -1510,7 +1547,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/ECL-2.0.json",
-      "referenceNumber": "295",
+      "referenceNumber": "298",
       "name": "Educational Community License v2.0",
       "licenseId": "ECL-2.0",
       "seeAlso": [
@@ -1522,7 +1559,7 @@
       "reference": "./EFL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/EFL-1.0.json",
-      "referenceNumber": "147",
+      "referenceNumber": "150",
       "name": "Eiffel Forum License v1.0",
       "licenseId": "EFL-1.0",
       "seeAlso": [
@@ -1536,7 +1573,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/EFL-2.0.json",
-      "referenceNumber": "158",
+      "referenceNumber": "161",
       "name": "Eiffel Forum License v2.0",
       "licenseId": "EFL-2.0",
       "seeAlso": [
@@ -1550,7 +1587,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/EPL-1.0.json",
-      "referenceNumber": "211",
+      "referenceNumber": "214",
       "name": "Eclipse Public License 1.0",
       "licenseId": "EPL-1.0",
       "seeAlso": [
@@ -1564,7 +1601,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/EPL-2.0.json",
-      "referenceNumber": "131",
+      "referenceNumber": "134",
       "name": "Eclipse Public License 2.0",
       "licenseId": "EPL-2.0",
       "seeAlso": [
@@ -1578,7 +1615,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/EUDatagrid.json",
-      "referenceNumber": "189",
+      "referenceNumber": "192",
       "name": "EU DataGrid Software License",
       "licenseId": "EUDatagrid",
       "seeAlso": [
@@ -1591,7 +1628,7 @@
       "reference": "./EUPL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/EUPL-1.0.json",
-      "referenceNumber": "170",
+      "referenceNumber": "173",
       "name": "European Union Public License 1.0",
       "licenseId": "EUPL-1.0",
       "seeAlso": [
@@ -1605,7 +1642,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/EUPL-1.1.json",
-      "referenceNumber": "89",
+      "referenceNumber": "92",
       "name": "European Union Public License 1.1",
       "licenseId": "EUPL-1.1",
       "seeAlso": [
@@ -1620,7 +1657,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/EUPL-1.2.json",
-      "referenceNumber": "379",
+      "referenceNumber": "387",
       "name": "European Union Public License 1.2",
       "licenseId": "EUPL-1.2",
       "seeAlso": [
@@ -1636,7 +1673,7 @@
       "reference": "./Entessa.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Entessa.json",
-      "referenceNumber": "96",
+      "referenceNumber": "99",
       "name": "Entessa Public License v1.0",
       "licenseId": "Entessa",
       "seeAlso": [
@@ -1648,7 +1685,7 @@
       "reference": "./ErlPL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/ErlPL-1.1.json",
-      "referenceNumber": "154",
+      "referenceNumber": "157",
       "name": "Erlang Public License v1.1",
       "licenseId": "ErlPL-1.1",
       "seeAlso": [
@@ -1660,7 +1697,7 @@
       "reference": "./Eurosym.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Eurosym.json",
-      "referenceNumber": "110",
+      "referenceNumber": "113",
       "name": "Eurosym License",
       "licenseId": "Eurosym",
       "seeAlso": [
@@ -1673,7 +1710,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/FSFAP.json",
-      "referenceNumber": "111",
+      "referenceNumber": "114",
       "name": "FSF All Permissive License",
       "licenseId": "FSFAP",
       "seeAlso": [
@@ -1685,7 +1722,7 @@
       "reference": "./FSFUL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/FSFUL.json",
-      "referenceNumber": "190",
+      "referenceNumber": "193",
       "name": "FSF Unlimited License",
       "licenseId": "FSFUL",
       "seeAlso": [
@@ -1697,7 +1734,7 @@
       "reference": "./FSFULLR.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/FSFULLR.json",
-      "referenceNumber": "42",
+      "referenceNumber": "43",
       "name": "FSF Unlimited License (with License Retention)",
       "licenseId": "FSFULLR",
       "seeAlso": [
@@ -1710,7 +1747,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/FTL.json",
-      "referenceNumber": "237",
+      "referenceNumber": "240",
       "name": "Freetype Project License",
       "licenseId": "FTL",
       "seeAlso": [
@@ -1723,7 +1760,7 @@
       "reference": "./Fair.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Fair.json",
-      "referenceNumber": "294",
+      "referenceNumber": "297",
       "name": "Fair License",
       "licenseId": "Fair",
       "seeAlso": [
@@ -1736,7 +1773,7 @@
       "reference": "./Frameworx-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Frameworx-1.0.json",
-      "referenceNumber": "381",
+      "referenceNumber": "389",
       "name": "Frameworx Open License 1.0",
       "licenseId": "Frameworx-1.0",
       "seeAlso": [
@@ -1748,7 +1785,7 @@
       "reference": "./FreeImage.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/FreeImage.json",
-      "referenceNumber": "274",
+      "referenceNumber": "277",
       "name": "FreeImage Public License v1.0",
       "licenseId": "FreeImage",
       "seeAlso": [
@@ -1761,7 +1798,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GFDL-1.1.json",
-      "referenceNumber": "95",
+      "referenceNumber": "98",
       "name": "GNU Free Documentation License v1.1",
       "licenseId": "GFDL-1.1",
       "seeAlso": [
@@ -1774,7 +1811,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GFDL-1.1-only.json",
-      "referenceNumber": "99",
+      "referenceNumber": "102",
       "name": "GNU Free Documentation License v1.1 only",
       "licenseId": "GFDL-1.1-only",
       "seeAlso": [
@@ -1787,7 +1824,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GFDL-1.1-or-later.json",
-      "referenceNumber": "343",
+      "referenceNumber": "348",
       "name": "GNU Free Documentation License v1.1 or later",
       "licenseId": "GFDL-1.1-or-later",
       "seeAlso": [
@@ -1800,7 +1837,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GFDL-1.2.json",
-      "referenceNumber": "194",
+      "referenceNumber": "197",
       "name": "GNU Free Documentation License v1.2",
       "licenseId": "GFDL-1.2",
       "seeAlso": [
@@ -1813,7 +1850,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GFDL-1.2-only.json",
-      "referenceNumber": "233",
+      "referenceNumber": "236",
       "name": "GNU Free Documentation License v1.2 only",
       "licenseId": "GFDL-1.2-only",
       "seeAlso": [
@@ -1826,7 +1863,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GFDL-1.2-or-later.json",
-      "referenceNumber": "212",
+      "referenceNumber": "215",
       "name": "GNU Free Documentation License v1.2 or later",
       "licenseId": "GFDL-1.2-or-later",
       "seeAlso": [
@@ -1839,7 +1876,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GFDL-1.3.json",
-      "referenceNumber": "109",
+      "referenceNumber": "112",
       "name": "GNU Free Documentation License v1.3",
       "licenseId": "GFDL-1.3",
       "seeAlso": [
@@ -1852,7 +1889,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GFDL-1.3-only.json",
-      "referenceNumber": "68",
+      "referenceNumber": "69",
       "name": "GNU Free Documentation License v1.3 only",
       "licenseId": "GFDL-1.3-only",
       "seeAlso": [
@@ -1877,7 +1914,7 @@
       "reference": "./GL2PS.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/GL2PS.json",
-      "referenceNumber": "121",
+      "referenceNumber": "124",
       "name": "GL2PS License",
       "licenseId": "GL2PS",
       "seeAlso": [
@@ -1889,7 +1926,7 @@
       "reference": "./GPL-1.0.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-1.0.json",
-      "referenceNumber": "77",
+      "referenceNumber": "79",
       "name": "GNU General Public License v1.0 only",
       "licenseId": "GPL-1.0",
       "seeAlso": [
@@ -1901,7 +1938,7 @@
       "reference": "./GPL-1.0+.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-1.0+.json",
-      "referenceNumber": "172",
+      "referenceNumber": "175",
       "name": "GNU General Public License v1.0 or later",
       "licenseId": "GPL-1.0+",
       "seeAlso": [
@@ -1925,7 +1962,7 @@
       "reference": "./GPL-1.0-or-later.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/GPL-1.0-or-later.json",
-      "referenceNumber": "350",
+      "referenceNumber": "357",
       "name": "GNU General Public License v1.0 or later",
       "licenseId": "GPL-1.0-or-later",
       "seeAlso": [
@@ -1938,7 +1975,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0.json",
-      "referenceNumber": "144",
+      "referenceNumber": "147",
       "name": "GNU General Public License v2.0 only",
       "licenseId": "GPL-2.0",
       "seeAlso": [
@@ -1952,7 +1989,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0+.json",
-      "referenceNumber": "73",
+      "referenceNumber": "75",
       "name": "GNU General Public License v2.0 or later",
       "licenseId": "GPL-2.0+",
       "seeAlso": [
@@ -1966,7 +2003,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0-only.json",
-      "referenceNumber": "230",
+      "referenceNumber": "233",
       "name": "GNU General Public License v2.0 only",
       "licenseId": "GPL-2.0-only",
       "seeAlso": [
@@ -1980,7 +2017,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0-or-later.json",
-      "referenceNumber": "55",
+      "referenceNumber": "56",
       "name": "GNU General Public License v2.0 or later",
       "licenseId": "GPL-2.0-or-later",
       "seeAlso": [
@@ -1993,7 +2030,7 @@
       "reference": "./GPL-2.0-with-GCC-exception.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0-with-GCC-exception.json",
-      "referenceNumber": "114",
+      "referenceNumber": "117",
       "name": "GNU General Public License v2.0 w/GCC Runtime Library exception",
       "licenseId": "GPL-2.0-with-GCC-exception",
       "seeAlso": [
@@ -2005,7 +2042,7 @@
       "reference": "./GPL-2.0-with-autoconf-exception.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0-with-autoconf-exception.json",
-      "referenceNumber": "349",
+      "referenceNumber": "355",
       "name": "GNU General Public License v2.0 w/Autoconf exception",
       "licenseId": "GPL-2.0-with-autoconf-exception",
       "seeAlso": [
@@ -2017,7 +2054,7 @@
       "reference": "./GPL-2.0-with-bison-exception.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0-with-bison-exception.json",
-      "referenceNumber": "370",
+      "referenceNumber": "378",
       "name": "GNU General Public License v2.0 w/Bison exception",
       "licenseId": "GPL-2.0-with-bison-exception",
       "seeAlso": [
@@ -2029,7 +2066,7 @@
       "reference": "./GPL-2.0-with-classpath-exception.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0-with-classpath-exception.json",
-      "referenceNumber": "59",
+      "referenceNumber": "60",
       "name": "GNU General Public License v2.0 w/Classpath exception",
       "licenseId": "GPL-2.0-with-classpath-exception",
       "seeAlso": [
@@ -2041,7 +2078,7 @@
       "reference": "./GPL-2.0-with-font-exception.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-2.0-with-font-exception.json",
-      "referenceNumber": "367",
+      "referenceNumber": "375",
       "name": "GNU General Public License v2.0 w/Font exception",
       "licenseId": "GPL-2.0-with-font-exception",
       "seeAlso": [
@@ -2054,7 +2091,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-3.0.json",
-      "referenceNumber": "239",
+      "referenceNumber": "242",
       "name": "GNU General Public License v3.0 only",
       "licenseId": "GPL-3.0",
       "seeAlso": [
@@ -2068,7 +2105,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-3.0+.json",
-      "referenceNumber": "71",
+      "referenceNumber": "73",
       "name": "GNU General Public License v3.0 or later",
       "licenseId": "GPL-3.0+",
       "seeAlso": [
@@ -2082,7 +2119,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-3.0-only.json",
-      "referenceNumber": "203",
+      "referenceNumber": "206",
       "name": "GNU General Public License v3.0 only",
       "licenseId": "GPL-3.0-only",
       "seeAlso": [
@@ -2096,7 +2133,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-3.0-or-later.json",
-      "referenceNumber": "193",
+      "referenceNumber": "196",
       "name": "GNU General Public License v3.0 or later",
       "licenseId": "GPL-3.0-or-later",
       "seeAlso": [
@@ -2109,7 +2146,7 @@
       "reference": "./GPL-3.0-with-GCC-exception.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-3.0-with-GCC-exception.json",
-      "referenceNumber": "218",
+      "referenceNumber": "221",
       "name": "GNU General Public License v3.0 w/GCC Runtime Library exception",
       "licenseId": "GPL-3.0-with-GCC-exception",
       "seeAlso": [
@@ -2121,7 +2158,7 @@
       "reference": "./GPL-3.0-with-autoconf-exception.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/GPL-3.0-with-autoconf-exception.json",
-      "referenceNumber": "232",
+      "referenceNumber": "235",
       "name": "GNU General Public License v3.0 w/Autoconf exception",
       "licenseId": "GPL-3.0-with-autoconf-exception",
       "seeAlso": [
@@ -2133,7 +2170,7 @@
       "reference": "./Giftware.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Giftware.json",
-      "referenceNumber": "362",
+      "referenceNumber": "369",
       "name": "Giftware License",
       "licenseId": "Giftware",
       "seeAlso": [
@@ -2145,7 +2182,7 @@
       "reference": "./Glide.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Glide.json",
-      "referenceNumber": "366",
+      "referenceNumber": "374",
       "name": "3dfx Glide License",
       "licenseId": "Glide",
       "seeAlso": [
@@ -2157,7 +2194,7 @@
       "reference": "./Glulxe.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Glulxe.json",
-      "referenceNumber": "90",
+      "referenceNumber": "93",
       "name": "Glulxe License",
       "licenseId": "Glulxe",
       "seeAlso": [
@@ -2170,7 +2207,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/HPND.json",
-      "referenceNumber": "261",
+      "referenceNumber": "264",
       "name": "Historical Permission Notice and Disclaimer",
       "licenseId": "HPND",
       "seeAlso": [
@@ -2182,7 +2219,7 @@
       "reference": "./HPND-sell-variant.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/HPND-sell-variant.json",
-      "referenceNumber": "142",
+      "referenceNumber": "145",
       "name": "Historical Permission Notice and Disclaimer - sell variant",
       "licenseId": "HPND-sell-variant",
       "seeAlso": [
@@ -2194,7 +2231,7 @@
       "reference": "./HaskellReport.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/HaskellReport.json",
-      "referenceNumber": "119",
+      "referenceNumber": "122",
       "name": "Haskell Language Report License",
       "licenseId": "HaskellReport",
       "seeAlso": [
@@ -2206,7 +2243,7 @@
       "reference": "./IBM-pibs.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/IBM-pibs.json",
-      "referenceNumber": "204",
+      "referenceNumber": "207",
       "name": "IBM PowerPC Initialization and Boot Software",
       "licenseId": "IBM-pibs",
       "seeAlso": [
@@ -2218,7 +2255,7 @@
       "reference": "./ICU.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/ICU.json",
-      "referenceNumber": "191",
+      "referenceNumber": "194",
       "name": "ICU License",
       "licenseId": "ICU",
       "seeAlso": [
@@ -2231,7 +2268,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/IJG.json",
-      "referenceNumber": "54",
+      "referenceNumber": "55",
       "name": "Independent JPEG Group License",
       "licenseId": "IJG",
       "seeAlso": [
@@ -2244,7 +2281,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/IPA.json",
-      "referenceNumber": "309",
+      "referenceNumber": "312",
       "name": "IPA Font License",
       "licenseId": "IPA",
       "seeAlso": [
@@ -2257,7 +2294,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/IPL-1.0.json",
-      "referenceNumber": "30",
+      "referenceNumber": "31",
       "name": "IBM Public License v1.0",
       "licenseId": "IPL-1.0",
       "seeAlso": [
@@ -2270,7 +2307,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/ISC.json",
-      "referenceNumber": "107",
+      "referenceNumber": "110",
       "name": "ISC License",
       "licenseId": "ISC",
       "seeAlso": [
@@ -2283,7 +2320,7 @@
       "reference": "./ImageMagick.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/ImageMagick.json",
-      "referenceNumber": "228",
+      "referenceNumber": "231",
       "name": "ImageMagick License",
       "licenseId": "ImageMagick",
       "seeAlso": [
@@ -2296,7 +2333,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Imlib2.json",
-      "referenceNumber": "254",
+      "referenceNumber": "257",
       "name": "Imlib2 License",
       "licenseId": "Imlib2",
       "seeAlso": [
@@ -2309,7 +2346,7 @@
       "reference": "./Info-ZIP.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Info-ZIP.json",
-      "referenceNumber": "101",
+      "referenceNumber": "104",
       "name": "Info-ZIP License",
       "licenseId": "Info-ZIP",
       "seeAlso": [
@@ -2322,7 +2359,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Intel.json",
-      "referenceNumber": "164",
+      "referenceNumber": "167",
       "name": "Intel Open Source License",
       "licenseId": "Intel",
       "seeAlso": [
@@ -2334,7 +2371,7 @@
       "reference": "./Intel-ACPI.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Intel-ACPI.json",
-      "referenceNumber": "86",
+      "referenceNumber": "88",
       "name": "Intel ACPI Software License Agreement",
       "licenseId": "Intel-ACPI",
       "seeAlso": [
@@ -2346,7 +2383,7 @@
       "reference": "./Interbase-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Interbase-1.0.json",
-      "referenceNumber": "81",
+      "referenceNumber": "83",
       "name": "Interbase Public License v1.0",
       "licenseId": "Interbase-1.0",
       "seeAlso": [
@@ -2358,7 +2395,7 @@
       "reference": "./JPNIC.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/JPNIC.json",
-      "referenceNumber": "102",
+      "referenceNumber": "105",
       "name": "Japan Network Information Center License",
       "licenseId": "JPNIC",
       "seeAlso": [
@@ -2370,7 +2407,7 @@
       "reference": "./JSON.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/JSON.json",
-      "referenceNumber": "364",
+      "referenceNumber": "372",
       "name": "JSON License",
       "licenseId": "JSON",
       "seeAlso": [
@@ -2382,7 +2419,7 @@
       "reference": "./JasPer-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/JasPer-2.0.json",
-      "referenceNumber": "236",
+      "referenceNumber": "239",
       "name": "JasPer License",
       "licenseId": "JasPer-2.0",
       "seeAlso": [
@@ -2394,7 +2431,7 @@
       "reference": "./LAL-1.2.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LAL-1.2.json",
-      "referenceNumber": "372",
+      "referenceNumber": "380",
       "name": "Licence Art Libre 1.2",
       "licenseId": "LAL-1.2",
       "seeAlso": [
@@ -2406,7 +2443,7 @@
       "reference": "./LAL-1.3.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LAL-1.3.json",
-      "referenceNumber": "153",
+      "referenceNumber": "156",
       "name": "Licence Art Libre 1.3",
       "licenseId": "LAL-1.3",
       "seeAlso": [
@@ -2418,7 +2455,7 @@
       "reference": "./LGPL-2.0.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-2.0.json",
-      "referenceNumber": "265",
+      "referenceNumber": "268",
       "name": "GNU Library General Public License v2 only",
       "licenseId": "LGPL-2.0",
       "seeAlso": [
@@ -2430,7 +2467,7 @@
       "reference": "./LGPL-2.0+.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-2.0+.json",
-      "referenceNumber": "51",
+      "referenceNumber": "52",
       "name": "GNU Library General Public License v2 or later",
       "licenseId": "LGPL-2.0+",
       "seeAlso": [
@@ -2442,7 +2479,7 @@
       "reference": "./LGPL-2.0-only.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LGPL-2.0-only.json",
-      "referenceNumber": "273",
+      "referenceNumber": "276",
       "name": "GNU Library General Public License v2 only",
       "licenseId": "LGPL-2.0-only",
       "seeAlso": [
@@ -2454,7 +2491,7 @@
       "reference": "./LGPL-2.0-or-later.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LGPL-2.0-or-later.json",
-      "referenceNumber": "214",
+      "referenceNumber": "217",
       "name": "GNU Library General Public License v2 or later",
       "licenseId": "LGPL-2.0-or-later",
       "seeAlso": [
@@ -2467,7 +2504,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-2.1.json",
-      "referenceNumber": "163",
+      "referenceNumber": "166",
       "name": "GNU Lesser General Public License v2.1 only",
       "licenseId": "LGPL-2.1",
       "seeAlso": [
@@ -2481,7 +2518,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-2.1+.json",
-      "referenceNumber": "63",
+      "referenceNumber": "64",
       "name": "GNU Library General Public License v2.1 or later",
       "licenseId": "LGPL-2.1+",
       "seeAlso": [
@@ -2509,7 +2546,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-2.1-or-later.json",
-      "referenceNumber": "333",
+      "referenceNumber": "338",
       "name": "GNU Lesser General Public License v2.1 or later",
       "licenseId": "LGPL-2.1-or-later",
       "seeAlso": [
@@ -2523,7 +2560,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-3.0.json",
-      "referenceNumber": "207",
+      "referenceNumber": "210",
       "name": "GNU Lesser General Public License v3.0 only",
       "licenseId": "LGPL-3.0",
       "seeAlso": [
@@ -2537,7 +2574,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-3.0+.json",
-      "referenceNumber": "149",
+      "referenceNumber": "152",
       "name": "GNU Lesser General Public License v3.0 or later",
       "licenseId": "LGPL-3.0+",
       "seeAlso": [
@@ -2551,7 +2588,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-3.0-only.json",
-      "referenceNumber": "251",
+      "referenceNumber": "254",
       "name": "GNU Lesser General Public License v3.0 only",
       "licenseId": "LGPL-3.0-only",
       "seeAlso": [
@@ -2565,7 +2602,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LGPL-3.0-or-later.json",
-      "referenceNumber": "298",
+      "referenceNumber": "301",
       "name": "GNU Lesser General Public License v3.0 or later",
       "licenseId": "LGPL-3.0-or-later",
       "seeAlso": [
@@ -2578,7 +2615,7 @@
       "reference": "./LGPLLR.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LGPLLR.json",
-      "referenceNumber": "100",
+      "referenceNumber": "103",
       "name": "Lesser General Public License For Linguistic Resources",
       "licenseId": "LGPLLR",
       "seeAlso": [
@@ -2590,7 +2627,7 @@
       "reference": "./LPL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LPL-1.0.json",
-      "referenceNumber": "87",
+      "referenceNumber": "89",
       "name": "Lucent Public License Version 1.0",
       "licenseId": "LPL-1.0",
       "seeAlso": [
@@ -2603,7 +2640,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LPL-1.02.json",
-      "referenceNumber": "128",
+      "referenceNumber": "131",
       "name": "Lucent Public License v1.02",
       "licenseId": "LPL-1.02",
       "seeAlso": [
@@ -2616,7 +2653,7 @@
       "reference": "./LPPL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LPPL-1.0.json",
-      "referenceNumber": "256",
+      "referenceNumber": "259",
       "name": "LaTeX Project Public License v1.0",
       "licenseId": "LPPL-1.0",
       "seeAlso": [
@@ -2628,7 +2665,7 @@
       "reference": "./LPPL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LPPL-1.1.json",
-      "referenceNumber": "306",
+      "referenceNumber": "309",
       "name": "LaTeX Project Public License v1.1",
       "licenseId": "LPPL-1.1",
       "seeAlso": [
@@ -2641,7 +2678,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LPPL-1.2.json",
-      "referenceNumber": "384",
+      "referenceNumber": "392",
       "name": "LaTeX Project Public License v1.2",
       "licenseId": "LPPL-1.2",
       "seeAlso": [
@@ -2654,7 +2691,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/LPPL-1.3a.json",
-      "referenceNumber": "302",
+      "referenceNumber": "305",
       "name": "LaTeX Project Public License v1.3a",
       "licenseId": "LPPL-1.3a",
       "seeAlso": [
@@ -2666,7 +2703,7 @@
       "reference": "./LPPL-1.3c.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LPPL-1.3c.json",
-      "referenceNumber": "322",
+      "referenceNumber": "326",
       "name": "LaTeX Project Public License v1.3c",
       "licenseId": "LPPL-1.3c",
       "seeAlso": [
@@ -2679,7 +2716,7 @@
       "reference": "./Latex2e.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Latex2e.json",
-      "referenceNumber": "280",
+      "referenceNumber": "283",
       "name": "Latex2e License",
       "licenseId": "Latex2e",
       "seeAlso": [
@@ -2691,7 +2728,7 @@
       "reference": "./Leptonica.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Leptonica.json",
-      "referenceNumber": "156",
+      "referenceNumber": "159",
       "name": "Leptonica License",
       "licenseId": "Leptonica",
       "seeAlso": [
@@ -2703,7 +2740,7 @@
       "reference": "./LiLiQ-P-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LiLiQ-P-1.1.json",
-      "referenceNumber": "371",
+      "referenceNumber": "379",
       "name": "Licence Libre du Québec – Permissive version 1.1",
       "licenseId": "LiLiQ-P-1.1",
       "seeAlso": [
@@ -2716,7 +2753,7 @@
       "reference": "./LiLiQ-R-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LiLiQ-R-1.1.json",
-      "referenceNumber": "283",
+      "referenceNumber": "286",
       "name": "Licence Libre du Québec – Réciprocité version 1.1",
       "licenseId": "LiLiQ-R-1.1",
       "seeAlso": [
@@ -2729,7 +2766,7 @@
       "reference": "./LiLiQ-Rplus-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/LiLiQ-Rplus-1.1.json",
-      "referenceNumber": "136",
+      "referenceNumber": "139",
       "name": "Licence Libre du Québec – Réciprocité forte version 1.1",
       "licenseId": "LiLiQ-Rplus-1.1",
       "seeAlso": [
@@ -2742,7 +2779,7 @@
       "reference": "./Libpng.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Libpng.json",
-      "referenceNumber": "98",
+      "referenceNumber": "101",
       "name": "libpng License",
       "licenseId": "Libpng",
       "seeAlso": [
@@ -2767,7 +2804,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/MIT.json",
-      "referenceNumber": "198",
+      "referenceNumber": "201",
       "name": "MIT License",
       "licenseId": "MIT",
       "seeAlso": [
@@ -2818,7 +2855,7 @@
       "reference": "./MIT-enna.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/MIT-enna.json",
-      "referenceNumber": "24",
+      "referenceNumber": "25",
       "name": "enna License",
       "licenseId": "MIT-enna",
       "seeAlso": [
@@ -2830,7 +2867,7 @@
       "reference": "./MIT-feh.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/MIT-feh.json",
-      "referenceNumber": "37",
+      "referenceNumber": "38",
       "name": "feh License",
       "licenseId": "MIT-feh",
       "seeAlso": [
@@ -2842,7 +2879,7 @@
       "reference": "./MITNFA.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/MITNFA.json",
-      "referenceNumber": "291",
+      "referenceNumber": "294",
       "name": "MIT +no-false-attribs license",
       "licenseId": "MITNFA",
       "seeAlso": [
@@ -2854,7 +2891,7 @@
       "reference": "./MPL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/MPL-1.0.json",
-      "referenceNumber": "48",
+      "referenceNumber": "49",
       "name": "Mozilla Public License 1.0",
       "licenseId": "MPL-1.0",
       "seeAlso": [
@@ -2868,7 +2905,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/MPL-1.1.json",
-      "referenceNumber": "301",
+      "referenceNumber": "304",
       "name": "Mozilla Public License 1.1",
       "licenseId": "MPL-1.1",
       "seeAlso": [
@@ -2882,7 +2919,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/MPL-2.0.json",
-      "referenceNumber": "231",
+      "referenceNumber": "234",
       "name": "Mozilla Public License 2.0",
       "licenseId": "MPL-2.0",
       "seeAlso": [
@@ -2895,7 +2932,7 @@
       "reference": "./MPL-2.0-no-copyleft-exception.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/MPL-2.0-no-copyleft-exception.json",
-      "referenceNumber": "300",
+      "referenceNumber": "303",
       "name": "Mozilla Public License 2.0 (no copyleft exception)",
       "licenseId": "MPL-2.0-no-copyleft-exception",
       "seeAlso": [
@@ -2909,7 +2946,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/MS-PL.json",
-      "referenceNumber": "331",
+      "referenceNumber": "336",
       "name": "Microsoft Public License",
       "licenseId": "MS-PL",
       "seeAlso": [
@@ -2923,7 +2960,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/MS-RL.json",
-      "referenceNumber": "277",
+      "referenceNumber": "280",
       "name": "Microsoft Reciprocal License",
       "licenseId": "MS-RL",
       "seeAlso": [
@@ -2936,7 +2973,7 @@
       "reference": "./MTLL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/MTLL.json",
-      "referenceNumber": "178",
+      "referenceNumber": "181",
       "name": "Matrix Template Library License",
       "licenseId": "MTLL",
       "seeAlso": [
@@ -2948,7 +2985,7 @@
       "reference": "./MakeIndex.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/MakeIndex.json",
-      "referenceNumber": "184",
+      "referenceNumber": "187",
       "name": "MakeIndex License",
       "licenseId": "MakeIndex",
       "seeAlso": [
@@ -2960,7 +2997,7 @@
       "reference": "./MirOS.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/MirOS.json",
-      "referenceNumber": "296",
+      "referenceNumber": "299",
       "name": "MirOS License",
       "licenseId": "MirOS",
       "seeAlso": [
@@ -2972,7 +3009,7 @@
       "reference": "./Motosoto.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Motosoto.json",
-      "referenceNumber": "313",
+      "referenceNumber": "317",
       "name": "Motosoto License",
       "licenseId": "Motosoto",
       "seeAlso": [
@@ -2984,7 +3021,7 @@
       "reference": "./Multics.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Multics.json",
-      "referenceNumber": "62",
+      "referenceNumber": "63",
       "name": "Multics License",
       "licenseId": "Multics",
       "seeAlso": [
@@ -2996,7 +3033,7 @@
       "reference": "./Mup.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Mup.json",
-      "referenceNumber": "347",
+      "referenceNumber": "353",
       "name": "Mup License",
       "licenseId": "Mup",
       "seeAlso": [
@@ -3008,7 +3045,7 @@
       "reference": "./NASA-1.3.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NASA-1.3.json",
-      "referenceNumber": "85",
+      "referenceNumber": "87",
       "name": "NASA Open Source Agreement 1.3",
       "licenseId": "NASA-1.3",
       "seeAlso": [
@@ -3021,7 +3058,7 @@
       "reference": "./NBPL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NBPL-1.0.json",
-      "referenceNumber": "354",
+      "referenceNumber": "361",
       "name": "Net Boolean Public License v1",
       "licenseId": "NBPL-1.0",
       "seeAlso": [
@@ -3034,7 +3071,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/NCSA.json",
-      "referenceNumber": "57",
+      "referenceNumber": "58",
       "name": "University of Illinois/NCSA Open Source License",
       "licenseId": "NCSA",
       "seeAlso": [
@@ -3047,7 +3084,7 @@
       "reference": "./NGPL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NGPL.json",
-      "referenceNumber": "70",
+      "referenceNumber": "71",
       "name": "Nethack General Public License",
       "licenseId": "NGPL",
       "seeAlso": [
@@ -3059,7 +3096,7 @@
       "reference": "./NLOD-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NLOD-1.0.json",
-      "referenceNumber": "206",
+      "referenceNumber": "209",
       "name": "Norwegian Licence for Open Government Data",
       "licenseId": "NLOD-1.0",
       "seeAlso": [
@@ -3071,7 +3108,7 @@
       "reference": "./NLPL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NLPL.json",
-      "referenceNumber": "339",
+      "referenceNumber": "344",
       "name": "No Limit Public License",
       "licenseId": "NLPL",
       "seeAlso": [
@@ -3084,7 +3121,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/NOSL.json",
-      "referenceNumber": "375",
+      "referenceNumber": "383",
       "name": "Netizen Open Source License",
       "licenseId": "NOSL",
       "seeAlso": [
@@ -3097,7 +3134,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/NPL-1.0.json",
-      "referenceNumber": "324",
+      "referenceNumber": "328",
       "name": "Netscape Public License v1.0",
       "licenseId": "NPL-1.0",
       "seeAlso": [
@@ -3110,7 +3147,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/NPL-1.1.json",
-      "referenceNumber": "182",
+      "referenceNumber": "185",
       "name": "Netscape Public License v1.1",
       "licenseId": "NPL-1.1",
       "seeAlso": [
@@ -3122,7 +3159,7 @@
       "reference": "./NPOSL-3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NPOSL-3.0.json",
-      "referenceNumber": "219",
+      "referenceNumber": "222",
       "name": "Non-Profit Open Software License 3.0",
       "licenseId": "NPOSL-3.0",
       "seeAlso": [
@@ -3134,7 +3171,7 @@
       "reference": "./NRL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NRL.json",
-      "referenceNumber": "52",
+      "referenceNumber": "53",
       "name": "NRL License",
       "licenseId": "NRL",
       "seeAlso": [
@@ -3146,7 +3183,7 @@
       "reference": "./NTP.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NTP.json",
-      "referenceNumber": "258",
+      "referenceNumber": "261",
       "name": "NTP License",
       "licenseId": "NTP",
       "seeAlso": [
@@ -3158,7 +3195,7 @@
       "reference": "./Naumen.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Naumen.json",
-      "referenceNumber": "275",
+      "referenceNumber": "278",
       "name": "Naumen Public License",
       "licenseId": "Naumen",
       "seeAlso": [
@@ -3170,7 +3207,7 @@
       "reference": "./Net-SNMP.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Net-SNMP.json",
-      "referenceNumber": "281",
+      "referenceNumber": "284",
       "name": "Net-SNMP License",
       "licenseId": "Net-SNMP",
       "seeAlso": [
@@ -3182,7 +3219,7 @@
       "reference": "./NetCDF.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/NetCDF.json",
-      "referenceNumber": "45",
+      "referenceNumber": "46",
       "name": "NetCDF license",
       "licenseId": "NetCDF",
       "seeAlso": [
@@ -3194,7 +3231,7 @@
       "reference": "./Newsletr.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Newsletr.json",
-      "referenceNumber": "276",
+      "referenceNumber": "279",
       "name": "Newsletr License",
       "licenseId": "Newsletr",
       "seeAlso": [
@@ -3207,7 +3244,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Nokia.json",
-      "referenceNumber": "323",
+      "referenceNumber": "327",
       "name": "Nokia Open Source License",
       "licenseId": "Nokia",
       "seeAlso": [
@@ -3219,7 +3256,7 @@
       "reference": "./Noweb.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Noweb.json",
-      "referenceNumber": "357",
+      "referenceNumber": "364",
       "name": "Noweb License",
       "licenseId": "Noweb",
       "seeAlso": [
@@ -3232,7 +3269,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Nunit.json",
-      "referenceNumber": "285",
+      "referenceNumber": "288",
       "name": "Nunit License",
       "licenseId": "Nunit",
       "seeAlso": [
@@ -3244,7 +3281,7 @@
       "reference": "./OCCT-PL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OCCT-PL.json",
-      "referenceNumber": "279",
+      "referenceNumber": "282",
       "name": "Open CASCADE Technology Public License",
       "licenseId": "OCCT-PL",
       "seeAlso": [
@@ -3256,7 +3293,7 @@
       "reference": "./OCLC-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OCLC-2.0.json",
-      "referenceNumber": "108",
+      "referenceNumber": "111",
       "name": "OCLC Research Public License 2.0",
       "licenseId": "OCLC-2.0",
       "seeAlso": [
@@ -3269,7 +3306,7 @@
       "reference": "./ODC-By-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/ODC-By-1.0.json",
-      "referenceNumber": "141",
+      "referenceNumber": "144",
       "name": "Open Data Commons Attribution License v1.0",
       "licenseId": "ODC-By-1.0",
       "seeAlso": [
@@ -3282,7 +3319,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/ODbL-1.0.json",
-      "referenceNumber": "243",
+      "referenceNumber": "246",
       "name": "ODC Open Database License v1.0",
       "licenseId": "ODbL-1.0",
       "seeAlso": [
@@ -3295,7 +3332,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OFL-1.0.json",
-      "referenceNumber": "150",
+      "referenceNumber": "153",
       "name": "SIL Open Font License 1.0",
       "licenseId": "OFL-1.0",
       "seeAlso": [
@@ -3308,7 +3345,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OFL-1.1.json",
-      "referenceNumber": "311",
+      "referenceNumber": "315",
       "name": "SIL Open Font License 1.1",
       "licenseId": "OFL-1.1",
       "seeAlso": [
@@ -3321,7 +3358,7 @@
       "reference": "./OGL-UK-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OGL-UK-1.0.json",
-      "referenceNumber": "113",
+      "referenceNumber": "116",
       "name": "Open Government Licence v1.0",
       "licenseId": "OGL-UK-1.0",
       "seeAlso": [
@@ -3333,7 +3370,7 @@
       "reference": "./OGL-UK-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OGL-UK-2.0.json",
-      "referenceNumber": "286",
+      "referenceNumber": "289",
       "name": "Open Government Licence v2.0",
       "licenseId": "OGL-UK-2.0",
       "seeAlso": [
@@ -3345,7 +3382,7 @@
       "reference": "./OGL-UK-3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OGL-UK-3.0.json",
-      "referenceNumber": "223",
+      "referenceNumber": "226",
       "name": "Open Government Licence v3.0",
       "licenseId": "OGL-UK-3.0",
       "seeAlso": [
@@ -3357,7 +3394,7 @@
       "reference": "./OGTSL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OGTSL.json",
-      "referenceNumber": "122",
+      "referenceNumber": "125",
       "name": "Open Group Test Suite License",
       "licenseId": "OGTSL",
       "seeAlso": [
@@ -3370,7 +3407,7 @@
       "reference": "./OLDAP-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-1.1.json",
-      "referenceNumber": "94",
+      "referenceNumber": "97",
       "name": "Open LDAP Public License v1.1",
       "licenseId": "OLDAP-1.1",
       "seeAlso": [
@@ -3382,7 +3419,7 @@
       "reference": "./OLDAP-1.2.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-1.2.json",
-      "referenceNumber": "187",
+      "referenceNumber": "190",
       "name": "Open LDAP Public License v1.2",
       "licenseId": "OLDAP-1.2",
       "seeAlso": [
@@ -3394,7 +3431,7 @@
       "reference": "./OLDAP-1.3.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-1.3.json",
-      "referenceNumber": "103",
+      "referenceNumber": "106",
       "name": "Open LDAP Public License v1.3",
       "licenseId": "OLDAP-1.3",
       "seeAlso": [
@@ -3406,7 +3443,7 @@
       "reference": "./OLDAP-1.4.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-1.4.json",
-      "referenceNumber": "29",
+      "referenceNumber": "30",
       "name": "Open LDAP Public License v1.4",
       "licenseId": "OLDAP-1.4",
       "seeAlso": [
@@ -3418,7 +3455,7 @@
       "reference": "./OLDAP-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.0.json",
-      "referenceNumber": "263",
+      "referenceNumber": "266",
       "name": "Open LDAP Public License v2.0 (or possibly 2.0A and 2.0B)",
       "licenseId": "OLDAP-2.0",
       "seeAlso": [
@@ -3430,7 +3467,7 @@
       "reference": "./OLDAP-2.0.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.0.1.json",
-      "referenceNumber": "344",
+      "referenceNumber": "350",
       "name": "Open LDAP Public License v2.0.1",
       "licenseId": "OLDAP-2.0.1",
       "seeAlso": [
@@ -3442,7 +3479,7 @@
       "reference": "./OLDAP-2.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.1.json",
-      "referenceNumber": "151",
+      "referenceNumber": "154",
       "name": "Open LDAP Public License v2.1",
       "licenseId": "OLDAP-2.1",
       "seeAlso": [
@@ -3454,7 +3491,7 @@
       "reference": "./OLDAP-2.2.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.2.json",
-      "referenceNumber": "355",
+      "referenceNumber": "362",
       "name": "Open LDAP Public License v2.2",
       "licenseId": "OLDAP-2.2",
       "seeAlso": [
@@ -3466,7 +3503,7 @@
       "reference": "./OLDAP-2.2.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.2.1.json",
-      "referenceNumber": "334",
+      "referenceNumber": "339",
       "name": "Open LDAP Public License v2.2.1",
       "licenseId": "OLDAP-2.2.1",
       "seeAlso": [
@@ -3478,7 +3515,7 @@
       "reference": "./OLDAP-2.2.2.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.2.2.json",
-      "referenceNumber": "196",
+      "referenceNumber": "199",
       "name": "Open LDAP Public License 2.2.2",
       "licenseId": "OLDAP-2.2.2",
       "seeAlso": [
@@ -3491,7 +3528,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.3.json",
-      "referenceNumber": "161",
+      "referenceNumber": "164",
       "name": "Open LDAP Public License v2.3",
       "licenseId": "OLDAP-2.3",
       "seeAlso": [
@@ -3503,7 +3540,7 @@
       "reference": "./OLDAP-2.4.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.4.json",
-      "referenceNumber": "65",
+      "referenceNumber": "66",
       "name": "Open LDAP Public License v2.4",
       "licenseId": "OLDAP-2.4",
       "seeAlso": [
@@ -3515,7 +3552,7 @@
       "reference": "./OLDAP-2.5.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.5.json",
-      "referenceNumber": "180",
+      "referenceNumber": "183",
       "name": "Open LDAP Public License v2.5",
       "licenseId": "OLDAP-2.5",
       "seeAlso": [
@@ -3527,7 +3564,7 @@
       "reference": "./OLDAP-2.6.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.6.json",
-      "referenceNumber": "60",
+      "referenceNumber": "61",
       "name": "Open LDAP Public License v2.6",
       "licenseId": "OLDAP-2.6",
       "seeAlso": [
@@ -3540,7 +3577,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.7.json",
-      "referenceNumber": "120",
+      "referenceNumber": "123",
       "name": "Open LDAP Public License v2.7",
       "licenseId": "OLDAP-2.7",
       "seeAlso": [
@@ -3552,7 +3589,7 @@
       "reference": "./OLDAP-2.8.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OLDAP-2.8.json",
-      "referenceNumber": "36",
+      "referenceNumber": "37",
       "name": "Open LDAP Public License v2.8",
       "licenseId": "OLDAP-2.8",
       "seeAlso": [
@@ -3564,7 +3601,7 @@
       "reference": "./OML.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OML.json",
-      "referenceNumber": "64",
+      "referenceNumber": "65",
       "name": "Open Market License",
       "licenseId": "OML",
       "seeAlso": [
@@ -3576,7 +3613,7 @@
       "reference": "./OPL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OPL-1.0.json",
-      "referenceNumber": "338",
+      "referenceNumber": "343",
       "name": "Open Public License v1.0",
       "licenseId": "OPL-1.0",
       "seeAlso": [
@@ -3589,7 +3626,7 @@
       "reference": "./OSET-PL-2.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/OSET-PL-2.1.json",
-      "referenceNumber": "288",
+      "referenceNumber": "291",
       "name": "OSET Public License version 2.1",
       "licenseId": "OSET-PL-2.1",
       "seeAlso": [
@@ -3603,7 +3640,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OSL-1.0.json",
-      "referenceNumber": "83",
+      "referenceNumber": "85",
       "name": "Open Software License 1.0",
       "licenseId": "OSL-1.0",
       "seeAlso": [
@@ -3616,7 +3653,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OSL-1.1.json",
-      "referenceNumber": "329",
+      "referenceNumber": "334",
       "name": "Open Software License 1.1",
       "licenseId": "OSL-1.1",
       "seeAlso": [
@@ -3642,7 +3679,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OSL-2.1.json",
-      "referenceNumber": "23",
+      "referenceNumber": "24",
       "name": "Open Software License 2.1",
       "licenseId": "OSL-2.1",
       "seeAlso": [
@@ -3656,7 +3693,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OSL-3.0.json",
-      "referenceNumber": "97",
+      "referenceNumber": "100",
       "name": "Open Software License 3.0",
       "licenseId": "OSL-3.0",
       "seeAlso": [
@@ -3670,7 +3707,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/OpenSSL.json",
-      "referenceNumber": "246",
+      "referenceNumber": "249",
       "name": "OpenSSL License",
       "licenseId": "OpenSSL",
       "seeAlso": [
@@ -3694,7 +3731,7 @@
       "reference": "./PHP-3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/PHP-3.0.json",
-      "referenceNumber": "377",
+      "referenceNumber": "385",
       "name": "PHP License v3.0",
       "licenseId": "PHP-3.0",
       "seeAlso": [
@@ -3708,7 +3745,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/PHP-3.01.json",
-      "referenceNumber": "312",
+      "referenceNumber": "316",
       "name": "PHP License v3.01",
       "licenseId": "PHP-3.01",
       "seeAlso": [
@@ -3716,11 +3753,23 @@
       ],
       "isOsiApproved": false
     },
+    {
+      "reference": "./Parity-6.0.0.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/Parity-6.0.0.json",
+      "referenceNumber": "91",
+      "name": "The Parity Public License 6.0.0",
+      "licenseId": "Parity-6.0.0",
+      "seeAlso": [
+        "https://paritylicense.com/versions/6.0.0.html"
+      ],
+      "isOsiApproved": false
+    },
     {
       "reference": "./Plexus.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Plexus.json",
-      "referenceNumber": "222",
+      "referenceNumber": "225",
       "name": "Plexus Classworlds License",
       "licenseId": "Plexus",
       "seeAlso": [
@@ -3732,7 +3781,7 @@
       "reference": "./PostgreSQL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/PostgreSQL.json",
-      "referenceNumber": "244",
+      "referenceNumber": "247",
       "name": "PostgreSQL License",
       "licenseId": "PostgreSQL",
       "seeAlso": [
@@ -3746,7 +3795,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Python-2.0.json",
-      "referenceNumber": "34",
+      "referenceNumber": "35",
       "name": "Python License 2.0",
       "licenseId": "Python-2.0",
       "seeAlso": [
@@ -3759,7 +3808,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/QPL-1.0.json",
-      "referenceNumber": "26",
+      "referenceNumber": "27",
       "name": "Q Public License 1.0",
       "licenseId": "QPL-1.0",
       "seeAlso": [
@@ -3772,7 +3821,7 @@
       "reference": "./Qhull.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Qhull.json",
-      "referenceNumber": "66",
+      "referenceNumber": "67",
       "name": "Qhull License",
       "licenseId": "Qhull",
       "seeAlso": [
@@ -3784,7 +3833,7 @@
       "reference": "./RHeCos-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/RHeCos-1.1.json",
-      "referenceNumber": "146",
+      "referenceNumber": "149",
       "name": "Red Hat eCos Public License v1.1",
       "licenseId": "RHeCos-1.1",
       "seeAlso": [
@@ -3796,7 +3845,7 @@
       "reference": "./RPL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/RPL-1.1.json",
-      "referenceNumber": "266",
+      "referenceNumber": "269",
       "name": "Reciprocal Public License 1.1",
       "licenseId": "RPL-1.1",
       "seeAlso": [
@@ -3808,7 +3857,7 @@
       "reference": "./RPL-1.5.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/RPL-1.5.json",
-      "referenceNumber": "224",
+      "referenceNumber": "227",
       "name": "Reciprocal Public License 1.5",
       "licenseId": "RPL-1.5",
       "seeAlso": [
@@ -3821,7 +3870,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/RPSL-1.0.json",
-      "referenceNumber": "270",
+      "referenceNumber": "273",
       "name": "RealNetworks Public Source License v1.0",
       "licenseId": "RPSL-1.0",
       "seeAlso": [
@@ -3834,7 +3883,7 @@
       "reference": "./RSA-MD.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/RSA-MD.json",
-      "referenceNumber": "80",
+      "referenceNumber": "82",
       "name": "RSA Message-Digest License ",
       "licenseId": "RSA-MD",
       "seeAlso": [
@@ -3846,7 +3895,7 @@
       "reference": "./RSCPL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/RSCPL.json",
-      "referenceNumber": "208",
+      "referenceNumber": "211",
       "name": "Ricoh Source Code Public License",
       "licenseId": "RSCPL",
       "seeAlso": [
@@ -3859,7 +3908,7 @@
       "reference": "./Rdisc.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Rdisc.json",
-      "referenceNumber": "292",
+      "referenceNumber": "295",
       "name": "Rdisc License",
       "licenseId": "Rdisc",
       "seeAlso": [
@@ -3872,7 +3921,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Ruby.json",
-      "referenceNumber": "260",
+      "referenceNumber": "263",
       "name": "Ruby License",
       "licenseId": "Ruby",
       "seeAlso": [
@@ -3884,7 +3933,7 @@
       "reference": "./SAX-PD.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/SAX-PD.json",
-      "referenceNumber": "137",
+      "referenceNumber": "140",
       "name": "Sax Public Domain Notice",
       "licenseId": "SAX-PD",
       "seeAlso": [
@@ -3908,7 +3957,7 @@
       "reference": "./SGI-B-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/SGI-B-1.0.json",
-      "referenceNumber": "88",
+      "referenceNumber": "90",
       "name": "SGI Free Software License B v1.0",
       "licenseId": "SGI-B-1.0",
       "seeAlso": [
@@ -3920,7 +3969,7 @@
       "reference": "./SGI-B-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/SGI-B-1.1.json",
-      "referenceNumber": "238",
+      "referenceNumber": "241",
       "name": "SGI Free Software License B v1.1",
       "licenseId": "SGI-B-1.1",
       "seeAlso": [
@@ -3933,7 +3982,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/SGI-B-2.0.json",
-      "referenceNumber": "269",
+      "referenceNumber": "272",
       "name": "SGI Free Software License B v2.0",
       "licenseId": "SGI-B-2.0",
       "seeAlso": [
@@ -3941,12 +3990,36 @@
       ],
       "isOsiApproved": false
     },
+    {
+      "reference": "./SHL-0.5.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/SHL-0.5.json",
+      "referenceNumber": "72",
+      "name": "Solderpad Hardware License v0.5",
+      "licenseId": "SHL-0.5",
+      "seeAlso": [
+        "https://solderpad.org/licenses/SHL-0.5/"
+      ],
+      "isOsiApproved": false
+    },
+    {
+      "reference": "./SHL-0.51.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/SHL-0.51.json",
+      "referenceNumber": "314",
+      "name": "Solderpad Hardware License, Version 0.51",
+      "licenseId": "SHL-0.51",
+      "seeAlso": [
+        "https://solderpad.org/licenses/SHL-0.51/"
+      ],
+      "isOsiApproved": false
+    },
     {
       "reference": "./SISSL.html",
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/SISSL.json",
-      "referenceNumber": "72",
+      "referenceNumber": "74",
       "name": "Sun Industry Standards Source License v1.1",
       "licenseId": "SISSL",
       "seeAlso": [
@@ -3972,7 +4045,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/SMLNJ.json",
-      "referenceNumber": "293",
+      "referenceNumber": "296",
       "name": "Standard ML of New Jersey License",
       "licenseId": "SMLNJ",
       "seeAlso": [
@@ -3984,7 +4057,7 @@
       "reference": "./SMPPL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/SMPPL.json",
-      "referenceNumber": "124",
+      "referenceNumber": "127",
       "name": "Secure Messaging Protocol Public License",
       "licenseId": "SMPPL",
       "seeAlso": [
@@ -3996,7 +4069,7 @@
       "reference": "./SNIA.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/SNIA.json",
-      "referenceNumber": "227",
+      "referenceNumber": "230",
       "name": "SNIA Public License 1.1",
       "licenseId": "SNIA",
       "seeAlso": [
@@ -4009,7 +4082,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/SPL-1.0.json",
-      "referenceNumber": "53",
+      "referenceNumber": "54",
       "name": "Sun Public License v1.0",
       "licenseId": "SPL-1.0",
       "seeAlso": [
@@ -4017,11 +4090,23 @@
       ],
       "isOsiApproved": true
     },
+    {
+      "reference": "./SSPL-1.0.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/SSPL-1.0.json",
+      "referenceNumber": "356",
+      "name": "Server Side Public License, v 1",
+      "licenseId": "SSPL-1.0",
+      "seeAlso": [
+        "https://www.mongodb.com/licensing/server-side-public-license"
+      ],
+      "isOsiApproved": false
+    },
     {
       "reference": "./SWL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/SWL.json",
-      "referenceNumber": "205",
+      "referenceNumber": "208",
       "name": "Scheme Widget Library (SWL) Software License Agreement",
       "licenseId": "SWL",
       "seeAlso": [
@@ -4045,7 +4130,7 @@
       "reference": "./Sendmail.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Sendmail.json",
-      "referenceNumber": "148",
+      "referenceNumber": "151",
       "name": "Sendmail License",
       "licenseId": "Sendmail",
       "seeAlso": [
@@ -4058,7 +4143,7 @@
       "reference": "./Sendmail-8.23.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Sendmail-8.23.json",
-      "referenceNumber": "40",
+      "referenceNumber": "41",
       "name": "Sendmail License 8.23",
       "licenseId": "Sendmail-8.23",
       "seeAlso": [
@@ -4071,7 +4156,7 @@
       "reference": "./SimPL-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/SimPL-2.0.json",
-      "referenceNumber": "181",
+      "referenceNumber": "184",
       "name": "Simple Public License 2.0",
       "licenseId": "SimPL-2.0",
       "seeAlso": [
@@ -4084,7 +4169,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Sleepycat.json",
-      "referenceNumber": "287",
+      "referenceNumber": "290",
       "name": "Sleepycat License",
       "licenseId": "Sleepycat",
       "seeAlso": [
@@ -4096,7 +4181,7 @@
       "reference": "./Spencer-86.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Spencer-86.json",
-      "referenceNumber": "310",
+      "referenceNumber": "313",
       "name": "Spencer License 86",
       "licenseId": "Spencer-86",
       "seeAlso": [
@@ -4108,7 +4193,7 @@
       "reference": "./Spencer-94.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Spencer-94.json",
-      "referenceNumber": "28",
+      "referenceNumber": "29",
       "name": "Spencer License 94",
       "licenseId": "Spencer-94",
       "seeAlso": [
@@ -4120,7 +4205,7 @@
       "reference": "./Spencer-99.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Spencer-99.json",
-      "referenceNumber": "378",
+      "referenceNumber": "386",
       "name": "Spencer License 99",
       "licenseId": "Spencer-99",
       "seeAlso": [
@@ -4133,7 +4218,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/StandardML-NJ.json",
-      "referenceNumber": "216",
+      "referenceNumber": "219",
       "name": "Standard ML of New Jersey License",
       "licenseId": "StandardML-NJ",
       "seeAlso": [
@@ -4145,7 +4230,7 @@
       "reference": "./SugarCRM-1.1.3.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/SugarCRM-1.1.3.json",
-      "referenceNumber": "289",
+      "referenceNumber": "292",
       "name": "SugarCRM Public License v1.1.3",
       "licenseId": "SugarCRM-1.1.3",
       "seeAlso": [
@@ -4157,11 +4242,11 @@
       "reference": "./TAPR-OHL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/TAPR-OHL-1.0.json",
-      "referenceNumber": "264",
+      "referenceNumber": "267",
       "name": "TAPR Open Hardware License v1.0",
       "licenseId": "TAPR-OHL-1.0",
       "seeAlso": [
-        "\nhttps://www.tapr.org/OHL"
+        "https://www.tapr.org/OHL"
       ],
       "isOsiApproved": false
     },
@@ -4169,7 +4254,7 @@
       "reference": "./TCL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/TCL.json",
-      "referenceNumber": "262",
+      "referenceNumber": "265",
       "name": "TCL/TK License",
       "licenseId": "TCL",
       "seeAlso": [
@@ -4182,7 +4267,7 @@
       "reference": "./TCP-wrappers.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/TCP-wrappers.json",
-      "referenceNumber": "271",
+      "referenceNumber": "274",
       "name": "TCP Wrappers License",
       "licenseId": "TCP-wrappers",
       "seeAlso": [
@@ -4194,7 +4279,7 @@
       "reference": "./TMate.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/TMate.json",
-      "referenceNumber": "250",
+      "referenceNumber": "253",
       "name": "TMate Open Source License",
       "licenseId": "TMate",
       "seeAlso": [
@@ -4206,7 +4291,7 @@
       "reference": "./TORQUE-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/TORQUE-1.1.json",
-      "referenceNumber": "168",
+      "referenceNumber": "171",
       "name": "TORQUE v2.5+ Software License v1.1",
       "licenseId": "TORQUE-1.1",
       "seeAlso": [
@@ -4218,7 +4303,7 @@
       "reference": "./TOSL.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/TOSL.json",
-      "referenceNumber": "353",
+      "referenceNumber": "360",
       "name": "Trusster Open Source License",
       "licenseId": "TOSL",
       "seeAlso": [
@@ -4230,7 +4315,7 @@
       "reference": "./TU-Berlin-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/TU-Berlin-1.0.json",
-      "referenceNumber": "365",
+      "referenceNumber": "373",
       "name": "Technische Universitaet Berlin License 1.0",
       "licenseId": "TU-Berlin-1.0",
       "seeAlso": [
@@ -4242,7 +4327,7 @@
       "reference": "./TU-Berlin-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/TU-Berlin-2.0.json",
-      "referenceNumber": "383",
+      "referenceNumber": "391",
       "name": "Technische Universitaet Berlin License 2.0",
       "licenseId": "TU-Berlin-2.0",
       "seeAlso": [
@@ -4255,7 +4340,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/UPL-1.0.json",
-      "referenceNumber": "202",
+      "referenceNumber": "205",
       "name": "Universal Permissive License v1.0",
       "licenseId": "UPL-1.0",
       "seeAlso": [
@@ -4279,7 +4364,7 @@
       "reference": "./Unicode-DFS-2016.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Unicode-DFS-2016.json",
-      "referenceNumber": "374",
+      "referenceNumber": "382",
       "name": "Unicode License Agreement - Data Files and Software (2016)",
       "licenseId": "Unicode-DFS-2016",
       "seeAlso": [
@@ -4291,7 +4376,7 @@
       "reference": "./Unicode-TOU.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Unicode-TOU.json",
-      "referenceNumber": "69",
+      "referenceNumber": "70",
       "name": "Unicode Terms of Use",
       "licenseId": "Unicode-TOU",
       "seeAlso": [
@@ -4304,7 +4389,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Unlicense.json",
-      "referenceNumber": "290",
+      "referenceNumber": "293",
       "name": "The Unlicense",
       "licenseId": "Unlicense",
       "seeAlso": [
@@ -4316,7 +4401,7 @@
       "reference": "./VOSTROM.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/VOSTROM.json",
-      "referenceNumber": "225",
+      "referenceNumber": "228",
       "name": "VOSTROM Public License for Open Source",
       "licenseId": "VOSTROM",
       "seeAlso": [
@@ -4328,7 +4413,7 @@
       "reference": "./VSL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/VSL-1.0.json",
-      "referenceNumber": "177",
+      "referenceNumber": "180",
       "name": "Vovida Software License v1.0",
       "licenseId": "VSL-1.0",
       "seeAlso": [
@@ -4341,7 +4426,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Vim.json",
-      "referenceNumber": "130",
+      "referenceNumber": "133",
       "name": "Vim License",
       "licenseId": "Vim",
       "seeAlso": [
@@ -4354,7 +4439,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/W3C.json",
-      "referenceNumber": "345",
+      "referenceNumber": "351",
       "name": "W3C Software Notice and License (2002-12-31)",
       "licenseId": "W3C",
       "seeAlso": [
@@ -4367,7 +4452,7 @@
       "reference": "./W3C-19980720.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/W3C-19980720.json",
-      "referenceNumber": "319",
+      "referenceNumber": "323",
       "name": "W3C Software Notice and License (1998-07-20)",
       "licenseId": "W3C-19980720",
       "seeAlso": [
@@ -4379,7 +4464,7 @@
       "reference": "./W3C-20150513.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/W3C-20150513.json",
-      "referenceNumber": "50",
+      "referenceNumber": "51",
       "name": "W3C Software Notice and Document License (2015-05-13)",
       "licenseId": "W3C-20150513",
       "seeAlso": [
@@ -4392,7 +4477,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/WTFPL.json",
-      "referenceNumber": "361",
+      "referenceNumber": "368",
       "name": "Do What The F*ck You Want To Public License",
       "licenseId": "WTFPL",
       "seeAlso": [
@@ -4404,7 +4489,7 @@
       "reference": "./Watcom-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Watcom-1.0.json",
-      "referenceNumber": "174",
+      "referenceNumber": "177",
       "name": "Sybase Open Watcom Public License 1.0",
       "licenseId": "Watcom-1.0",
       "seeAlso": [
@@ -4416,7 +4501,7 @@
       "reference": "./Wsuipa.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Wsuipa.json",
-      "referenceNumber": "132",
+      "referenceNumber": "135",
       "name": "Wsuipa License",
       "licenseId": "Wsuipa",
       "seeAlso": [
@@ -4429,7 +4514,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/X11.json",
-      "referenceNumber": "185",
+      "referenceNumber": "188",
       "name": "X11 License",
       "licenseId": "X11",
       "seeAlso": [
@@ -4442,7 +4527,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/XFree86-1.1.json",
-      "referenceNumber": "240",
+      "referenceNumber": "243",
       "name": "XFree86 License 1.1",
       "licenseId": "XFree86-1.1",
       "seeAlso": [
@@ -4454,7 +4539,7 @@
       "reference": "./XSkat.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/XSkat.json",
-      "referenceNumber": "93",
+      "referenceNumber": "96",
       "name": "XSkat License",
       "licenseId": "XSkat",
       "seeAlso": [
@@ -4466,7 +4551,7 @@
       "reference": "./Xerox.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Xerox.json",
-      "referenceNumber": "160",
+      "referenceNumber": "163",
       "name": "Xerox License",
       "licenseId": "Xerox",
       "seeAlso": [
@@ -4478,7 +4563,7 @@
       "reference": "./Xnet.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Xnet.json",
-      "referenceNumber": "380",
+      "referenceNumber": "388",
       "name": "X.Net License",
       "licenseId": "Xnet",
       "seeAlso": [
@@ -4490,7 +4575,7 @@
       "reference": "./YPL-1.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/YPL-1.0.json",
-      "referenceNumber": "171",
+      "referenceNumber": "174",
       "name": "Yahoo! Public License v1.0",
       "licenseId": "YPL-1.0",
       "seeAlso": [
@@ -4503,7 +4588,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/YPL-1.1.json",
-      "referenceNumber": "56",
+      "referenceNumber": "57",
       "name": "Yahoo! Public License v1.1",
       "licenseId": "YPL-1.1",
       "seeAlso": [
@@ -4515,7 +4600,7 @@
       "reference": "./ZPL-1.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/ZPL-1.1.json",
-      "referenceNumber": "352",
+      "referenceNumber": "359",
       "name": "Zope Public License 1.1",
       "licenseId": "ZPL-1.1",
       "seeAlso": [
@@ -4528,7 +4613,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/ZPL-2.0.json",
-      "referenceNumber": "76",
+      "referenceNumber": "78",
       "name": "Zope Public License 2.0",
       "licenseId": "ZPL-2.0",
       "seeAlso": [
@@ -4542,7 +4627,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/ZPL-2.1.json",
-      "referenceNumber": "340",
+      "referenceNumber": "345",
       "name": "Zope Public License 2.1",
       "licenseId": "ZPL-2.1",
       "seeAlso": [
@@ -4554,7 +4639,7 @@
       "reference": "./Zed.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Zed.json",
-      "referenceNumber": "245",
+      "referenceNumber": "248",
       "name": "Zed License",
       "licenseId": "Zed",
       "seeAlso": [
@@ -4567,7 +4652,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Zend-2.0.json",
-      "referenceNumber": "195",
+      "referenceNumber": "198",
       "name": "Zend License v2.0",
       "licenseId": "Zend-2.0",
       "seeAlso": [
@@ -4580,7 +4665,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Zimbra-1.3.json",
-      "referenceNumber": "39",
+      "referenceNumber": "40",
       "name": "Zimbra Public License v1.3",
       "licenseId": "Zimbra-1.3",
       "seeAlso": [
@@ -4592,7 +4677,7 @@
       "reference": "./Zimbra-1.4.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/Zimbra-1.4.json",
-      "referenceNumber": "235",
+      "referenceNumber": "238",
       "name": "Zimbra Public License v1.4",
       "licenseId": "Zimbra-1.4",
       "seeAlso": [
@@ -4605,7 +4690,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/Zlib.json",
-      "referenceNumber": "316",
+      "referenceNumber": "320",
       "name": "zlib License",
       "licenseId": "Zlib",
       "seeAlso": [
@@ -4614,11 +4699,24 @@
       ],
       "isOsiApproved": true
     },
+    {
+      "reference": "./blessing.html",
+      "isDeprecatedLicenseId": false,
+      "detailsUrl": "http://spdx.org/licenses/blessing.json",
+      "referenceNumber": "331",
+      "name": "SQLite Blessing",
+      "licenseId": "blessing",
+      "seeAlso": [
+        "https://www.sqlite.org/src/artifact/e33a4df7e32d742a?ln\u003d4-9",
+        "https://sqlite.org/src/artifact/df5091916dbb40e6"
+      ],
+      "isOsiApproved": false
+    },
     {
       "reference": "./bzip2-1.0.5.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/bzip2-1.0.5.json",
-      "referenceNumber": "197",
+      "referenceNumber": "200",
       "name": "bzip2 and libbzip2 License v1.0.5",
       "licenseId": "bzip2-1.0.5",
       "seeAlso": [
@@ -4630,7 +4728,7 @@
       "reference": "./bzip2-1.0.6.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/bzip2-1.0.6.json",
-      "referenceNumber": "299",
+      "referenceNumber": "302",
       "name": "bzip2 and libbzip2 License v1.0.6",
       "licenseId": "bzip2-1.0.6",
       "seeAlso": [
@@ -4642,7 +4740,7 @@
       "reference": "./copyleft-next-0.3.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/copyleft-next-0.3.0.json",
-      "referenceNumber": "173",
+      "referenceNumber": "176",
       "name": "copyleft-next 0.3.0",
       "licenseId": "copyleft-next-0.3.0",
       "seeAlso": [
@@ -4654,7 +4752,7 @@
       "reference": "./copyleft-next-0.3.1.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/copyleft-next-0.3.1.json",
-      "referenceNumber": "342",
+      "referenceNumber": "347",
       "name": "copyleft-next 0.3.1",
       "licenseId": "copyleft-next-0.3.1",
       "seeAlso": [
@@ -4666,7 +4764,7 @@
       "reference": "./curl.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/curl.json",
-      "referenceNumber": "257",
+      "referenceNumber": "260",
       "name": "curl License",
       "licenseId": "curl",
       "seeAlso": [
@@ -4678,7 +4776,7 @@
       "reference": "./diffmark.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/diffmark.json",
-      "referenceNumber": "360",
+      "referenceNumber": "367",
       "name": "diffmark license",
       "licenseId": "diffmark",
       "seeAlso": [
@@ -4690,7 +4788,7 @@
       "reference": "./dvipdfm.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/dvipdfm.json",
-      "referenceNumber": "140",
+      "referenceNumber": "143",
       "name": "dvipdfm License",
       "licenseId": "dvipdfm",
       "seeAlso": [
@@ -4703,7 +4801,7 @@
       "isDeprecatedLicenseId": true,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/eCos-2.0.json",
-      "referenceNumber": "325",
+      "referenceNumber": "329",
       "name": "eCos license version 2.0",
       "licenseId": "eCos-2.0",
       "seeAlso": [
@@ -4715,7 +4813,7 @@
       "reference": "./eGenix.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/eGenix.json",
-      "referenceNumber": "201",
+      "referenceNumber": "204",
       "name": "eGenix.com Public License 1.1.0",
       "licenseId": "eGenix",
       "seeAlso": [
@@ -4728,7 +4826,7 @@
       "reference": "./gSOAP-1.3b.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/gSOAP-1.3b.json",
-      "referenceNumber": "341",
+      "referenceNumber": "346",
       "name": "gSOAP Public License v1.3b",
       "licenseId": "gSOAP-1.3b",
       "seeAlso": [
@@ -4754,7 +4852,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/iMatix.json",
-      "referenceNumber": "337",
+      "referenceNumber": "342",
       "name": "iMatix Standard Function Library Agreement",
       "licenseId": "iMatix",
       "seeAlso": [
@@ -4766,11 +4864,11 @@
       "reference": "./libpng-2.0.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/libpng-2.0.json",
-      "referenceNumber": "74",
+      "referenceNumber": "76",
       "name": "PNG Reference Library version 2",
       "licenseId": "libpng-2.0",
       "seeAlso": [
-        "http://www.libpng.org/pub/png/src/libpng-LICENSE.txt\n         "
+        "http://www.libpng.org/pub/png/src/libpng-LICENSE.txt"
       ],
       "isOsiApproved": false
     },
@@ -4778,7 +4876,7 @@
       "reference": "./libtiff.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/libtiff.json",
-      "referenceNumber": "217",
+      "referenceNumber": "220",
       "name": "libtiff License",
       "licenseId": "libtiff",
       "seeAlso": [
@@ -4790,7 +4888,7 @@
       "reference": "./mpich2.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/mpich2.json",
-      "referenceNumber": "314",
+      "referenceNumber": "318",
       "name": "mpich2 License",
       "licenseId": "mpich2",
       "seeAlso": [
@@ -4802,7 +4900,7 @@
       "reference": "./psfrag.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/psfrag.json",
-      "referenceNumber": "242",
+      "referenceNumber": "245",
       "name": "psfrag License",
       "licenseId": "psfrag",
       "seeAlso": [
@@ -4814,7 +4912,7 @@
       "reference": "./psutils.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/psutils.json",
-      "referenceNumber": "123",
+      "referenceNumber": "126",
       "name": "psutils License",
       "licenseId": "psutils",
       "seeAlso": [
@@ -4826,7 +4924,7 @@
       "reference": "./wxWindows.html",
       "isDeprecatedLicenseId": true,
       "detailsUrl": "http://spdx.org/licenses/wxWindows.json",
-      "referenceNumber": "84",
+      "referenceNumber": "86",
       "name": "wxWindows Library License",
       "licenseId": "wxWindows",
       "seeAlso": [
@@ -4839,7 +4937,7 @@
       "isDeprecatedLicenseId": false,
       "isFsfLibre": true,
       "detailsUrl": "http://spdx.org/licenses/xinetd.json",
-      "referenceNumber": "143",
+      "referenceNumber": "146",
       "name": "xinetd License",
       "licenseId": "xinetd",
       "seeAlso": [
@@ -4851,7 +4949,7 @@
       "reference": "./xpp.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/xpp.json",
-      "referenceNumber": "272",
+      "referenceNumber": "275",
       "name": "XPP License",
       "licenseId": "xpp",
       "seeAlso": [
@@ -4863,7 +4961,7 @@
       "reference": "./zlib-acknowledgement.html",
       "isDeprecatedLicenseId": false,
       "detailsUrl": "http://spdx.org/licenses/zlib-acknowledgement.json",
-      "referenceNumber": "317",
+      "referenceNumber": "321",
       "name": "zlib/libpng License with Acknowledgement",
       "licenseId": "zlib-acknowledgement",
       "seeAlso": [
@@ -4872,5 +4970,5 @@
       "isOsiApproved": false
     }
   ],
-  "releaseDate": "2019-04-02"
+  "releaseDate": "2019-07-10"
 }
\ No newline at end of file
diff --git a/solver-benchmarks/solver-benchmarks.cabal b/solver-benchmarks/solver-benchmarks.cabal
index d3175488d201f88d45fcb65e910691f78ca60216..f91a00db496a591036334a265c5efbb87b883475 100644
--- a/solver-benchmarks/solver-benchmarks.cabal
+++ b/solver-benchmarks/solver-benchmarks.cabal
@@ -1,5 +1,5 @@
 name:          solver-benchmarks
-version:       3.0.0.0
+version:       3.1.0.0
 copyright:     2003-2017, Cabal Development Team (see AUTHORS file)
 license:       BSD3
 license-file:  LICENSE
diff --git a/travis-common.sh b/travis-common.sh
index d6fe02c5acdd9051a740deba285387f75a469799..0582e28a566ecd9d0de60d8af2d019b5c42dd16a 100644
--- a/travis-common.sh
+++ b/travis-common.sh
@@ -1,8 +1,8 @@
 set -e
 
 HACKAGE_REPO_TOOL_VERSION="0.1.1.1"
-CABAL_VERSION="3.0.0.0"
-CABAL_INSTALL_VERSION="3.0.0.0"
+CABAL_VERSION="3.1.0.0"
+CABAL_INSTALL_VERSION="3.1.0.0"
 
 if [ "$TRAVIS_OS_NAME" = "linux" ]; then
     ARCH="x86_64-linux"
diff --git a/travis-deploy.sh b/travis-deploy.sh
index 88d7ddbbb9ba40abe719f7803d3974c3c3673409..e90c2fdb3b5647e2a6432b20244f2ba0cb2f2c1d 100755
--- a/travis-deploy.sh
+++ b/travis-deploy.sh
@@ -8,7 +8,7 @@ deploy() {
     (cd cabal-website && git checkout --track -b gh-pages origin/gh-pages)
     rm -rf cabal-website/doc
     mkdir -p cabal-website/doc/html
-    mv dist-newstyle/build/`uname -m`-$TRAVIS_OS_NAME/ghc-$GHCVER/Cabal-3.0.0.0/doc/html/Cabal \
+    mv dist-newstyle/build/`uname -m`-$TRAVIS_OS_NAME/ghc-$GHCVER/Cabal-3.1.0.0/doc/html/Cabal \
        cabal-website/doc/html/Cabal
     (cd cabal-website && git add --all .)
     (cd cabal-website && \
diff --git a/travis-install.sh b/travis-install.sh
index ab66fffca78f6831fb5d8689b087e7ca921c01ac..ade6e57e91e3a8c7b8d1b833e4d597d17085cfc0 100755
--- a/travis-install.sh
+++ b/travis-install.sh
@@ -18,9 +18,9 @@ if [ -z ${STACK_CONFIG+x} ]; then
 
         if [ "$SCRIPT" = "meta" ]; then
             # change to /tmp so cabal.project doesn't affect new-install
-            cabal update
-            (cd /tmp && cabal new-install alex --constraint='alex ^>= 3.2.4')
-            (cd /tmp && cabal new-install happy --constraint='happy ^>= 1.19.9')
+            cabal v2-update
+            (cd /tmp && cabal v2-install alex --constraint='alex ^>= 3.2.4' --overwrite=always)
+            (cd /tmp && cabal v2-install happy --constraint='happy ^>= 1.19.9' --overwrite=always)
         fi
 
     elif [ "$TRAVIS_OS_NAME" = "osx" ]; then
diff --git a/validate.sh b/validate.sh
index 6e6353c63b2ff20bf16ac306745f6fccc07b9ff7..15c19d40f7ca11332e6ed8c4e746ef129d2bbc07 100755
--- a/validate.sh
+++ b/validate.sh
@@ -177,7 +177,7 @@ timed $CABALPLAN --version
 #######################################################################
 
 # NOTE: This should match cabal-testsuite version
-CABAL_VERSION="3.0.0.0"
+CABAL_VERSION="3.1.0.0"
 
 if [ "$(uname)" = "Linux" ]; then
     ARCH="x86_64-linux"