From 1548a395816a7df08fc8dbdd68a063d5c4e6743b Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 11 Nov 2026 13:42:40 -0700 Subject: [PATCH 01/17] Graft MicroHs support (5a4fd8f2a..e46621ead) onto 73d3ffda3e Cherry-pick of 23eefcaed (MicroHs support squashed) with conflicts resolved: Stage->Machine renames applied to Machine.hs, HEAD's dependency bounds and Machine/InMachine logic kept, MicroHs compatibility changes (flag mhs stanzas, c-sources, ifdef __MHS__ guards, fundep IsNode instances, positional GADT constructors) preserved. Verified with GHC 9.14.1 build of lib:Cabal-syntax, lib:Cabal, lib:cabal-install-solver, lib:cabal-install and exe:cabal. --- .../src/Distribution/Simple/SetupHooks.hs | 2 +- Cabal-syntax/Cabal-syntax.cabal | 36 +- Cabal-syntax/cbits/mhs_posix.c | 194 + Cabal-syntax/cbits/mhs_posix.h | 41 + .../src/Distribution/Compat/Directory.hs | 399 +++ Cabal-syntax/src/Distribution/Compat/Graph.hs | 124 +- .../Compat/Internal/LazyByteString.hs | 43 + .../Distribution/Compat/Internal/MhsPosix.hs | 324 ++ .../src/Distribution/Compat/MhsInstances.hs | 32 + .../src/Distribution/Compat/NonEmptySet.hs | 19 +- .../src/Distribution/Compat/Prelude.hs | 127 +- Cabal-syntax/src/Distribution/Compiler.hs | 1 + .../Distribution/FieldGrammar/FieldDescrs.hs | 12 + .../src/Distribution/FieldGrammar/Newtypes.hs | 1 - .../src/Distribution/FieldGrammar/Parsec.hs | 12 + .../src/Distribution/FieldGrammar/Pretty.hs | 12 + Cabal-syntax/src/Distribution/Fields/Field.hs | 1 + Cabal-syntax/src/Distribution/Fields/Lexer.hs | 3165 +++++++++++++++++ .../src/Distribution/Fields/Pretty.hs | 1 + .../PackageDescription/FieldGrammar.hs | 575 ++- .../Distribution/PackageDescription/Quirks.hs | 1 - .../Distribution/SPDX/LicenseExceptionId.hs | 59 +- .../src/Distribution/SPDX/LicenseId.hs | 149 +- .../Distribution/Types/BenchmarkInterface.hs | 2 - .../src/Distribution/Types/BuildInfo.hs | 2 - .../src/Distribution/Types/BuildInfo/Lens.hs | 2 - .../src/Distribution/Types/ComponentId.hs | 2 +- .../src/Distribution/Types/CondTree.hs | 26 +- .../src/Distribution/Types/Condition.hs | 16 +- .../src/Distribution/Types/Executable.hs | 2 - .../src/Distribution/Types/Executable/Lens.hs | 2 - .../src/Distribution/Types/ForeignLib.hs | 2 - .../src/Distribution/Types/ForeignLib/Lens.hs | 2 - .../Types/InstalledPackageInfo.hs | 4 +- .../InstalledPackageInfo/FieldGrammar.hs | 73 +- .../Distribution/Types/PackageDescription.hs | 2 - .../Types/PackageDescription/Lens.hs | 2 - .../Distribution/Types/TestSuiteInterface.hs | 2 - .../Types/VersionRange/Internal.hs | 3 +- Cabal-syntax/src/Distribution/Utils/Base62.hs | 5 + .../src/Distribution/Utils/Generic.hs | 24 +- Cabal-syntax/src/Distribution/Utils/MD5.hs | 94 +- Cabal-syntax/src/Distribution/Utils/Path.hs | 149 +- Cabal-syntax/src/Distribution/Utils/String.hs | 2 +- .../src/Distribution/Utils/Structured.hs | 56 +- Cabal-tests/Cabal-tests.cabal | 2 + Cabal-tests/lib/Test/Utils/TempTestDir.hs | 2 +- Cabal-tests/tests/CheckTests.hs | 2 +- Cabal-tests/tests/HackageTests.hs | 2 +- Cabal-tests/tests/ParserTests.hs | 2 +- Cabal-tests/tests/UnitTests.hs | 6 + .../Distribution/Compat/Directory.hs | 114 + .../UnitTests/Distribution/Compat/Graph.hs | 149 +- .../UnitTests/Distribution/Compat/Prelude.hs | 40 + .../tests/UnitTests/Distribution/SPDX.hs | 23 + .../UnitTests/Distribution/Simple/Glob.hs | 2 +- .../UnitTests/Distribution/Simple/Utils.hs | 2 +- .../tests/custom-setup/CabalDoctestSetup.hs | 2 +- Cabal-tests/tests/custom-setup/IdrisSetup.hs | 4 +- Cabal/Cabal.cabal | 84 +- Cabal/cbits/mhs_handle.c | 108 + Cabal/cbits/mhs_handle.h | 20 + Cabal/cbits/mhs_spawn.c | 185 + Cabal/cbits/mhs_spawn.h | 21 + .../Distribution/Backpack/ComponentsGraph.hs | 3 +- Cabal/src/Distribution/Backpack/Configure.hs | 8 +- .../Backpack/ConfiguredComponent.hs | 6 + .../Distribution/Backpack/DescribeUnitId.hs | 1 + .../Distribution/Backpack/LinkedComponent.hs | 6 +- Cabal/src/Distribution/Backpack/MixLink.hs | 3 +- .../src/Distribution/Backpack/ModuleScope.hs | 1 + .../Distribution/Backpack/ReadyComponent.hs | 8 +- Cabal/src/Distribution/Backpack/UnifyM.hs | 2 +- Cabal/src/Distribution/Compat/Async.hs | 3 +- Cabal/src/Distribution/Compat/CopyFile.hs | 77 +- Cabal/src/Distribution/Compat/CreatePipe.hs | 22 +- Cabal/src/Distribution/Compat/Environment.hs | 11 + .../Compat/Internal/MhsProcess.hs | 501 +++ .../Distribution/Compat/Internal/TempFile.hs | 97 +- Cabal/src/Distribution/Compat/Process.hs | 446 ++- Cabal/src/Distribution/Compat/ResponseFile.hs | 85 + Cabal/src/Distribution/Compat/Stack.hs | 41 + Cabal/src/Distribution/Compat/Time.hs | 2 +- .../Distribution/PackageDescription/Check.hs | 16 +- .../PackageDescription/Check/Warning.hs | 3 +- Cabal/src/Distribution/Simple.hs | 19 +- Cabal/src/Distribution/Simple/Bench.hs | 6 +- Cabal/src/Distribution/Simple/Build.hs | 24 +- .../src/Distribution/Simple/Build/Macros/Z.hs | 7 + .../Simple/Build/PackageInfoModule/Z.hs | 3 + .../Simple/Build/PathsModule/Z.hs | 3 + Cabal/src/Distribution/Simple/BuildPaths.hs | 10 +- Cabal/src/Distribution/Simple/BuildTarget.hs | 3 +- Cabal/src/Distribution/Simple/Command.hs | 3 + Cabal/src/Distribution/Simple/Compiler.hs | 105 +- Cabal/src/Distribution/Simple/Configure.hs | 29 +- .../Distribution/Simple/ConfigureScript.hs | 3 +- Cabal/src/Distribution/Simple/Errors.hs | 12 + Cabal/src/Distribution/Simple/GHC.hs | 12 +- Cabal/src/Distribution/Simple/GHC/Build.hs | 6 +- .../Simple/GHC/Build/ExtraSources.hs | 3 +- .../src/Distribution/Simple/GHC/Build/Link.hs | 5 +- .../Distribution/Simple/GHC/Build/Modules.hs | 4 +- .../Distribution/Simple/GHC/Build/Utils.hs | 2 - .../Simple/GHC/EnvironmentParser.hs | 2 +- Cabal/src/Distribution/Simple/GHC/Internal.hs | 4 +- Cabal/src/Distribution/Simple/Glob.hs | 4 +- Cabal/src/Distribution/Simple/Haddock.hs | 14 +- Cabal/src/Distribution/Simple/Hpc.hs | 4 +- Cabal/src/Distribution/Simple/Install.hs | 5 +- Cabal/src/Distribution/Simple/InstallDirs.hs | 69 +- .../src/Distribution/Simple/LocalBuildInfo.hs | 3 +- .../Distribution/Simple/PackageDescription.hs | 4 +- Cabal/src/Distribution/Simple/PreProcess.hs | 8 +- .../Distribution/Simple/PreProcess/Types.hs | 2 - Cabal/src/Distribution/Simple/Program.hs | 2 - Cabal/src/Distribution/Simple/Program/Ar.hs | 22 +- Cabal/src/Distribution/Simple/Program/Db.hs | 2 +- Cabal/src/Distribution/Simple/Program/Find.hs | 2 +- Cabal/src/Distribution/Simple/Program/GHC.hs | 5 +- .../src/Distribution/Simple/Program/HcPkg.hs | 3 +- Cabal/src/Distribution/Simple/Program/Hpc.hs | 2 - Cabal/src/Distribution/Simple/Program/Ld.hs | 4 +- .../Simple/Program/ResponseFile.hs | 2 - Cabal/src/Distribution/Simple/Program/Run.hs | 1 - Cabal/src/Distribution/Simple/Register.hs | 10 +- Cabal/src/Distribution/Simple/Setup.hs | 1 - .../Distribution/Simple/Setup/Benchmark.hs | 8 +- Cabal/src/Distribution/Simple/Setup/Build.hs | 8 +- Cabal/src/Distribution/Simple/Setup/Clean.hs | 8 +- Cabal/src/Distribution/Simple/Setup/Common.hs | 1 - Cabal/src/Distribution/Simple/Setup/Config.hs | 7 +- Cabal/src/Distribution/Simple/Setup/Copy.hs | 8 +- Cabal/src/Distribution/Simple/Setup/Global.hs | 1 - .../src/Distribution/Simple/Setup/Haddock.hs | 8 +- .../src/Distribution/Simple/Setup/Hscolour.hs | 8 +- .../src/Distribution/Simple/Setup/Install.hs | 8 +- .../src/Distribution/Simple/Setup/Register.hs | 8 +- Cabal/src/Distribution/Simple/Setup/Repl.hs | 8 +- Cabal/src/Distribution/Simple/Setup/SDist.hs | 8 +- Cabal/src/Distribution/Simple/Setup/Test.hs | 8 +- .../Distribution/Simple/SetupHooks/Errors.hs | 2 +- .../Simple/SetupHooks/HooksMain.hs | 56 +- .../Simple/SetupHooks/Internal.hs | 41 +- .../Distribution/Simple/SetupHooks/Rule.hs | 276 +- .../src/Distribution/Simple/ShowBuildInfo.hs | 1 - Cabal/src/Distribution/Simple/SrcDist.hs | 4 +- Cabal/src/Distribution/Simple/Test.hs | 3 +- Cabal/src/Distribution/Simple/Test/ExeV10.hs | 39 +- Cabal/src/Distribution/Simple/Test/LibV09.hs | 26 +- Cabal/src/Distribution/Simple/UHC.hs | 3 +- Cabal/src/Distribution/Simple/Utils.hs | 78 +- .../Types/ComponentLocalBuildInfo.hs | 5 +- .../Distribution/Types/LocalBuildConfig.hs | 3 +- .../src/Distribution/Types/LocalBuildInfo.hs | 164 +- Cabal/src/Distribution/Types/TargetInfo.hs | 5 +- Cabal/src/Distribution/Utils/IOData.hs | 24 +- Cabal/src/Distribution/Utils/LogProgress.hs | 12 +- Cabal/src/Distribution/Utils/UnionFind.hs | 14 + Cabal/src/Distribution/Verbosity.hs | 13 +- Cabal/tests/ProcessCaptureTests.hs | 370 ++ Makefile | 6 + cabal-dev-scripts/src/GenSPDX.hs | 16 + cabal-dev-scripts/src/GenSPDXExc.hs | 16 + cabal-dev-scripts/src/GenUtils.hs | 1 + .../cabal-install-solver.cabal | 25 +- .../src/Distribution/Solver/Modular/Cycles.hs | 8 +- .../Distribution/Solver/Modular/Dependency.hs | 12 + .../Solver/Modular/MessageUtils.hs | 31 + .../Distribution/Solver/Modular/Validate.hs | 8 + .../Solver/Modular/WeightedPSQ.hs | 6 + .../Solver/Types/ComponentDeps.hs | 1 + .../src/Distribution/Solver/Types/Machine.hs | 1 + .../Distribution/Solver/Types/PkgConfigDb.hs | 12 + .../Solver/Types/ProjectConfigPath.hs | 24 +- .../Solver/Types/ResolverPackage.hs | 4 +- cabal-install/cabal-install.cabal | 67 +- cabal-install/cbits/mhs_sha256.c | 27 + cabal-install/cbits/mhs_sha256.h | 21 + .../parser-tests/Tests/ParserTests.hs | 2 +- .../Client/BuildReports/Anonymous.hs | 3 + .../Client/BuildReports/Storage.hs | 2 +- .../src/Distribution/Client/Check.hs | 4 +- .../src/Distribution/Client/CmdBench.hs | 11 + .../src/Distribution/Client/CmdClean.hs | 25 +- .../src/Distribution/Client/CmdConfigure.hs | 2 +- .../src/Distribution/Client/CmdGenBounds.hs | 2 +- .../src/Distribution/Client/CmdHaddock.hs | 10 +- .../Distribution/Client/CmdHaddockProject.hs | 10 +- .../src/Distribution/Client/CmdInstall.hs | 2 +- .../src/Distribution/Client/CmdOutdated.hs | 5 +- .../src/Distribution/Client/CmdRepl.hs | 7 +- .../src/Distribution/Client/CmdRun.hs | 14 +- .../src/Distribution/Client/CmdSdist.hs | 5 +- .../src/Distribution/Client/CmdTarget.hs | 5 +- .../src/Distribution/Client/CmdTest.hs | 10 + .../src/Distribution/Client/CmdUpdate.hs | 22 +- .../src/Distribution/Client/Compat/Base16.hs | 49 + .../src/Distribution/Client/Compat/Orphans.hs | 23 + .../Distribution/Client/Compat/Semaphore.hs | 2 - .../src/Distribution/Client/Compat/Tar.hs | 457 +++ .../src/Distribution/Client/Config.hs | 15 +- .../src/Distribution/Client/Configure.hs | 2 - .../src/Distribution/Client/Dependency.hs | 6 +- .../src/Distribution/Client/Errors.hs | 11 +- .../src/Distribution/Client/FetchUtils.hs | 75 +- .../src/Distribution/Client/FileMonitor.hs | 8 +- .../src/Distribution/Client/GZipUtils.hs | 133 + cabal-install/src/Distribution/Client/Get.hs | 4 +- cabal-install/src/Distribution/Client/Glob.hs | 2 +- .../src/Distribution/Client/GlobalFlags.hs | 49 + .../src/Distribution/Client/Haddock.hs | 2 +- .../src/Distribution/Client/HashValue.hs | 84 +- .../src/Distribution/Client/HttpUtils.hs | 139 +- .../src/Distribution/Client/InLibrary.hs | 51 +- .../src/Distribution/Client/IndexUtils.hs | 58 +- .../Client/IndexUtils/IndexState.hs | 1 + .../Client/IndexUtils/Timestamp.hs | 16 +- .../Distribution/Client/Init/FileCreators.hs | 2 +- .../src/Distribution/Client/Init/Format.hs | 1 + .../Client/Init/NonInteractive/Command.hs | 2 +- .../Client/Init/NonInteractive/Heuristics.hs | 1 + .../src/Distribution/Client/Init/Prompt.hs | 3 +- .../src/Distribution/Client/Init/Types.hs | 4 +- .../src/Distribution/Client/Init/Utils.hs | 4 +- .../src/Distribution/Client/Install.hs | 3 +- .../src/Distribution/Client/InstallPlan.hs | 222 +- .../src/Distribution/Client/InstallSymlink.hs | 2 +- .../src/Distribution/Client/JobControl.hs | 25 + cabal-install/src/Distribution/Client/List.hs | 44 +- cabal-install/src/Distribution/Client/Main.hs | 20 +- .../src/Distribution/Client/Manpage.hs | 16 +- .../src/Distribution/Client/ManpageFlags.hs | 1 + .../src/Distribution/Client/PackageHash.hs | 1 + .../Distribution/Client/ProjectBuilding.hs | 20 +- .../Client/ProjectBuilding/UnpackedPackage.hs | 100 +- .../src/Distribution/Client/ProjectConfig.hs | 19 +- .../Client/ProjectConfig/FieldGrammar.hs | 1 + .../Client/ProjectConfig/Import.hs | 3 +- .../Client/ProjectConfig/Legacy.hs | 6 +- .../Distribution/Client/ProjectConfig/Lens.hs | 1 + .../Client/ProjectConfig/Parsec.hs | 6 +- .../src/Distribution/Client/ProjectFlags.hs | 1 - .../Client/ProjectOrchestration.hs | 2 +- .../Distribution/Client/ProjectPlanOutput.hs | 17 +- .../Distribution/Client/ProjectPlanning.hs | 83 +- .../Client/ProjectPlanning/Machine.hs | 6 +- .../Client/ProjectPlanning/SetupPolicy.hs | 8 +- .../Client/ProjectPlanning/Types.hs | 5 +- .../src/Distribution/Client/RebuildMonad.hs | 2 +- .../src/Distribution/Client/Reconfigure.hs | 5 +- cabal-install/src/Distribution/Client/Run.hs | 4 +- .../src/Distribution/Client/Sandbox.hs | 2 +- .../Client/Sandbox/PackageEnvironment.hs | 2 +- .../src/Distribution/Client/SavedFlags.hs | 2 +- .../src/Distribution/Client/ScriptUtils.hs | 2 +- .../src/Distribution/Client/Security/DNS.hs | 6 + .../src/Distribution/Client/Security/HTTP.hs | 29 + .../src/Distribution/Client/SetupWrapper.hs | 306 +- .../src/Distribution/Client/Signal.hs | 6 +- .../Distribution/Client/SolverInstallPlan.hs | 6 +- .../src/Distribution/Client/SourceFiles.hs | 3 + .../src/Distribution/Client/SrcDist.hs | 14 + .../src/Distribution/Client/Store.hs | 2 +- cabal-install/src/Distribution/Client/Tar.hs | 8 + .../src/Distribution/Client/TargetProblem.hs | 16 +- .../src/Distribution/Client/TargetSelector.hs | 34 +- .../src/Distribution/Client/Targets.hs | 14 +- .../src/Distribution/Client/Types.hs | 2 - .../Client/Types/ConfiguredPackage.hs | 5 +- .../Distribution/Client/Types/ReadyPackage.hs | 5 +- .../Distribution/Client/Types/SourceRepo.hs | 4 +- .../src/Distribution/Client/Upload.hs | 43 + .../src/Distribution/Client/Utils.hs | 62 +- .../src/Distribution/Client/Utils/Json.hs | 1 + .../src/Distribution/Client/Utils/Newtypes.hs | 1 + cabal-install/src/Distribution/Client/VCS.hs | 4 +- .../Distribution/Client/Win32SelfUpgrade.hs | 4 +- .../src/Distribution/Deprecated/ParseUtils.hs | 1 + .../src/Distribution/Deprecated/ReadP.hs | 1 + cabal-install/tests/IntegrationTests2.hs | 4 +- .../Distribution/Client/Configure.hs | 2 +- .../Distribution/Client/FileMonitor.hs | 2 +- .../Distribution/Client/GZipUtils.hs | 134 + .../UnitTests/Distribution/Client/Get.hs | 2 +- .../Distribution/Client/InstallPlan.hs | 19 +- .../Distribution/Client/ProjectConfig.hs | 2 +- .../Distribution/Client/ProjectPlanning.hs | 1 + .../UnitTests/Distribution/Client/Store.hs | 2 +- .../UnitTests/Distribution/Client/Tar.hs | 123 + .../Distribution/Client/UserConfig.hs | 2 +- .../UnitTests/Distribution/Client/VCS.hs | 2 +- cabal-testsuite/main/cabal-tests.hs | 4 +- cabal-testsuite/src/Test/Cabal/Monad.hs | 4 +- cabal-testsuite/src/Test/Cabal/Prelude.hs | 8 +- cabal-testsuite/src/Test/Cabal/Run.hs | 4 +- cabal-testsuite/src/Test/Cabal/Server.hs | 2 +- cabal-testsuite/src/Test/Cabal/Workdir.hs | 3 +- cabal-validate/cabal-validate.cabal | 1 + cabal-validate/src/Cli.hs | 2 +- cabal-validate/src/ProcessUtil.hs | 2 +- cabal.mhs.project | 46 + .../Client/SetupHooks/CallHooksExe.hs | 18 +- .../Client/SetupHooks/CallHooksExe/Errors.hs | 2 +- solver-benchmarks/HackageBenchmark.hs | 4 +- solver-benchmarks/solver-benchmarks.cabal | 1 + templates/SPDX.LicenseExceptionId.template.hs | 47 +- templates/SPDX.LicenseId.template.hs | 60 +- 308 files changed, 11729 insertions(+), 1199 deletions(-) create mode 100644 Cabal-syntax/cbits/mhs_posix.c create mode 100644 Cabal-syntax/cbits/mhs_posix.h create mode 100644 Cabal-syntax/src/Distribution/Compat/Directory.hs create mode 100644 Cabal-syntax/src/Distribution/Compat/Internal/LazyByteString.hs create mode 100644 Cabal-syntax/src/Distribution/Compat/Internal/MhsPosix.hs create mode 100644 Cabal-syntax/src/Distribution/Compat/MhsInstances.hs create mode 100644 Cabal-syntax/src/Distribution/Fields/Lexer.hs create mode 100644 Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs create mode 100644 Cabal-tests/tests/UnitTests/Distribution/Compat/Prelude.hs create mode 100644 Cabal/cbits/mhs_handle.c create mode 100644 Cabal/cbits/mhs_handle.h create mode 100644 Cabal/cbits/mhs_spawn.c create mode 100644 Cabal/cbits/mhs_spawn.h create mode 100644 Cabal/src/Distribution/Compat/Internal/MhsProcess.hs create mode 100644 Cabal/tests/ProcessCaptureTests.hs create mode 100644 cabal-install/cbits/mhs_sha256.c create mode 100644 cabal-install/cbits/mhs_sha256.h create mode 100644 cabal-install/src/Distribution/Client/Compat/Base16.hs create mode 100644 cabal.mhs.project diff --git a/Cabal-hooks/src/Distribution/Simple/SetupHooks.hs b/Cabal-hooks/src/Distribution/Simple/SetupHooks.hs index 683332715a0..f86a79f235a 100644 --- a/Cabal-hooks/src/Distribution/Simple/SetupHooks.hs +++ b/Cabal-hooks/src/Distribution/Simple/SetupHooks.hs @@ -302,7 +302,7 @@ import Distribution.Types.LocalBuildConfig import Distribution.Types.TargetInfo ( TargetInfo(..) ) import Distribution.Utils.Path - ( SymbolicPath, CWD, Pkg, FileOrDir(..) + ( SymbolicPath, CWD, Pkg, FileOrDir(..), Dir , interpretSymbolicPath, makeRelativePathEx , RelativePath, Source, Build , getSymbolicPath, sameDirectory, moduleNameSymbolicPath diff --git a/Cabal-syntax/Cabal-syntax.cabal b/Cabal-syntax/Cabal-syntax.cabal index 1ef3ae0a526..84f879e593d 100644 --- a/Cabal-syntax/Cabal-syntax.cabal +++ b/Cabal-syntax/Cabal-syntax.cabal @@ -18,11 +18,19 @@ build-type: Simple extra-doc-files: README.md ChangeLog.md +extra-source-files: + cbits/mhs_posix.h + source-repository head type: git location: https://github.com/haskell/cabal/ subdir: Cabal-syntax +flag mhs + description: MicroHs build (uses -mhs package variants for array/binary/pretty) + default: False + manual: True + library default-language: GHC2021 -- Disabling ImportQualifiedPost, otherwise fourmolu jumps ahead to apply it everywhere @@ -30,9 +38,7 @@ library hs-source-dirs: src build-depends: - , array >= 0.4.0.1 && < 0.6 , base >= 4.18 && < 5 - , binary >= 0.8.1 && < 0.9 , bytestring >= 0.10.4.0 && < 0.13 , containers >= 0.5.2 && < 0.9 , deepseq >= 1.4 && < 1.7 @@ -40,13 +46,23 @@ library , filepath >= 1.4.301 && < 1.6 , mtl >= 2.1 && < 2.4 , parsec >= 3.1.13.0 && < 3.2 - , pretty >= 1.1.1 && < 1.2 , text >= 2.0.2 && < 2.2 , time >= 1.4.0.1 && < 1.17 -- transformers-0.4.0.0 doesn't have record syntax e.g. for Identity -- See also https://github.com/ekmett/transformers-compat/issues/35 , transformers (>= 0.3 && < 0.4) || (>=0.4.1.0 && <0.7) + if flag(mhs) + build-depends: + array-mhs >= 0.5.8 && < 0.6, + binary-mhs >= 0.8.1 && < 0.9, + pretty-mhs >= 1.1.3.6 && < 1.2 + else + build-depends: + array >= 0.4.0.1 && < 0.6, + binary >= 0.8.1 && < 0.9, + pretty >= 1.1.1 && < 1.2 + ghc-options: -Wall -fno-ignore-asserts @@ -70,9 +86,12 @@ library Distribution.Compat.Binary Distribution.Compat.CharParsing Distribution.Compat.DList + Distribution.Compat.Directory Distribution.Compat.Exception Distribution.Compat.Graph + Distribution.Compat.Internal.LazyByteString Distribution.Compat.Lens + Distribution.Compat.MhsInstances Distribution.Compat.NonEmptySet Distribution.Compat.Parsing Distribution.Compat.Prelude @@ -203,6 +222,17 @@ library Distribution.Version Language.Haskell.Extension + other-modules: + Distribution.Compat.Internal.MhsPosix + + -- C helpers for the MHS (MicroHs) build of Distribution.Compat.Directory. + -- The POSIX bodies are used there; other platforms compile the stubs. + -- The matching header (cbits/mhs_posix.h, shipped in + -- extra-source-files) carries the prototypes (with platform types + -- from the standard headers) for MicroHs-generated FFI call sites. + c-sources: cbits/mhs_posix.c + include-dirs: cbits + other-extensions: BangPatterns CPP diff --git a/Cabal-syntax/cbits/mhs_posix.c b/Cabal-syntax/cbits/mhs_posix.c new file mode 100644 index 00000000000..fae6829f525 --- /dev/null +++ b/Cabal-syntax/cbits/mhs_posix.c @@ -0,0 +1,194 @@ +/* MHS POSIX file-query helpers for the Cabal-syntax library. + * + * The MHS (MicroHs) build of Cabal-syntax cannot use the @unix@ + * package, and the C @struct stat@ layout is platform specific, so the + * file-kind, modification-time and timestamp queries needed by + * Distribution.Compat.Directory live here in C rather than behind + * Haskell FFI. Plain libc calls (@rename@, @rmdir@, @realpath@, + * @symlink@, @readlink@, @mkdir@, @chmod@) are imported directly from + * Haskell and need no helpers. + * + * The Haskell side (Distribution.Compat.Internal.MhsPosix) only calls + * the three functions declared below. + * + * On non-POSIX platforms (notably Windows) these functions are stubs + * that fail; the MHS port targets POSIX systems. + */ + +#if defined(_WIN32) + +/* Stubs so that the file still compiles where lacks the + * POSIX members used below. */ + +#include + +int mhs_path_kind(const char *path, int follow) +{ + (void) path; (void) follow; + errno = ENOSYS; + return -1; +} + +int mhs_path_mode(const char *path, long *mode) +{ + (void) path; (void) mode; + errno = ENOSYS; + return -1; +} + +int mhs_path_mtime(const char *path, long *sec, long *nsec) +{ + (void) path; (void) sec; (void) nsec; + errno = ENOSYS; + return -1; +} + +int mhs_set_mtime(const char *path, long sec, long nsec) +{ + (void) path; (void) sec; (void) nsec; + errno = ENOSYS; + return -1; +} + +int mhs_create_exclusive(const char *path, int mode) +{ + (void) path; (void) mode; + errno = ENOSYS; + return -1; +} + +#else /* POSIX */ + +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include + +/* Check the header declarations against these definitions in the + * same translation unit. Kept inside the POSIX branch: the header + * needs , which does not exist on Windows (whose stubs + * above are unchanged). */ +#include "mhs_posix.h" + +/* Classify a path: 0 = missing, 1 = regular file, 2 = directory, + * 3 = symbolic link, 4 = anything else, -1 = error (errno set). + * With @follow@ set, symbolic links are followed (like @stat@); + * otherwise the link itself is reported (like @lstat@). A dangling + * link reported with @follow@ set counts as missing, matching the + * behaviour of the @directory@ package queries. + */ +int +mhs_path_kind(const char *path, int follow) +{ + struct stat st; + + if (follow ? stat(path, &st) != 0 : lstat(path, &st) != 0) { + if (errno == ENOENT || errno == ENOTDIR) { + return 0; + } + return -1; + } + if (!follow && S_ISLNK(st.st_mode)) { + return 3; + } + if (S_ISREG(st.st_mode)) { + return 1; + } + if (S_ISDIR(st.st_mode)) { + return 2; + } + return 4; +} + +/* Fetch the raw mode bits of @path@ (following links), as for + * @st_mode@. Returns 0 on success, -1 with errno set. + */ +int +mhs_path_mode(const char *path, long *mode) +{ + struct stat st; + + if (stat(path, &st) != 0) { + return -1; + } + *mode = (long) st.st_mode; + return 0; +} + +/* Fetch the modification time of @path@ (following links) as seconds + * plus nanoseconds. Returns 0 on success, -1 with errno set. + */ +int +mhs_path_mtime(const char *path, long *sec, long *nsec) +{ + struct stat st; + + if (stat(path, &st) != 0) { + return -1; + } +#if defined(__APPLE__) && (!defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)) + *sec = (long) st.st_mtimespec.tv_sec; + *nsec = (long) st.st_mtimespec.tv_nsec; +#elif defined(__APPLE__) + /* Strict POSIX view (this file defines _POSIX_C_SOURCE itself): + * st_mtime plus st_mtimensec. */ + *sec = (long) st.st_mtime; + *nsec = (long) st.st_mtimensec; +#else + *sec = (long) st.st_mtim.tv_sec; + *nsec = (long) st.st_mtim.tv_nsec; +#endif + return 0; +} + +/* Set the modification time of @path@ (following links), leaving the + * access time unchanged where the platform allows. Returns 0 on + * success, -1 with errno set. + */ +int +mhs_set_mtime(const char *path, long sec, long nsec) +{ +#if defined(__linux__) || defined(__APPLE__) + struct timespec ts[2]; + ts[0].tv_sec = 0; + ts[0].tv_nsec = UTIME_OMIT; + ts[1].tv_sec = (time_t) sec; + ts[1].tv_nsec = (long) nsec; + return utimensat(AT_FDCWD, path, ts, 0); +#else + /* No sub-second precision portably here; atime follows mtime. */ + (void) nsec; + { + struct utimbuf tb; + tb.actime = (time_t) sec; + tb.modtime = (time_t) sec; + return utime(path, &tb); + } +#endif +} + +/* Atomically create a regular file, failing if the path already exists + * (O_EXCL also refuses pre-existing symlinks, dangling or otherwise). + * Returns 0 on success, 1 if the path exists, -1 with errno set on + * other errors. + */ +int +mhs_create_exclusive(const char *path, mode_t mode) +{ + int fd = open(path, O_RDWR | O_CREAT | O_EXCL, mode); + if (fd >= 0) { + close(fd); + return 0; + } + if (errno == EEXIST) { + return 1; + } + return -1; +} + +#endif /* _WIN32 */ diff --git a/Cabal-syntax/cbits/mhs_posix.h b/Cabal-syntax/cbits/mhs_posix.h new file mode 100644 index 00000000000..ae25ab9487a --- /dev/null +++ b/Cabal-syntax/cbits/mhs_posix.h @@ -0,0 +1,41 @@ +/* Prototypes for the MicroHs POSIX helpers in mhs_posix.c, + * plus the libc functions used through bare 'foreign import ccall' + * imports (which MicroHs resolves without a C header in scope). + * + * MicroHs emits a call for every 'foreign import ccall' into its + * generated C file, which is compiled as its own translation unit; + * without these prototypes the implicit declarations are rejected + * (and would be unsound for pointer-sized types such as the + * 'realpath' result). + * + * The libc declarations below use the actual platform types + * ('mode_t', 'ssize_t', 'size_t') from the standard headers rather + * than hand-written approximations, so this header never conflicts + * with the system headers on macOS or Linux. Include this header + * via a header-qualified import, e.g. + * foreign import ccall "mhs_posix.h mhs_path_kind" ... + */ +#ifndef MHS_POSIX_H +#define MHS_POSIX_H + +#include /* mkdir, chmod, mode_t */ +#include /* ssize_t, size_t */ +#include /* realpath */ +#include /* rmdir, symlink, readlink */ + +int mhs_path_kind(const char *path, int follow); +int mhs_create_exclusive(const char *path, mode_t mode); +int mhs_path_mode(const char *path, long *mode); +int mhs_path_mtime(const char *path, long *sec, long *nsec); +int mhs_set_mtime(const char *path, long sec, long nsec); + +/* libc functions used through bare foreign imports */ +int rename(const char *oldpath, const char *newpath); +int rmdir(const char *path); +int mkdir(const char *path, mode_t mode); +int chmod(const char *path, mode_t mode); +char *realpath(const char *path, char *resolved); +int symlink(const char *target, const char *linkpath); +ssize_t readlink(const char *path, char *buf, size_t bufsize); + +#endif /* MHS_POSIX_H */ diff --git a/Cabal-syntax/src/Distribution/Compat/Directory.hs b/Cabal-syntax/src/Distribution/Compat/Directory.hs new file mode 100644 index 00000000000..530bcaedbd1 --- /dev/null +++ b/Cabal-syntax/src/Distribution/Compat/Directory.hs @@ -0,0 +1,399 @@ +{-# LANGUAGE CPP #-} + +#if defined(__MHS__) || defined(MHS) +-- | Portability seam for directory operations. +-- +-- Under GHC this module re-exports "System.Directory". +-- Under MHS (MicroHs, which has only a partial @System.Directory@ and +-- no @unix@ or @process@ packages) the missing operations are +-- implemented here: renames, removal, canonicalisation, timestamps, +-- symbolic links and executable lookup are built on the raw POSIX +-- queries in "Distribution.Compat.Internal.MhsPosix" (direct libc FFI +-- for @rename@/@rmdir@/@realpath@/@stat@/@utimes@/@symlink@/@readlink@, +-- plus small C helpers that hide the @struct stat@ layout), while +-- 'findExecutable' is a pure-Haskell search over @PATH@. +-- +-- MicroHs defines @__MHS__@ itself; a manual @-DMHS@ flag is accepted +-- as well. Either macro selects this branch. +module Distribution.Compat.Directory + ( Permissions (..) + , XdgDirectory (..) + , addFileMode + , canonicalizePath + , copyFile + , copyFileWithMetadata + , createFileExclusively + , createPrivateDirectory + , copyPermissions + , createDirectory + , createDirectoryIfMissing + , createDirectoryLink + , createFileLink + , doesDirectoryExist + , doesFileExist + , doesPathExist + , emptyPermissions + , findExecutable + , findExecutables + , getAppUserDataDirectory + , getCurrentDirectory + , getDirectoryContents + , getFileSize + , getHomeDirectory + , getModificationTime + , getPermissions + , getSymbolicLinkTarget + , getTemporaryDirectory + , getXdgDirectory + , listDirectory + , makeAbsolute + , pathIsSymbolicLink + , removeDirectory + , removeDirectoryRecursive + , removeFile + , removePathForcibly + , renameDirectory + , renameFile + , setCurrentDirectory + , setModificationTime + , setPermissions + , withCurrentDirectory + ) where + +import Control.Exception (catch) +import Control.Monad (filterM, unless) +import Data.Bits ((.&.), (.|.), complement) +import Data.Maybe (listToMaybe) +import Data.Time.Clock (UTCTime) +import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) +import Distribution.Compat.Internal.MhsPosix + ( MhsPathKind (..) + , mhsChmod + , mhsCreateExclusive + , mhsMakeDir + , mhsModTime + , mhsPathKind + , mhsPathMode + , mhsReadlink + , mhsRealpath + , mhsRemoveDir + , mhsRename + , mhsSetModTime + , mhsSymlink + ) +import System.Directory + ( Permissions (..) + , copyFile + , createDirectory + , emptyPermissions + , getCurrentDirectory + , getDirectoryContents + , getFileSize + , getHomeDirectory + , getTemporaryDirectory + , listDirectory + , removeFile + , setCurrentDirectory + , withCurrentDirectory + ) +import System.Environment (lookupEnv) +import System.FilePath ((), isRelative, normalise, pathSeparator, splitSearchPath, takeDirectory, takeFileName) +import System.IO.Error (IOErrorType (..), alreadyExistsErrorType, doesNotExistErrorType, ioeSetErrorString, mkIOError) + +-- | Swallow any 'IOError', reporting 'False'. Used for existence and +-- permission probes where races with concurrent deletion are benign. +catchFalse :: IO Bool -> IO Bool +catchFalse io = catch io handle + where + handle :: IOError -> IO Bool + handle _ = pure False + +-- | XDG base directory specification. +data XdgDirectory + = XdgData + | XdgConfig + | XdgCache + | XdgState + | XdgRuntime + deriving (Eq, Ord, Show, Read, Enum, Bounded) + +-- | Query the kind of a path, following links. Missing paths and +-- dangling links report 'MhsMissing'. +pathKind :: FilePath -> IO MhsPathKind +pathKind fp = mhsPathKind fp True + +doesFileExist :: FilePath -> IO Bool +doesFileExist fp = catchFalse ((== MhsFile) <$> pathKind fp) + +doesDirectoryExist :: FilePath -> IO Bool +doesDirectoryExist fp = catchFalse ((== MhsDir) <$> pathKind fp) + +doesPathExist :: FilePath -> IO Bool +doesPathExist fp = catchFalse ((/= MhsMissing) <$> pathKind fp) + +pathIsSymbolicLink :: FilePath -> IO Bool +pathIsSymbolicLink fp = catchFalse ((== MhsLink) <$> mhsPathKind fp False) + +renameFile :: FilePath -> FilePath -> IO () +renameFile = mhsRename + +renameDirectory :: FilePath -> FilePath -> IO () +renameDirectory = mhsRename + +removeDirectory :: FilePath -> IO () +removeDirectory = mhsRemoveDir + +-- | Remove a file or directory tree, never following symbolic links: +-- links (including links to directories) are unlinked themselves. +-- Matches 'System.Directory.removeDirectoryRecursive': the top-level +-- target must be a real directory; a top-level symlink (even to a +-- directory) or non-directory raises an 'inappropriateTypeErrorType' +-- error, and a missing path raises 'doesNotExistErrorType'. +removeDirectoryRecursive :: FilePath -> IO () +removeDirectoryRecursive fp = do + kind <- mhsPathKind fp False + case kind of + MhsDir -> do + entries <- listDirectory fp + mapM_ removeEntry entries + mhsRemoveDir fp + MhsLink -> + ioError + ( ioeSetErrorString + (mkIOError InappropriateType "removeDirectoryRecursive" Nothing (Just fp)) + "is a directory symbolic link" + ) + MhsMissing -> + ioError (mkIOError doesNotExistErrorType "removeDirectoryRecursive" Nothing (Just fp)) + _ -> + ioError + ( ioeSetErrorString + (mkIOError InappropriateType "removeDirectoryRecursive" Nothing (Just fp)) + "not a directory" + ) + where + -- Single lstat classification: only real directories are recursed + -- into; everything else (files, symlinks including links to + -- directories, FIFOs, sockets, devices) is unlinked without + -- following. + removeEntry name = do + let sub = fp name + kind <- mhsPathKind sub False + case kind of + MhsDir -> removeDirectoryRecursive sub + _ -> removeFile sub + +-- | Remove a file or directory tree, ignoring missing paths. +-- Anything that is not a directory (files, FIFOs, sockets, devices) +-- is unlinked; symbolic links are unlinked without following them. +-- 'mhsPathKind' reports missing paths as 'MhsMissing' rather than +-- throwing, so only that case is ignored and genuine lstat failures +-- propagate, matching 'System.Directory.removePathForcibly'. +removePathForcibly :: FilePath -> IO () +removePathForcibly fp = do + kind <- mhsPathKind fp False + case kind of + MhsMissing -> pure () + MhsDir -> removeDirectoryRecursive fp + _ -> removeFile fp + +-- | Atomically create a regular file with the given mode bits, +-- failing when the path already exists (existing files, directories +-- and symlinks, dangling or otherwise). Returns 'True' when the file +-- was created. Use the result in a retry loop with fresh names to +-- implement race-free temporary files. +createFileExclusively :: FilePath -> Int -> IO Bool +createFileExclusively = mhsCreateExclusive + +-- | Atomically create a directory with the given mode bits, failing +-- when the path already exists. Returns 'True' when the directory +-- was created. Unlike 'createDirectoryIfMissing', the mode applies +-- atomically at creation time rather than after the fact. +createPrivateDirectory :: FilePath -> Int -> IO Bool +createPrivateDirectory = mhsMakeDir + +createDirectoryIfMissing :: Bool -> FilePath -> IO () +createDirectoryIfMissing False fp = do + created <- mhsMakeDir fp 0o777 + unless created $ do + -- The path already exists: succeed only for directories, matching + -- 'System.Directory' which throws 'already exists' for files. + isDir <- doesDirectoryExist fp + unless isDir $ + ioError (mkIOError alreadyExistsErrorType "createDirectory" Nothing (Just fp)) +createDirectoryIfMissing True fp = + mapM_ (createDirectoryIfMissing False) (rootFirst fp) + where + rootFirst :: FilePath -> [FilePath] + rootFirst p = reverse (p : parents p) + parents :: FilePath -> [FilePath] + parents q = + let d = takeDirectory q + in if d == q then [] else d : parents d + +-- | Resolve a path against the file system, following symbolic links. +-- Missing trailing components are tolerated: the longest existing +-- prefix is resolved and the remainder appended lexically, matching +-- 'System.Directory.canonicalizePath'. +canonicalizePath :: FilePath -> IO FilePath +canonicalizePath fp = do + absPath <- if isRelative fp then ( fp) <$> getCurrentDirectory else pure fp + resolve absPath + where + resolve :: FilePath -> IO FilePath + resolve p = mhsRealpath p `catch` handle p + handle :: FilePath -> IOError -> IO FilePath + handle p _ = + let parent = takeDirectory p + base = takeFileName p + in if parent == p + then pure (normalise p) + else ( base) <$> resolve parent + +makeAbsolute :: FilePath -> IO FilePath +makeAbsolute p + | isRelative p = normalise . ( p) <$> getCurrentDirectory + | otherwise = pure p + +getSymbolicLinkTarget :: FilePath -> IO FilePath +getSymbolicLinkTarget = mhsReadlink + +createFileLink :: FilePath -> FilePath -> IO () +createFileLink = mhsSymlink + +createDirectoryLink :: FilePath -> FilePath -> IO () +createDirectoryLink = mhsSymlink + +getPermissions :: FilePath -> IO Permissions +getPermissions fp = do + -- Only owner bits are reported, matching 'System.Directory' (group + -- and other bits do not count; @fileAccess@ root/group semantics + -- are not reproduced). Like 'System.Directory.getAccessPermissions' + -- (@directory-1.3.10.0@, @System.Directory.Internal.Posix@), only + -- directories can be searchable and only non-directories can be + -- executable: an owner-executable regular file reports + -- 'executable = True, searchable = False', while an + -- owner-executable directory reports the converse. + mode <- mhsPathMode fp + isDir <- (== MhsDir) <$> pathKind fp + let x = mode .&. 0o100 /= 0 + pure + Permissions + { readable = mode .&. 0o400 /= 0 + , writable = mode .&. 0o200 /= 0 + , executable = x && not isDir + , searchable = x && isDir + } + +setPermissions :: FilePath -> Permissions -> IO () +setPermissions = setPermissionsMode + +-- | Helper setting the mode bits for 'setPermissions' and +-- 'copyPermissions'. +setPermissionsMode :: FilePath -> Permissions -> IO () +setPermissionsMode fp p = do + mode <- mhsPathMode fp + -- Like 'System.Directory.setAccessPermissions' + -- (@directory-1.3.10.0@): the owner-execute bit is set when either + -- 'executable' or 'searchable' is requested, regardless of file kind; + -- 'getPermissions' then reports it back gated on 'isDir'. + let execBit = executable p || searchable p + ownBits = + (if readable p then 0o400 else 0) + .|. (if writable p then 0o200 else 0) + .|. (if execBit then 0o100 else 0) + mhsChmod fp ((mode .&. complement 0o700) .|. ownBits) + +copyPermissions :: FilePath -> FilePath -> IO () +copyPermissions src dst = do + -- Transfer the full permission bits (including group/other and + -- set-uid/set-gid/sticky), matching 'System.Directory', which + -- copies the whole mode rather than just the owner bits. + srcMode <- mhsPathMode src + dstMode <- mhsPathMode dst + mhsChmod dst ((dstMode .&. complement 0o7777) .|. (srcMode .&. 0o7777)) + +-- | OR the given permission bits into a path's mode, preserving +-- file-type bits and all other bits. Used to implement the +-- @setFile*@ family where @unix@ is unavailable. +addFileMode :: FilePath -> Int -> IO () +addFileMode fp bits = do + mode <- mhsPathMode fp + mhsChmod fp (mode .|. (bits .&. 0o7777)) + +getModificationTime :: FilePath -> IO UTCTime +getModificationTime fp = do + (sec, nsec) <- mhsModTime fp + pure (posixSecondsToUTCTime (fromIntegral sec + fromIntegral nsec / 1000000000)) + +setModificationTime :: FilePath -> UTCTime -> IO () +setModificationTime fp t = do + let posix = utcTimeToPOSIXSeconds t + sec = floor posix :: Integer + mhsSetModTime fp sec (floor ((posix - fromIntegral sec) * 1000000000)) + +copyFileWithMetadata :: FilePath -> FilePath -> IO () +copyFileWithMetadata src dst = do + copyFile src dst + copyPermissions src dst + getModificationTime src >>= setModificationTime dst + +-- | Is the path an executable regular file? Never throws. +isExecutableFile :: FilePath -> IO Bool +isExecutableFile fp = + catchFalse $ do + kind <- pathKind fp + if kind /= MhsFile + then pure False + else executable <$> getPermissions fp + +-- | Find an executable by name, searching @PATH@. A name containing +-- a path separator is checked directly instead. +findExecutables :: String -> IO [FilePath] +findExecutables name + | pathSeparator `elem` name = do + ok <- isExecutableFile name + pure [name | ok] + | otherwise = do + mpath <- lookupEnv "PATH" + let dirs = maybe [] splitSearchPath mpath + filterM isExecutableFile [dir name | dir <- dirs] + +findExecutable :: String -> IO (Maybe FilePath) +findExecutable name = listToMaybe <$> findExecutables name + +xdgOrHome :: String -> FilePath -> IO FilePath +xdgOrHome var defrel = do + mdir <- lookupEnv var + case mdir of + Just d | not (null d) -> pure d + _ -> ( defrel) <$> getHomeDirectory + +getXdgDirectory :: XdgDirectory -> FilePath -> IO FilePath +getXdgDirectory XdgData app = ( app) <$> xdgOrHome "XDG_DATA_HOME" (".local" "share") +getXdgDirectory XdgConfig app = ( app) <$> xdgOrHome "XDG_CONFIG_HOME" ".config" +getXdgDirectory XdgCache app = ( app) <$> xdgOrHome "XDG_CACHE_HOME" ".cache" +getXdgDirectory XdgState app = ( app) <$> xdgOrHome "XDG_STATE_HOME" (".local" "state") +getXdgDirectory XdgRuntime app = do + mdir <- lookupEnv "XDG_RUNTIME_DIR" + case mdir of + Just d | not (null d) -> pure (d app) + _ -> ioError (userError "getXdgDirectory: XDG_RUNTIME_DIR is not set") + +getAppUserDataDirectory :: FilePath -> IO FilePath +getAppUserDataDirectory app = ( ('.' : app)) <$> getHomeDirectory + +#else + +-- | GHC-only re-export shim for "System.Directory". +-- +-- In-tree code should import this module instead of "System.Directory" +-- directly, so that alternative backends can be provided behind this +-- seam in a later phase. Under GHC this module is exactly +-- "System.Directory". +module Distribution.Compat.Directory + ( module System.Directory + ) where + +import System.Directory +#endif diff --git a/Cabal-syntax/src/Distribution/Compat/Graph.hs b/Cabal-syntax/src/Distribution/Compat/Graph.hs index efbbd1a534b..9c4174cc932 100644 --- a/Cabal-syntax/src/Distribution/Compat/Graph.hs +++ b/Cabal-syntax/src/Distribution/Compat/Graph.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} -- | @@ -91,7 +91,7 @@ import Prelude () import Data.Array ((!)) import Data.Graph (SCC (..)) -import Distribution.Utils.Structured (Structure (..), Structured (..)) +import Distribution.Utils.Structured (Structure (..)) import qualified Data.Array as Array import qualified Data.Foldable as Foldable @@ -101,42 +101,45 @@ import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.Tree as Tree --- | A graph of nodes @a@. The nodes are expected to have instance --- of class 'IsNode'. -data Graph a = Graph - { graphMap :: !(Map (Key a) a) +-- | A graph of nodes @a@ keyed by @k@. The nodes are expected to have +-- instance of class 'IsNode'. +data Graph k a = Graph + { graphMap :: !(Map k a) , -- Lazily cached graph representation graphForward :: G.Graph , graphAdjoint :: G.Graph , graphVertexToNode :: G.Vertex -> a - , graphKeyToVertex :: Key a -> Maybe G.Vertex - , graphBroken :: [(a, NonEmpty (Key a))] + , graphKeyToVertex :: k -> Maybe G.Vertex + , graphBroken :: [(a, NonEmpty k)] } --- NB: Not a Functor! (or Traversable), because you need --- to restrict Key a ~ Key b. We provide our own mapping --- functions. +-- NB: Not a Functor! (or Traversable), because mapping must preserve +-- the key type @k@. We provide our own mapping functions. -- General strategy is most operations are deferred to the -- Map representation. -instance Show a => Show (Graph a) where +instance Show a => Show (Graph k a) where show = show . toList -instance (IsNode a, Read a) => Read (Graph a) where +instance (IsNode k a, Read a) => Read (Graph k a) where readsPrec d s = map (first fromDistinctListTrusted) (readsPrec d s) -instance (IsNode a, Binary a) => Binary (Graph a) where +instance (IsNode k a, Binary a) => Binary (Graph k a) where put x = put (toList x) get = fmap fromDistinctListTrusted get -instance Structured a => Structured (Graph a) where - structure p = Nominal (typeRep p) 0 "Graph" [structure (Proxy :: Proxy a)] +instance (Typeable k, Structured a) => Structured (Graph k a) where + -- NB: the tag uses the TypeRep of @[a]@ rather than @Graph k a@, matching + -- the 'Binary' instance which serialises the graph as @[a]@. The + -- 'Typeable k' constraint is still required for the 'Typeable' + -- superclass of this instance. + structure _ = Nominal (typeRep (Proxy :: Proxy [a])) 0 "Graph" [structure (Proxy :: Proxy a)] -instance (Eq (Key a), Eq a) => Eq (Graph a) where +instance (Eq k, Eq a) => Eq (Graph k a) where g1 == g2 = graphMap g1 == graphMap g2 -instance Foldable.Foldable Graph where +instance Foldable.Foldable (Graph k) where elem x = Foldable.elem x . graphMap fold = Foldable.fold . graphMap foldl f z = Foldable.foldl f z . graphMap @@ -152,7 +155,7 @@ instance Foldable.Foldable Graph where sum = Foldable.sum . graphMap toList = Foldable.toList . graphMap -instance (NFData a, NFData (Key a)) => NFData (Graph a) where +instance (NFData a, NFData k) => NFData (Graph k a) where rnf Graph { graphMap = m @@ -167,15 +170,13 @@ instance (NFData a, NFData (Key a)) => NFData (Graph a) where -- | The 'IsNode' class is used for datatypes which represent directed -- graph nodes. A node of type @a@ is associated with some unique key of --- type @'Key' a@; given a node we can determine its key ('nodeKey') --- and the keys of its neighbors ('nodeNeighbors'). -class Ord (Key a) => IsNode a where - type Key a - nodeKey :: a -> Key a - nodeNeighbors :: a -> [Key a] - -instance (IsNode a, IsNode b, Key a ~ Key b) => IsNode (Either a b) where - type Key (Either a b) = Key a +-- type @k@ (uniquely determined by @a@); given a node we can determine +-- its key ('nodeKey') and the keys of its neighbors ('nodeNeighbors'). +class Ord k => IsNode k a | a -> k where + nodeKey :: a -> k + nodeNeighbors :: a -> [k] + +instance (IsNode k a, IsNode k b) => IsNode k (Either a b) where nodeKey (Left x) = nodeKey x nodeKey (Right x) = nodeKey x nodeNeighbors (Left x) = nodeNeighbors x @@ -192,50 +193,49 @@ nodeValue (N a _ _) = a instance Functor (Node k) where fmap f (N a k ks) = N (f a) k ks -instance Ord k => IsNode (Node k a) where - type Key (Node k a) = k +instance Ord k => IsNode k (Node k a) where nodeKey (N _ k _) = k nodeNeighbors (N _ _ ks) = ks -- TODO: Maybe introduce a typeclass for items which just --- keys (so, Key associated type, and nodeKey method). But +-- have keys (so, the nodeKey method). But -- I didn't need it here, so I didn't introduce it. -- Query -- | /O(1)/. Is the graph empty? -null :: Graph a -> Bool +null :: Graph k a -> Bool null = Map.null . toMap -- | /O(1)/. The number of nodes in the graph. -size :: Graph a -> Int +size :: Graph k a -> Int size = Map.size . toMap -- | /O(log V)/. Check if the key is in the graph. -member :: IsNode a => Key a -> Graph a -> Bool +member :: IsNode k a => k -> Graph k a -> Bool member k g = Map.member k (toMap g) -- | /O(log V)/. Lookup the node at a key in the graph. -lookup :: IsNode a => Key a -> Graph a -> Maybe a +lookup :: IsNode k a => k -> Graph k a -> Maybe a lookup k g = Map.lookup k (toMap g) -- Construction -- | /O(1)/. The empty graph. -empty :: IsNode a => Graph a +empty :: IsNode k a => Graph k a empty = fromMap Map.empty -- | /O(log V)/. Insert a node into a graph. -insert :: IsNode a => a -> Graph a -> Graph a +insert :: IsNode k a => a -> Graph k a -> Graph k a insert !n g = fromMap (Map.insert (nodeKey n) n (toMap g)) -- | /O(log V)/. Delete the node at a key from the graph. -deleteKey :: IsNode a => Key a -> Graph a -> Graph a +deleteKey :: IsNode k a => k -> Graph k a -> Graph k a deleteKey k g = fromMap (Map.delete k (toMap g)) -- | /O(log V)/. Lookup and delete. This function returns the deleted -- value if it existed. -deleteLookup :: IsNode a => Key a -> Graph a -> (Maybe a, Graph a) +deleteLookup :: IsNode k a => k -> Graph k a -> (Maybe a, Graph k a) deleteLookup k g = let (r, m') = Map.updateLookupWithKey (\_ _ -> Nothing) k (toMap g) in (r, fromMap m') @@ -245,19 +245,19 @@ deleteLookup k g = -- | /O(V + V')/. Right-biased union, preferring entries -- from the second map when conflicts occur. -- @'nodeKey' x = 'nodeKey' (f x)@. -unionRight :: IsNode a => Graph a -> Graph a -> Graph a +unionRight :: IsNode k a => Graph k a -> Graph k a -> Graph k a unionRight g g' = fromMap (Map.union (toMap g') (toMap g)) -- | /O(V + V')/. Left-biased union, preferring entries from -- the first map when conflicts occur. -unionLeft :: IsNode a => Graph a -> Graph a -> Graph a +unionLeft :: IsNode k a => Graph k a -> Graph k a -> Graph k a unionLeft = flip unionRight -- Graph-like operations -- | /Ω(V + E)/. Compute the strongly connected components of a graph. -- Requires amortized construction of graph. -stronglyConnComp :: Graph a -> [SCC a] +stronglyConnComp :: Graph k a -> [SCC a] stronglyConnComp g = map decode forest where forest = G.scc (graphForward g) @@ -274,25 +274,25 @@ stronglyConnComp g = map decode forest -- | /Ω(V + E)/. Compute the cycles of a graph. -- Requires amortized construction of graph. -cycles :: Graph a -> [[a]] +cycles :: Graph k a -> [[a]] cycles g = [vs | CyclicSCC vs <- stronglyConnComp g] -- | /O(1)/. Return a list of nodes paired with their broken -- neighbors (i.e., neighbor keys which are not in the graph). -- Requires amortized construction of graph. -broken :: Graph a -> [(a, NonEmpty (Key a))] +broken :: Graph k a -> [(a, NonEmpty k)] broken g = graphBroken g -- | Lookup the immediate neighbors from a key in the graph. -- Requires amortized construction of graph. -neighbors :: Graph a -> Key a -> Maybe [a] +neighbors :: Graph k a -> k -> Maybe [a] neighbors g k = do v <- graphKeyToVertex g k return (map (graphVertexToNode g) (graphForward g ! v)) -- | Lookup the immediate reverse neighbors from a key in the graph. -- Requires amortized construction of graph. -revNeighbors :: Graph a -> Key a -> Maybe [a] +revNeighbors :: Graph k a -> k -> Maybe [a] revNeighbors g k = do v <- graphKeyToVertex g k return (map (graphVertexToNode g) (graphAdjoint g ! v)) @@ -301,7 +301,7 @@ revNeighbors g k = do -- Returns @Nothing@ if one (or more) keys are not present in -- the graph. -- Requires amortized construction of graph. -closure :: Graph a -> [Key a] -> Maybe [a] +closure :: Graph k a -> [k] -> Maybe [a] closure g ks = do vs <- traverse (graphKeyToVertex g) ks return (decodeVertexForest g (G.dfs (graphForward g) vs)) @@ -310,7 +310,7 @@ closure g ks = do -- of keys. Returns @Nothing@ if one (or more) keys are not present in -- the graph. -- Requires amortized construction of graph. -revClosure :: Graph a -> [Key a] -> Maybe [a] +revClosure :: Graph k a -> [k] -> Maybe [a] revClosure g ks = do vs <- traverse (graphKeyToVertex g) ks return (decodeVertexForest g (G.dfs (graphAdjoint g) vs)) @@ -318,17 +318,17 @@ revClosure g ks = do flattenForest :: Tree.Forest a -> [a] flattenForest = concatMap Tree.flatten -decodeVertexForest :: Graph a -> Tree.Forest G.Vertex -> [a] +decodeVertexForest :: Graph k a -> Tree.Forest G.Vertex -> [a] decodeVertexForest g = map (graphVertexToNode g) . flattenForest -- | Topologically sort the nodes of a graph. -- Requires amortized construction of graph. -topSort :: Graph a -> [a] +topSort :: Graph k a -> [a] topSort g = map (graphVertexToNode g) $ G.topSort (graphForward g) -- | Reverse topologically sort the nodes of a graph. -- Requires amortized construction of graph. -revTopSort :: Graph a -> [a] +revTopSort :: Graph k a -> [a] revTopSort g = map (graphVertexToNode g) $ G.topSort (graphAdjoint g) -- Conversions @@ -339,7 +339,7 @@ revTopSort g = map (graphVertexToNode g) $ G.topSort (graphAdjoint g) -- if you can't fulfill this invariant use @'fromList' ('Data.Map.elems' m)@ -- instead. The values of the map are assumed to already -- be in WHNF. -fromMap :: forall a. IsNode a => Map (Key a) a -> Graph a +fromMap :: forall k a. IsNode k a => Map k a -> Graph k a fromMap m = Graph { graphMap = m @@ -353,10 +353,10 @@ fromMap m = NE.groupWith (nodeKey . fst) brokenEdges' } where - brokenEdges' :: [(a, Key a)] + brokenEdges' :: [(a, k)] brokenEdges' = concat brokenEdges - brokenEdges :: [[(a, Key a)]] + brokenEdges :: [[(a, k)]] (brokenEdges, edges) = unzip [ partitionEithers @@ -381,7 +381,7 @@ fromMap m = bounds = (0, Map.size m - 1) -- | /O(V log V)/. Convert a list of nodes (with distinct keys) into a graph. -fromDistinctList :: (IsNode a, Show (Key a)) => [a] -> Graph a +fromDistinctList :: (IsNode k a, Show k) => [a] -> Graph k a fromDistinctList = fromMap . Map.fromListWith (\_ -> duplicateError) @@ -396,34 +396,34 @@ fromDistinctList = -- already known to be distinct — in particular a graph produced by 'toList' -- and round-tripped through the 'Binary'/'Read' instances. It performs no -- duplicate-key check, and so (unlike 'fromDistinctList') does not require --- @Show (Key a)@. -fromDistinctListTrusted :: IsNode a => [a] -> Graph a +-- @Show k@. +fromDistinctListTrusted :: IsNode k a => [a] -> Graph k a fromDistinctListTrusted = fromMap . Map.fromList . map (\n -> n `seq` (nodeKey n, n)) -- Map-like operations -- | /O(V)/. Convert a graph into a list of nodes. -toList :: Graph a -> [a] +toList :: Graph k a -> [a] toList g = Map.elems (toMap g) -- | /O(V)/. Convert a graph into a list of keys. -keys :: Graph a -> [Key a] +keys :: Graph k a -> [k] keys g = Map.keys (toMap g) -- | /O(V)/. Convert a graph into a set of keys. -keysSet :: Graph a -> Set.Set (Key a) +keysSet :: Graph k a -> Set.Set k keysSet g = Map.keysSet (toMap g) -- | /O(1)/. Convert a graph into a map from keys to nodes. -- The resulting map @m@ is guaranteed to have the property that -- @'Prelude.all' (\(k,n) -> k == 'nodeKey' n) ('Data.Map.toList' m)@. -toMap :: Graph a -> Map (Key a) a +toMap :: Graph k a -> Map k a toMap = graphMap -- Graph-like operations -- | /O(1)/. Convert a graph into a 'Data.Graph.Graph'. -- Requires amortized construction of graph. -toGraph :: Graph a -> (G.Graph, G.Vertex -> a, Key a -> Maybe G.Vertex) +toGraph :: Graph k a -> (G.Graph, G.Vertex -> a, k -> Maybe G.Vertex) toGraph g = (graphForward g, graphVertexToNode g, graphKeyToVertex g) diff --git a/Cabal-syntax/src/Distribution/Compat/Internal/LazyByteString.hs b/Cabal-syntax/src/Distribution/Compat/Internal/LazyByteString.hs new file mode 100644 index 00000000000..c0d03cecd4c --- /dev/null +++ b/Cabal-syntax/src/Distribution/Compat/Internal/LazyByteString.hs @@ -0,0 +1,43 @@ +{-# LANGUAGE CPP #-} + +-- | Lazy-'ByteString' file reads that also work under MicroHs. +-- +-- In MicroHs 0.16.12.0, 'Data.ByteString.Lazy.readFile' and +-- 'Data.ByteString.Lazy.hGetContents' read in chunks with +-- 'Data.ByteString.hGetSome', which is unimplemented (@bsUnimp@) and +-- throws @Data.ByteString.hGetSome unimplemented@ at runtime. The +-- strict 'Data.ByteString' operations use @c_readb@, which works on +-- every handle kind, so under MHS the whole file is read strictly +-- and wrapped with 'BSL.fromStrict'. Use these two helpers instead +-- of 'BSL.readFile'/'BSL.hGetContents' in any module reachable from +-- the MHS build. +module Distribution.Compat.Internal.LazyByteString + ( readFileLBS + , hGetContentsLBS + ) where + +#ifdef __MHS__ +import qualified Data.ByteString as BS +#endif +import qualified Data.ByteString.Lazy as BSL +import System.IO (Handle) + +-- | Read a whole file into a lazy 'ByteString', strictly under MHS. +readFileLBS :: FilePath -> IO BSL.ByteString +#ifdef __MHS__ +-- 'BSL.readFile' needs 'hGetSome', which MicroHs does not implement. +readFileLBS f = BSL.fromStrict <$> BS.readFile f +#else +readFileLBS = BSL.readFile +#endif + +-- | Read a handle's remaining contents into a lazy 'ByteString', +-- strictly under MHS. +hGetContentsLBS :: Handle -> IO BSL.ByteString +#ifdef __MHS__ +-- 'BSL.hGetContents' needs 'hGetSome', which MicroHs does not +-- implement. +hGetContentsLBS h = BSL.fromStrict <$> BS.hGetContents h +#else +hGetContentsLBS = BSL.hGetContents +#endif diff --git a/Cabal-syntax/src/Distribution/Compat/Internal/MhsPosix.hs b/Cabal-syntax/src/Distribution/Compat/Internal/MhsPosix.hs new file mode 100644 index 00000000000..a8316610f49 --- /dev/null +++ b/Cabal-syntax/src/Distribution/Compat/Internal/MhsPosix.hs @@ -0,0 +1,324 @@ +{-# LANGUAGE CPP #-} + +-- | Low-level POSIX file queries for the MHS (MicroHs) build. +-- +-- Under GHC this module reimplements the same interface on top of +-- "System.Directory" (plus "Data.Time" for timestamps), so the GHC +-- build behaves exactly as before. Under MHS the operations are +-- implemented with direct libc FFI ("rename", "rmdir", "realpath", +-- "symlink", "readlink", "mkdir", "chmod") plus the small C helpers +-- in @cbits/mhs_posix.c@ that hide the platform-specific +-- @struct stat@ layout. +-- +-- This module is shared plumbing for "Distribution.Compat.Directory"; +-- it is not part of the public API. +module Distribution.Compat.Internal.MhsPosix + ( MhsPathKind (..) + , mhsPathKind + , mhsPathMode + , mhsChmod + , mhsRename + , mhsRemoveDir + , mhsMakeDir + , mhsCreateExclusive + , mhsRealpath + , mhsSymlink + , mhsReadlink + , mhsModTime + , mhsSetModTime + ) where + +#if defined(__MHS__) || defined(MHS) + +import Foreign.C.Error (eEXIST, getErrno, throwErrnoIfMinus1_, throwErrnoIfNull, throwErrnoPath) +import Foreign.C.String (CString, peekCAString, peekCAStringLen, withCAString) +import Foreign.C.Types (CChar, CInt, CLong, CULong) +import Foreign.Marshal.Alloc (alloca, allocaBytes, free) +import Foreign.Ptr (Ptr, nullPtr) +import Foreign.Storable (peek) + +-- | Classification of a path, see @mhs_path_kind@ in @cbits/mhs_posix.c@. +data MhsPathKind + = MhsMissing + | MhsFile + | MhsDir + | MhsLink + | MhsOther + deriving (Eq, Ord, Show) + +foreign import ccall "mhs_posix.h mhs_path_kind" c_path_kind + :: CString -> CInt -> IO CInt +foreign import ccall "mhs_posix.h mhs_path_mode" c_path_mode + :: CString -> Ptr CLong -> IO CInt +foreign import ccall "mhs_posix.h mhs_path_mtime" c_path_mtime + :: CString -> Ptr CLong -> Ptr CLong -> IO CInt +foreign import ccall "mhs_posix.h mhs_set_mtime" c_set_mtime + :: CString -> CLong -> CLong -> IO CInt +foreign import ccall "mhs_posix.h rename" c_rename + :: CString -> CString -> IO CInt +foreign import ccall "mhs_posix.h rmdir" c_rmdir + :: CString -> IO CInt +foreign import ccall "mhs_posix.h mkdir" c_mkdir + :: CString -> CInt -> IO CInt +foreign import ccall "mhs_posix.h mhs_create_exclusive" c_createExclusive + :: CString -> CInt -> IO CInt +foreign import ccall "mhs_posix.h chmod" c_chmod + :: CString -> CInt -> IO CInt +foreign import ccall "mhs_posix.h realpath" c_realpath + :: CString -> Ptr CChar -> IO CString +foreign import ccall "mhs_posix.h symlink" c_symlink + :: CString -> CString -> IO CInt +foreign import ccall "mhs_posix.h readlink" c_readlink + :: CString -> Ptr CChar -> CULong -> IO CLong + +-- | Classify a path. When the second argument is 'True', symbolic +-- links are followed (like @stat@); otherwise the link itself is +-- reported (like @lstat@). Missing paths report 'MhsMissing' rather +-- than throwing; other errors throw. +mhsPathKind :: FilePath -> Bool -> IO MhsPathKind +mhsPathKind fp follow = + withCAString fp $ \cfp -> do + r <- c_path_kind cfp (if follow then 1 else 0) + case r of + 0 -> pure MhsMissing + 1 -> pure MhsFile + 2 -> pure MhsDir + 3 -> pure MhsLink + _ -> + if r > 0 + then pure MhsOther + else throwErrnoPath "mhsPathKind" fp + +-- | Raw permission bits of a path (following links), as for @st_mode@. +-- Throws when the path does not exist. +mhsPathMode :: FilePath -> IO Int +mhsPathMode fp = + withCAString fp $ \cfp -> + alloca $ \pmode -> do + throwErrnoIfMinus1_ "mhsPathMode" (c_path_mode cfp pmode) + fromIntegral <$> peek pmode + +-- | Set raw permission bits, as for @chmod@. +mhsChmod :: FilePath -> Int -> IO () +mhsChmod fp mode = + withCAString fp $ \cfp -> + throwErrnoIfMinus1_ "mhsChmod" (c_chmod cfp (fromIntegral mode)) + +-- | Rename a file or directory, as for @rename@. +mhsRename :: FilePath -> FilePath -> IO () +mhsRename old new = + withCAString old $ \cold -> + withCAString new $ \cnew -> + throwErrnoIfMinus1_ "mhsRename" (c_rename cold cnew) + +-- | Remove an empty directory, as for @rmdir@. +mhsRemoveDir :: FilePath -> IO () +mhsRemoveDir fp = + withCAString fp $ \cfp -> + throwErrnoIfMinus1_ "mhsRemoveDir" (c_rmdir cfp) + +-- | Create a directory with the given mode, as for @mkdir@. +-- Returns 'True' when the directory was created and 'False' when it +-- already existed; other errors throw. +mhsMakeDir :: FilePath -> Int -> IO Bool +mhsMakeDir fp mode = + withCAString fp $ \cfp -> do + r <- c_mkdir cfp (fromIntegral mode) + if r == 0 + then pure True + else do + e <- getErrno + if e == eEXIST + then pure False + else throwErrnoPath "mhsMakeDir" fp + +-- | Atomically create a regular file, failing when the path already +-- exists (including dangling symlinks, which @O_EXCL@ does not +-- follow). Returns 'True' when the file was created and 'False' when +-- it already exists; other errors throw. +mhsCreateExclusive :: FilePath -> Int -> IO Bool +mhsCreateExclusive fp mode = + withCAString fp $ \cfp -> do + r <- c_createExclusive cfp (fromIntegral mode) + if r == 0 + then pure True + else + if r == 1 + then pure False + else throwErrnoPath "mhsCreateExclusive" fp + +-- | Canonicalise a path, resolving symbolic links, as for +-- @realpath@. Throws when the path does not exist. +mhsRealpath :: FilePath -> IO FilePath +mhsRealpath fp = + withCAString fp $ \cfp -> do + rp <- throwErrnoIfNull "mhsRealpath" (c_realpath cfp nullPtr) + s <- peekCAString rp + free rp + pure s + +-- | Create a symbolic link, as for @symlink@. +mhsSymlink :: FilePath -> FilePath -> IO () +mhsSymlink target link = + withCAString target $ \ctarget -> + withCAString link $ \clink -> + throwErrnoIfMinus1_ "mhsSymlink" (c_symlink ctarget clink) + +-- | Read a symbolic link, as for @readlink@. +mhsReadlink :: FilePath -> IO FilePath +mhsReadlink fp = + withCAString fp $ \cfp -> go cfp 256 + where + go :: CString -> Int -> IO FilePath + go cfp size = + allocaBytes size $ \buf -> do + r <- c_readlink cfp buf (fromIntegral size) + if r < 0 + then throwErrnoPath "mhsReadlink" fp + else + if fromIntegral r < size + then peekCAStringLen (buf, fromIntegral r) + else go cfp (size * 2) + +-- | Modification time of a path (following links) as seconds plus +-- nanoseconds since the epoch. Throws when the path does not exist. +mhsModTime :: FilePath -> IO (Integer, Int) +mhsModTime fp = + withCAString fp $ \cfp -> + alloca $ \psec -> + alloca $ \pnsec -> do + throwErrnoIfMinus1_ "mhsModTime" (c_path_mtime cfp psec pnsec) + sec <- peek psec + nsec <- peek pnsec + pure (toInteger sec, fromIntegral nsec) + +-- | Set the modification time of a path (following links) from seconds +-- plus nanoseconds since the epoch. +mhsSetModTime :: FilePath -> Integer -> Int -> IO () +mhsSetModTime fp sec nsec = + withCAString fp $ \cfp -> + throwErrnoIfMinus1_ "mhsSetModTime" (c_set_mtime cfp (fromInteger sec) (fromIntegral nsec)) + +#else + +-- GHC fallback: reimplement the same interface on top of +-- "System.Directory" and "Data.Time". This branch only runs under +-- GHC ("Distribution.Compat.Directory" keeps calling "System.Directory" +-- directly there), so it is a safety net for direct users of this +-- module rather than behaviour-critical code. +import Data.Bits ((.&.), (.|.)) +import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) +import System.IO (writeFile) +import System.IO.Error (catchIOError, isAlreadyExistsError) +import System.Directory + ( Permissions (..) + , canonicalizePath + , createDirectory + , createFileLink + , doesDirectoryExist + , doesFileExist + , getModificationTime + , getPermissions + , getSymbolicLinkTarget + , pathIsSymbolicLink + , removeDirectory + , renameFile + , setModificationTime + , setPermissions + ) + +-- | Classification of a path. +data MhsPathKind + = MhsMissing + | MhsFile + | MhsDir + | MhsLink + | MhsOther + deriving (Eq, Ord, Show) + +-- | Classify a path, following links when asked. +mhsPathKind :: FilePath -> Bool -> IO MhsPathKind +mhsPathKind fp follow = do + isLink <- if follow then pure False else pathIsSymbolicLink fp + if isLink + then pure MhsLink + else do + isFile <- doesFileExist fp + if isFile + then pure MhsFile + else do + isDir <- doesDirectoryExist fp + pure (if isDir then MhsDir else MhsMissing) + +-- | Approximate raw permission bits from 'getPermissions'. +mhsPathMode :: FilePath -> IO Int +mhsPathMode fp = do + p <- getPermissions fp + pure $ + (if readable p then 0o444 else 0) + .|. (if writable p then 0o222 else 0) + .|. (if executable p then 0o111 else 0) + +-- | Set permission bits (owner bits only, as for 'setPermissions'). +mhsChmod :: FilePath -> Int -> IO () +mhsChmod fp mode = do + p <- getPermissions fp + setPermissions + fp + p + { readable = mode .&. 0o444 /= 0 + , writable = mode .&. 0o222 /= 0 + , executable = mode .&. 0o111 /= 0 + } + +-- | Rename a file or directory. +mhsRename :: FilePath -> FilePath -> IO () +mhsRename = renameFile + +-- | Remove an empty directory. +mhsRemoveDir :: FilePath -> IO () +mhsRemoveDir = removeDirectory + +-- | Create a directory; 'False' when it already existed. +mhsMakeDir :: FilePath -> Int -> IO Bool +mhsMakeDir fp _mode = + catchIOError + (createDirectory fp >> pure True) + (\e -> if isAlreadyExistsError e then pure False else ioError e) + +-- | Best-effort 'mhsCreateExclusive' for GHC builds: GHC's own file +-- opening has no 'O_EXCL' mode without @unix@, and this helper is only +-- used by the MHS-only creation paths. The existence check plus the +-- caller's retry loop close the practical collision window. +mhsCreateExclusive :: FilePath -> Int -> IO Bool +mhsCreateExclusive fp _mode = do + exists <- doesFileExist fp + if exists + then pure False + else writeFile fp "" >> pure True + +-- | Canonicalise a path, resolving symbolic links. +mhsRealpath :: FilePath -> IO FilePath +mhsRealpath = canonicalizePath + +-- | Create a symbolic link. +mhsSymlink :: FilePath -> FilePath -> IO () +mhsSymlink = createFileLink + +-- | Read a symbolic link. +mhsReadlink :: FilePath -> IO FilePath +mhsReadlink = getSymbolicLinkTarget + +-- | Modification time as seconds plus nanoseconds since the epoch. +mhsModTime :: FilePath -> IO (Integer, Int) +mhsModTime fp = do + t <- utcTimeToPOSIXSeconds <$> getModificationTime fp + let s = floor t :: Integer + pure (s, floor ((t - fromIntegral s) * 1000000000)) + +-- | Set the modification time from seconds plus nanoseconds. +mhsSetModTime :: FilePath -> Integer -> Int -> IO () +mhsSetModTime fp sec nsec = + setModificationTime fp (posixSecondsToUTCTime (fromIntegral sec + fromIntegral nsec / 1000000000)) + +#endif diff --git a/Cabal-syntax/src/Distribution/Compat/MhsInstances.hs b/Cabal-syntax/src/Distribution/Compat/MhsInstances.hs new file mode 100644 index 00000000000..acf1afcef7f --- /dev/null +++ b/Cabal-syntax/src/Distribution/Compat/MhsInstances.hs @@ -0,0 +1,32 @@ +{-# LANGUAGE CPP #-} + +-- | MicroHs compatibility instances. +-- +-- MicroHs\'s @containers@ package gates its 'Data.Data' instances +-- behind @__GLASGOW_HASKELL__@, so they are missing under MicroHs. +-- This module provides those instances as orphans, for use behind +-- @__MHS__@ only (GHC already gets them from @containers@ itself). +-- +-- The method bodies are intentionally absent: MicroHs accepts empty +-- instance bodies, and nothing in this repository calls 'Data' +-- methods on these types. The instances exist only so that +-- @deriving@ clauses and explicit @instance@ contexts resolve. +module Distribution.Compat.MhsInstances + ( + ) where + +#ifdef __MHS__ +import Data.Data (Data) +import qualified Data.ByteString as BS +import qualified Data.Map as Map +import qualified Data.Set as Set +import qualified Data.Text as T + +instance (Data a, Ord a) => Data (Set.Set a) + +instance (Data k, Data v, Ord k) => Data (Map.Map k v) + +instance Data T.Text + +instance Data BS.ByteString +#endif diff --git a/Cabal-syntax/src/Distribution/Compat/NonEmptySet.hs b/Cabal-syntax/src/Distribution/Compat/NonEmptySet.hs index ca640d73f05..0bb0ead2324 100644 --- a/Cabal-syntax/src/Distribution/Compat/NonEmptySet.hs +++ b/Cabal-syntax/src/Distribution/Compat/NonEmptySet.hs @@ -1,3 +1,6 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE StandaloneDeriving #-} + module Distribution.Compat.NonEmptySet ( NonEmptySet @@ -35,12 +38,26 @@ import Data.Semigroup (Semigroup (..)) import qualified Data.Foldable as F import qualified Data.Set as Set +#ifdef __MHS__ +import Distribution.Compat.MhsInstances () +#endif + import Distribution.Compat.Binary (Binary (..)) import Distribution.Utils.Structured -- | @since 3.4.0.0 newtype NonEmptySet a = NES (Set.Set a) - deriving (Eq, Ord, Data, Read) + deriving (Eq, Ord, Read +#ifndef __MHS__ + , Data +#endif + ) + +#ifdef __MHS__ +-- MicroHs cannot derive 'Data' for parameterised types (it drops the +-- required context), so the instance is spelled out explicitly. +deriving instance (Data a, Ord a) => Data (NonEmptySet a) +#endif ------------------------------------------------------------------------------- -- Instances diff --git a/Cabal-syntax/src/Distribution/Compat/Prelude.hs b/Cabal-syntax/src/Distribution/Compat/Prelude.hs index 7800c0d70a0..d705dce88c2 100644 --- a/Cabal-syntax/src/Distribution/Compat/Prelude.hs +++ b/Cabal-syntax/src/Distribution/Compat/Prelude.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE Trustworthy #-} -- | This module does two things: @@ -18,11 +19,15 @@ module Distribution.Compat.Prelude , TypeRep , typeRep , Data +#ifdef __MHS__ + , Generic (..) +#else , Generic +#endif , Generically (..) , NFData (..) , Binary (..) - , Structured + , Structured (..) , Alternative (..) , MonadPlus (..) , IsString (..) @@ -38,6 +43,10 @@ module Distribution.Compat.Prelude -- * Data.Either , partitionEithers +#ifdef __MHS__ + , lefts + , rights +#endif -- * Data.Maybe , catMaybes @@ -72,23 +81,36 @@ module Distribution.Compat.Prelude , init -- * Data.Foldable - , Foldable + -- NOTE: only the class methods are re-exported here (as plain + -- functions), never the class itself. MicroHs merges a re-exported + -- class method with a same-named local definition ('foldr1' + -- and 'foldl1' below) into an ambiguous export. Modules needing + -- the class (instances, deriving) import it directly. 'fold' is + -- deliberately not re-exported: several modules define a local + -- 'fold' ('Distribution.Utils.Progress', 'VersionRange', 'Graph'), + -- and every use of 'Data.Foldable.fold' imports it directly. , foldMap + , foldMap' , foldr + , foldr' + , foldl + , foldl' + , toList , null , length + , elem + , maximum + , minimum + , sum + , product , find - , foldl' - , traverse_ , for_ + , traverse_ , any , all - , toList -- * Data.Traversable - , Traversable - , traverse - , sequenceA + , Traversable (..) , for -- * Data.Function @@ -178,6 +200,21 @@ module Distribution.Compat.Prelude {- FOURMOLU_DISABLE -} import Prelude as BasePrelude hiding ( mapM, mapM_, sequence, any, all, head, tail, last, init + -- 'foldr' is also imported from 'Data.Foldable' below; hiding + -- Prelude's copy keeps the export list unambiguous. (Under GHC both + -- names denote the same entity, so this changes nothing there.) + , foldr + -- Same for the other list functions that 'Data.Foldable' + -- re-exports generically below (all identical to Prelude's + -- since the Foldable-Traversable Proposal). + , foldl + , length + , null + , elem + , maximum + , minimum + , product + , sum -- partial functions , read , foldr1, foldl1 @@ -187,23 +224,35 @@ import Prelude as BasePrelude hiding , Foldable(..) ) {- FOURMOLU_ENABLE -} -import Data.Foldable as BasePrelude (elem, foldl, maximum, minimum, product, sum) - -- AMP import Data.Foldable - ( Foldable (foldMap, foldr, toList) + -- NOTE: only the class methods are re-exported here (as plain + -- functions), never the class itself. MicroHs merges a re-exported + -- class method with a same-named local definition ('foldr1' + -- and 'foldl1' below) into an ambiguous export. Modules needing + -- the class (instances, deriving) import it directly. + ( foldMap + , foldMap' + , foldr + , foldr' + , foldl + , foldl' + , toList + , null + , length + , elem + , maximum + , minimum + , sum + , product , all , any , find - , foldl' , for_ - , length - , null , traverse_ ) -import Data.Traversable (Traversable (sequenceA, traverse), for) +import Data.Traversable (Traversable (..), for) -import qualified Data.Foldable1 -- Extra exports import Control.Applicative (Alternative (..), Const (..)) @@ -214,6 +263,13 @@ import Control.Monad (MonadPlus (..), ap, filterM, foldM, guard, join, liftM, li import Data.Char (chr, isAlpha, isAlphaNum, isDigit, isSpace, isUpper, ord, toLower, toUpper) import Data.Data (Data) import Data.Either (partitionEithers) +#ifdef __MHS__ +lefts :: [Either a b] -> [a] +lefts xs = [x | Left x <- xs] + +rights :: [Either a b] -> [b] +rights xs = [x | Right x <- xs] +#endif import Data.Function (on) import Data.Functor.Identity (Identity (..)) import Data.Int (Int16, Int32, Int64, Int8) @@ -229,7 +285,7 @@ import Data.Typeable (TypeRep, Typeable, typeRep) import Data.Void (Void, absurd, vacuous) import Data.Word (Word, Word16, Word32, Word64, Word8) import Distribution.Compat.Binary (Binary (..)) -import GHC.Generics (Generic, Generically (..)) +import GHC.Generics (Generic (..), Generically (..)) import System.Exit (ExitCode (..), exitFailure, exitSuccess, exitWith) import Text.Read (readMaybe) @@ -237,21 +293,31 @@ import qualified Text.PrettyPrint as Disp import Distribution.Compat.Exception import Distribution.Compat.NonEmptySet (NonEmptySet) -import Distribution.Utils.Structured (Structured) +import Distribution.Utils.Structured (Structured (..)) import qualified Debug.Trace +#ifdef __MHS__ +-- | Re-export the MicroHs compatibility instances (see +-- 'Distribution.Compat.MhsInstances') so that every module importing +-- this 'Prelude' can derive 'Data' over sets and maps. +import Distribution.Compat.MhsInstances () +#endif + -- | New name for 'Text.PrettyPrint.<>' (<<>>) :: Disp.Doc -> Disp.Doc -> Disp.Doc (<<>>) = (Disp.<>) {-# INLINE foldr1 #-} foldr1 :: (a -> a -> a) -> NonEmpty a -> a -foldr1 = Data.Foldable1.foldr1 +foldr1 f (x :| xs) = go x xs + where + go y [] = y + go y (z : zs) = f y (go z zs) {-# INLINE foldl1 #-} foldl1 :: (a -> a -> a) -> NonEmpty a -> a -foldl1 = Data.Foldable1.foldl1 +foldl1 f (x :| xs) = foldl f x xs ------------------------------------------------------------------------------- -- Trace @@ -265,17 +331,38 @@ trace = Debug.Trace.trace {-# DEPRECATED trace "Don't leave me in the code" #-} traceShowId :: Show a => a -> a +#ifdef __MHS__ +-- MicroHs's 'Debug.Trace' has no 'traceShow'. +traceShowId x = Debug.Trace.trace (show x) x +#else traceShowId x = Debug.Trace.traceShow x x +#endif {-# DEPRECATED traceShowId "Don't leave me in the code" #-} traceShow :: Show a => a -> b -> b +#ifdef __MHS__ +traceShow x y = Debug.Trace.trace (show x) y +#else traceShow = Debug.Trace.traceShow +#endif {-# DEPRECATED traceShow "Don't leave me in the code" #-} traceM :: Applicative f => String -> f () +#ifdef __MHS__ +-- MicroHs's 'Debug.Trace.traceM' needs 'Monad', so define the more +-- general 'Applicative' version via 'trace'. +traceM s = trace s (pure ()) +#else traceM = Debug.Trace.traceM +#endif {-# DEPRECATED traceM "Don't leave me in the code" #-} traceShowM :: (Show a, Applicative f) => a -> f () +#ifdef __MHS__ +-- MicroHs's 'Debug.Trace' has no 'traceShowM', and its 'traceM' +-- needs 'Monad', so go through 'trace' directly. +traceShowM x = Debug.Trace.trace (show x) (pure ()) +#else traceShowM = Debug.Trace.traceShowM +#endif {-# DEPRECATED traceShowM "Don't leave me in the code" #-} diff --git a/Cabal-syntax/src/Distribution/Compiler.hs b/Cabal-syntax/src/Distribution/Compiler.hs index 311410c0abb..ef5a45bd4dd 100644 --- a/Cabal-syntax/src/Distribution/Compiler.hs +++ b/Cabal-syntax/src/Distribution/Compiler.hs @@ -42,6 +42,7 @@ module Distribution.Compiler , abiTagString ) where +import Data.Foldable (Foldable) import Distribution.Compat.Prelude import Prelude () diff --git a/Cabal-syntax/src/Distribution/FieldGrammar/FieldDescrs.hs b/Cabal-syntax/src/Distribution/FieldGrammar/FieldDescrs.hs index 1983d0f933a..e6a18434b56 100644 --- a/Cabal-syntax/src/Distribution/FieldGrammar/FieldDescrs.hs +++ b/Cabal-syntax/src/Distribution/FieldGrammar/FieldDescrs.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE UndecidableInstances #-} module Distribution.FieldGrammar.FieldDescrs @@ -31,7 +32,18 @@ data SP s = SP -- | A collection of field parsers and pretty-printers. newtype FieldDescrs s a = F {runF :: Map P.FieldName (SP s)} +#ifndef __MHS__ deriving (Functor) +#endif + +#ifdef __MHS__ +-- MicroHs cannot derive Functor here ('a' is phantom and its deriving +-- machinery demands a 'Functor SP' instance), so spell out the same +-- mapping by hand. Semantics are identical to the derived instance: +-- the map is carried over unchanged. +instance Functor (FieldDescrs s) where + fmap _ (F m) = F m +#endif instance Applicative (FieldDescrs s) where pure _ = F mempty diff --git a/Cabal-syntax/src/Distribution/FieldGrammar/Newtypes.hs b/Cabal-syntax/src/Distribution/FieldGrammar/Newtypes.hs index b99805f1e06..edfd54a8d28 100644 --- a/Cabal-syntax/src/Distribution/FieldGrammar/Newtypes.hs +++ b/Cabal-syntax/src/Distribution/FieldGrammar/Newtypes.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} -- | This module provides @newtype@ wrappers to be used with "Distribution.FieldGrammar". diff --git a/Cabal-syntax/src/Distribution/FieldGrammar/Parsec.hs b/Cabal-syntax/src/Distribution/FieldGrammar/Parsec.hs index dde2f604dc3..eec8394ecd8 100644 --- a/Cabal-syntax/src/Distribution/FieldGrammar/Parsec.hs +++ b/Cabal-syntax/src/Distribution/FieldGrammar/Parsec.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} -- | This module provides a 'FieldGrammarParser', one way to parse @@ -116,7 +117,18 @@ data ParsecFieldGrammar s a = ParsecFG , fieldGrammarKnownPrefixes :: !(Set FieldName) , fieldGrammarParser :: forall src. (CabalSpecVersion -> Fields Position -> ParseResult src a) } +#ifndef __MHS__ deriving (Functor) +#endif + +#ifdef __MHS__ +-- MicroHs cannot derive Functor through the rank-2 'fieldGrammarParser' +-- field, so spell out the same mapping by hand. Semantics are identical +-- to the derived instance: mapped over the parsed result value. +instance Functor (ParsecFieldGrammar s) where + fmap f (ParsecFG known prefixes parser) = + ParsecFG known prefixes (\v fields -> fmap f (parser v fields)) +#endif parseFieldGrammar :: CabalSpecVersion -> Fields Position -> ParsecFieldGrammar s a -> ParseResult src a parseFieldGrammar v fields grammar = do diff --git a/Cabal-syntax/src/Distribution/FieldGrammar/Pretty.hs b/Cabal-syntax/src/Distribution/FieldGrammar/Pretty.hs index 148aaa9fa79..87006234e51 100644 --- a/Cabal-syntax/src/Distribution/FieldGrammar/Pretty.hs +++ b/Cabal-syntax/src/Distribution/FieldGrammar/Pretty.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} module Distribution.FieldGrammar.Pretty ( PrettyFieldGrammar , prettyFieldGrammar @@ -21,7 +22,18 @@ import Distribution.FieldGrammar.Class newtype PrettyFieldGrammar s a = PrettyFG { fieldGrammarPretty :: CabalSpecVersion -> s -> [PrettyField ()] } +#ifndef __MHS__ deriving (Functor) +#endif + +#ifdef __MHS__ +-- MicroHs cannot derive Functor here ('a' is phantom and its deriving +-- machinery refers to an undefined helper), so spell out the same +-- mapping by hand. Semantics are identical to the derived instance: +-- the function field is carried over unchanged. +instance Functor (PrettyFieldGrammar s) where + fmap _ (PrettyFG pp) = PrettyFG pp +#endif instance Applicative (PrettyFieldGrammar s) where pure _ = PrettyFG (\_ _ -> mempty) diff --git a/Cabal-syntax/src/Distribution/Fields/Field.hs b/Cabal-syntax/src/Distribution/Fields/Field.hs index 20906e78202..ed96619d602 100644 --- a/Cabal-syntax/src/Distribution/Fields/Field.hs +++ b/Cabal-syntax/src/Distribution/Fields/Field.hs @@ -28,6 +28,7 @@ module Distribution.Fields.Field import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B import qualified Data.Char as Char +import Data.Foldable (Foldable) import qualified Data.Foldable1 as F1 import Distribution.Compat.Prelude import Distribution.Pretty (showTokenStr) diff --git a/Cabal-syntax/src/Distribution/Fields/Lexer.hs b/Cabal-syntax/src/Distribution/Fields/Lexer.hs new file mode 100644 index 00000000000..097702d7767 --- /dev/null +++ b/Cabal-syntax/src/Distribution/Fields/Lexer.hs @@ -0,0 +1,3165 @@ +-- This file is pregenerated from Distribution.Fields.Lexer +-- (Cabal-syntax/src/Distribution/Fields/Lexer.x) WITHOUT the alex -g flag, +-- for compilers that cannot parse GHC-specific extensions (mhs). +-- Do not edit it directly; regenerate with: +-- alex src/Distribution/Fields/Lexer.x -o src/Distribution/Fields/Lexer.hs +-- (run from the Cabal-syntax directory, with the alex version pinned in +-- Cabal-syntax.cabal build-tool-depends; alex 3.5.4.2 reproduces the +-- build-tree GHC -g output byte-for-byte). +{- FOURMOLU_DISABLE -} +{-# OPTIONS_GHC -fno-warn-missing-signatures #-} +{-# OPTIONS_GHC -fno-warn-tabs #-} +{-# OPTIONS_GHC -fno-warn-unused-binds #-} +{-# OPTIONS_GHC -fno-warn-unused-imports #-} +{-# LANGUAGE CPP #-} +{-# LINE 1 "src/Distribution/Fields/Lexer.x" #-} +----------------------------------------------------------------------------- +-- | +-- Module : Distribution.Fields.Lexer +-- License : BSD3 +-- +-- Maintainer : cabal-devel@haskell.org +-- Portability : portable +-- +-- Lexer for the cabal files. +{-# LANGUAGE CPP #-} +{-# LANGUAGE BangPatterns #-} +#ifdef CABAL_PARSEC_DEBUG +{-# LANGUAGE PatternGuards #-} +#endif +{-# OPTIONS_GHC -fno-warn-unused-imports #-} +module Distribution.Fields.Lexer + (ltest, lexToken, Token(..), LToken(..) + ,bol_section, in_section, in_field_layout, in_field_braces + ,mkLexState) where + +import Prelude () +import qualified Prelude +import Distribution.Compat.Prelude + +import Distribution.Fields.LexerMonad +import Distribution.Parsec.Position (Position (..), incPos, retPos) +import Data.ByteString (ByteString) +import qualified Data.ByteString as B +import qualified Data.ByteString.Char8 as B.Char8 +import qualified Data.Word as Word + +#ifdef CABAL_PARSEC_DEBUG +import Debug.Trace +import qualified Data.Vector as V +import qualified Data.Text as T +import qualified Data.Text.Encoding as T +import qualified Data.Text.Encoding.Error as T +#endif +#include "ghcconfig.h" +import qualified Data.Array +import qualified Data.Char +alex_tab_size :: Int +alex_tab_size = 8 +alex_base :: Data.Array.Array Int Int +alex_base = Data.Array.listArray (0 :: Int, 48) + [ -238 + , -7 + , -5 + , 1 + , 47 + , 80 + , 208 + , 0 + , 336 + , 372 + , 0 + , 0 + , 0 + , 0 + , -3 + , 0 + , 3 + , 9 + , 129 + , -1 + , 0 + , 10 + , 499 + , 0 + , 0 + , 5 + , 0 + , 531 + , -170 + , -140 + , -139 + , 248 + , 250 + , 0 + , -169 + , 0 + , 13 + , 566 + , -21 + , 264 + , -134 + , 0 + , 0 + , 106 + , 649 + , 694 + , 822 + , 950 + , 986 + ] + +alex_table :: Data.Array.Array Int Int +alex_table = Data.Array.listArray (0 :: Int, 1241) + [ 0 + , 28 + , 32 + , 35 + , 2 + , 35 + , 36 + , 15 + , 36 + , 20 + , 3 + , 35 + , 16 + , 35 + , 36 + , 26 + , 36 + , 34 + , 17 + , 21 + , 16 + , 31 + , 33 + , 35 + , 37 + , 32 + , 39 + , 2 + , 0 + , 0 + , 0 + , 0 + , 0 + , 3 + , 0 + , 16 + , 0 + , 0 + , 38 + , 0 + , 38 + , 17 + , 21 + , 0 + , 0 + , 0 + , 38 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 21 + , 26 + , -1 + , -1 + , 25 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 21 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 17 + , 20 + , -1 + , -1 + , 19 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 17 + , 0 + , 0 + , 43 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 41 + , 0 + , 42 + , 0 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 43 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 23 + , 0 + , 24 + , 0 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 30 + , 0 + , 29 + , 0 + , 0 + , 0 + , 0 + , 0 + , 40 + , 0 + , 29 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 43 + , 15 + , -1 + , -1 + , 14 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 43 + , 9 + , 27 + , 9 + , 9 + , 9 + , 9 + , 0 + , 10 + , 10 + , 9 + , 9 + , 9 + , 46 + , 8 + , 9 + , -1 + , 31 + , 35 + , 32 + , 35 + , 36 + , 0 + , 36 + , 0 + , 0 + , 11 + , 0 + , 9 + , 9 + , 9 + , 9 + , 9 + , 39 + , 35 + , 0 + , 0 + , 36 + , 0 + , 0 + , 31 + , 0 + , 32 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 38 + , 39 + , 0 + , 0 + , 10 + , 9 + , 10 + , 9 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 12 + , 9 + , 13 + , 9 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 9 + , -1 + , 9 + , 9 + , 9 + , 9 + , 0 + , -1 + , -1 + , 9 + , 9 + , 9 + , 8 + , 8 + , 9 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 0 + , 9 + , 9 + , 9 + , 9 + , 9 + , 0 + , 0 + , 0 + , 0 + , 9 + , 0 + , 9 + , 9 + , 9 + , 9 + , 0 + , 0 + , 0 + , 9 + , 9 + , 9 + , 9 + , 9 + , 9 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 9 + , -1 + , 9 + , 0 + , 9 + , 9 + , 9 + , 9 + , 9 + , 0 + , 0 + , 0 + , 0 + , 0 + , 30 + , 0 + , 30 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 40 + , -1 + , 9 + , -1 + , 9 + , -1 + , 9 + , 0 + , 9 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 9 + , 0 + , 9 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , 7 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 48 + , -1 + , 0 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 9 + , -1 + , 9 + , 9 + , 9 + , 9 + , 0 + , -1 + , -1 + , 9 + , 9 + , 9 + , 44 + , 8 + , 9 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 0 + , 9 + , 9 + , 9 + , 9 + , 9 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 9 + , -1 + , 9 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 9 + , -1 + , 9 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , 7 + , 0 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 0 + , 47 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 48 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 48 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , -1 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + ] + +alex_check :: Data.Array.Array Int Int +alex_check = Data.Array.listArray (0 :: Int, 1241) + [ -1 + , 239 + , 9 + , 10 + , 9 + , 10 + , 13 + , 10 + , 13 + , 10 + , 9 + , 10 + , 9 + , 10 + , 13 + , 10 + , 13 + , 187 + , 9 + , 9 + , 160 + , 160 + , 191 + , 10 + , 45 + , 32 + , 160 + , 32 + , -1 + , -1 + , -1 + , -1 + , -1 + , 32 + , -1 + , 32 + , -1 + , -1 + , 45 + , -1 + , 45 + , 32 + , 32 + , -1 + , -1 + , -1 + , 45 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , 32 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , 32 + , -1 + , -1 + , 9 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 123 + , -1 + , 125 + , -1 + , -1 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 32 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 123 + , -1 + , 125 + , -1 + , 127 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 194 + , -1 + , 194 + , -1 + , -1 + , -1 + , -1 + , -1 + , 194 + , -1 + , 194 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 127 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , 32 + , 33 + , 34 + , 35 + , 36 + , 37 + , 38 + , -1 + , 40 + , 41 + , 42 + , 43 + , 44 + , 45 + , 46 + , 47 + , 127 + , 9 + , 10 + , 9 + , 10 + , 13 + , -1 + , 13 + , -1 + , -1 + , 58 + , -1 + , 60 + , 61 + , 62 + , 63 + , 64 + , 9 + , 10 + , -1 + , -1 + , 13 + , -1 + , -1 + , 32 + , -1 + , 32 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 45 + , 32 + , -1 + , -1 + , 91 + , 92 + , 93 + , 94 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 123 + , 124 + , 125 + , 126 + , 127 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , 32 + , 33 + , 34 + , 35 + , 36 + , 37 + , 38 + , -1 + , 40 + , 41 + , 42 + , 43 + , 44 + , 45 + , 46 + , 47 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 58 + , -1 + , 60 + , 61 + , 62 + , 63 + , 64 + , -1 + , -1 + , -1 + , -1 + , 33 + , -1 + , 35 + , 36 + , 37 + , 38 + , -1 + , -1 + , -1 + , 42 + , 43 + , 44 + , 45 + , 46 + , 47 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 91 + , 92 + , 93 + , 94 + , -1 + , 60 + , 61 + , 62 + , 63 + , 64 + , -1 + , -1 + , -1 + , -1 + , -1 + , 194 + , -1 + , 194 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 194 + , 123 + , 124 + , 125 + , 126 + , 127 + , 92 + , -1 + , 94 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 124 + , -1 + , 126 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , -1 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , -1 + , -1 + , 34 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , -1 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 123 + , 92 + , 125 + , -1 + , 127 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 127 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 127 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , 32 + , 33 + , 34 + , 35 + , 36 + , 37 + , 38 + , -1 + , 40 + , 41 + , 42 + , 43 + , 44 + , -1 + , -1 + , 47 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 58 + , -1 + , 60 + , 61 + , 62 + , 63 + , 64 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 127 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 91 + , 92 + , 93 + , 94 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 123 + , 124 + , 125 + , 126 + , 127 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , 32 + , 33 + , 34 + , 35 + , 36 + , 37 + , 38 + , -1 + , 40 + , 41 + , 42 + , 43 + , 44 + , 45 + , 46 + , 47 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 58 + , -1 + , 60 + , 61 + , 62 + , 63 + , 64 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 91 + , 92 + , 93 + , 94 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 123 + , 124 + , 125 + , 126 + , 127 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , -1 + , -1 + , 34 + , -1 + , 0 + , 1 + , 2 + , 3 + , 4 + , 5 + , 6 + , 7 + , 8 + , 9 + , 10 + , 11 + , 12 + , 13 + , 14 + , 15 + , 16 + , 17 + , 18 + , 19 + , 20 + , 21 + , 22 + , 23 + , 24 + , 25 + , 26 + , 27 + , 28 + , 29 + , 30 + , 31 + , -1 + , -1 + , 34 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 92 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 127 + , 92 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 127 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + ] + +alex_deflt :: Data.Array.Array Int Int +alex_deflt = Data.Array.listArray (0 :: Int, 48) + [ -1 + , -1 + , -1 + , -1 + , 22 + , 18 + , 45 + , -1 + , 45 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 18 + , -1 + , -1 + , -1 + , 22 + , -1 + , -1 + , -1 + , -1 + , 27 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 37 + , -1 + , -1 + , -1 + , -1 + , -1 + , -1 + , 44 + , 45 + , 45 + , 27 + , 27 + ] + +alex_accept = Data.Array.listArray (0 :: Int, 48) + [ AlexAcc 30 + , AlexAcc 29 + , AlexAcc 28 + , AlexAcc 27 + , AlexAccNone + , AlexAccNone + , AlexAccNone + , AlexAcc 26 + , AlexAcc 25 + , AlexAcc 24 + , AlexAcc 23 + , AlexAcc 22 + , AlexAcc 21 + , AlexAcc 20 + , AlexAcc 19 + , AlexAcc 18 + , AlexAcc 17 + , AlexAccSkip + , AlexAcc 16 + , AlexAcc 15 + , AlexAcc 14 + , AlexAccSkip + , AlexAcc 13 + , AlexAcc 12 + , AlexAcc 11 + , AlexAcc 10 + , AlexAcc 9 + , AlexAccNone + , AlexAccNone + , AlexAccNone + , AlexAccNone + , AlexAccNone + , AlexAccNone + , AlexAcc 8 + , AlexAccNone + , AlexAcc 7 + , AlexAcc 6 + , AlexAccSkip + , AlexAccNone + , AlexAcc 5 + , AlexAccNone + , AlexAcc 4 + , AlexAcc 3 + , AlexAccSkip + , AlexAccSkip + , AlexAcc 2 + , AlexAcc 1 + , AlexAcc 0 + , AlexAccNone + ] + +alex_actions = Data.Array.array (0 :: Int, 31) + [ (30,alex_action_0) + , (29,alex_action_20) + , (28,alex_action_16) + , (27,alex_action_3) + , (26,alex_action_9) + , (25,alex_action_8) + , (24,alex_action_10) + , (23,alex_action_11) + , (22,alex_action_12) + , (21,alex_action_13) + , (20,alex_action_14) + , (19,alex_action_15) + , (18,alex_action_15) + , (17,alex_action_16) + , (16,alex_action_18) + , (15,alex_action_19) + , (14,alex_action_19) + , (13,alex_action_22) + , (12,alex_action_23) + , (11,alex_action_24) + , (10,alex_action_25) + , (9,alex_action_25) + , (8,alex_action_0) + , (7,alex_action_1) + , (6,alex_action_1) + , (5,alex_action_3) + , (4,alex_action_4) + , (3,alex_action_5) + , (2,alex_action_8) + , (1,alex_action_8) + , (0,alex_action_9) + ] + + +bol_field_braces,bol_field_layout,bol_section,in_field_braces,in_field_layout,in_section :: Int +bol_field_braces = 1 +bol_field_layout = 2 +bol_section = 3 +in_field_braces = 4 +in_field_layout = 5 +in_section = 6 +alex_action_0 = \pos len _ -> do + when (len /= 0) $ addWarningAt pos LexWarningBOM + setPos pos -- reset position as if BOM didn't exist + setStartCode bol_section + lexToken +alex_action_1 = \pos len inp -> checkWhitespace pos len inp >> adjustPos retPos >> lexToken +alex_action_3 = \pos len inp -> checkLeadingWhitespace pos len inp >>= \len' -> + -- len' is character whitespace length (counting nbsp as one) + if B.length inp == len + then return (L pos EOF) + else do + -- Small hack: if char and byte length mismatch + -- subtract the difference, so lexToken will count position correctly. + -- Proper (and slower) fix is to count utf8 length in lexToken + when (len' /= len) $ adjustPos (incPos (len' - len)) + setStartCode in_section + return (L pos (Indent len')) +alex_action_4 = tok OpenBrace +alex_action_5 = tok CloseBrace +alex_action_8 = toki TokSym +alex_action_9 = \pos len inp -> return $! L pos (TokStr (B.take (len - 2) (B.tail inp))) +alex_action_10 = toki TokOther +alex_action_11 = toki TokOther +alex_action_12 = tok Colon +alex_action_13 = tok OpenBrace +alex_action_14 = tok CloseBrace +alex_action_15 = \_ _ _ -> adjustPos retPos >> setStartCode bol_section >> lexToken +alex_action_16 = \pos len inp -> checkLeadingWhitespace pos len inp >>= \len' -> + if B.length inp == len + then return (L pos EOF) + else do + -- Small hack: if char and byte length mismatch + -- subtract the difference, so lexToken will count position correctly. + -- Proper (and slower) fix is to count utf8 length in lexToken + when (len' /= len) $ adjustPos (incPos (len' - len)) + setStartCode in_field_layout + return (L pos (Indent len')) +alex_action_18 = toki TokFieldLine +alex_action_19 = \_ _ _ -> adjustPos retPos >> setStartCode bol_field_layout >> lexToken +alex_action_20 = \_ _ _ -> setStartCode in_field_braces >> lexToken +alex_action_22 = toki TokFieldLine +alex_action_23 = tok OpenBrace +alex_action_24 = tok CloseBrace +alex_action_25 = \_ _ _ -> adjustPos retPos >> setStartCode bol_field_braces >> lexToken + +#define ALEX_LATIN1 1 +#define ALEX_NOPRED 1 +-- ----------------------------------------------------------------------------- +-- ALEX TEMPLATE +-- +-- This code is in the PUBLIC DOMAIN; you may copy it freely and use +-- it for any purpose whatsoever. + +-- ----------------------------------------------------------------------------- +-- INTERNALS and main scanner engine + +#ifdef ALEX_GHC +# define ILIT(n) n# +# define IBOX(n) (I# (n)) +# define FAST_INT Int# +-- Do not remove this comment. Required to fix CPP parsing when using GCC and a clang-compiled alex. +# if __GLASGOW_HASKELL__ > 706 +# define CMP_GEQ(n,m) (((n) >=# (m)) :: Int#) +# define CMP_EQ(n,m) (((n) ==# (m)) :: Int#) +# define CMP_MKBOOL(x) ((GHC.Exts.tagToEnum# (x)) :: Bool) +# else +# define CMP_GEQ(n,m) (((n) >= (m)) :: Bool) +# define CMP_EQ(n,m) (((n) == (m)) :: Bool) +# define CMP_MKBOOL(x) ((x) :: Bool) +# endif +# define GTE(n,m) CMP_MKBOOL(CMP_GEQ(n,m)) +# define EQ(n,m) CMP_MKBOOL(CMP_EQ(n,m)) +# define PLUS(n,m) (n +# m) +# define MINUS(n,m) (n -# m) +# define TIMES(n,m) (n *# m) +# define NEGATE(n) (negateInt# (n)) +# define IF_GHC(x) (x) +#else +# define ILIT(n) (n) +# define IBOX(n) (n) +# define FAST_INT Int +# define GTE(n,m) (n >= m) +# define EQ(n,m) (n == m) +# define PLUS(n,m) (n + m) +# define MINUS(n,m) (n - m) +# define TIMES(n,m) (n * m) +# define NEGATE(n) (negate (n)) +# define IF_GHC(x) +#endif + +#ifdef ALEX_GHC +data AlexAddr = AlexA# Addr# +-- Do not remove this comment. Required to fix CPP parsing when using GCC and a clang-compiled alex. + +{-# INLINE alexIndexInt16OffAddr #-} +alexIndexInt16OffAddr :: AlexAddr -> Int# -> Int# +alexIndexInt16OffAddr (AlexA# arr) off = +#if __GLASGOW_HASKELL__ >= 901 + GHC.Exts.int16ToInt# -- qualified import because it doesn't exist on older GHC's +#endif +#ifdef WORDS_BIGENDIAN + (GHC.Exts.word16ToInt16# (GHC.Exts.wordToWord16# (GHC.Exts.byteSwap16# (GHC.Exts.word16ToWord# (GHC.Exts.int16ToWord16# +#endif + (indexInt16OffAddr# arr off) +#ifdef WORDS_BIGENDIAN + ))))) +#endif +#else +alexIndexInt16OffAddr = (Data.Array.!) +#endif + +#ifdef ALEX_GHC +{-# INLINE alexIndexInt32OffAddr #-} +alexIndexInt32OffAddr :: AlexAddr -> Int# -> Int# +alexIndexInt32OffAddr (AlexA# arr) off = +#if __GLASGOW_HASKELL__ >= 901 + GHC.Exts.int32ToInt# -- qualified import because it doesn't exist on older GHC's +#endif +#ifdef WORDS_BIGENDIAN + (GHC.Exts.word32ToInt32# (GHC.Exts.wordToWord32# (GHC.Exts.byteSwap32# (GHC.Exts.word32ToWord# (GHC.Exts.int32ToWord32# +#endif + (indexInt32OffAddr# arr off) +#ifdef WORDS_BIGENDIAN + ))))) +#endif +#else +alexIndexInt32OffAddr = (Data.Array.!) +#endif + +#ifdef ALEX_GHC +-- GHC >= 503, unsafeAt is available from Data.Array.Base. +quickIndex = unsafeAt +#else +quickIndex = (Data.Array.!) +#endif + +-- ----------------------------------------------------------------------------- +-- Main lexing routines + +data AlexReturn a + = AlexEOF + | AlexError !AlexInput + | AlexSkip !AlexInput !Int + | AlexToken !AlexInput !Int a + +-- alexScan :: AlexInput -> StartCode -> AlexReturn a +alexScan input__ IBOX(sc) + = alexScanUser (error "alex rule requiring context was invoked by alexScan; use alexScanUser instead?") input__ IBOX(sc) + +-- If the generated alexScan/alexScanUser functions are called multiple times +-- in the same file, alexScanUser gets broken out into a separate function and +-- increases memory usage. Make sure GHC inlines this function and optimizes it. +{-# INLINE alexScanUser #-} + +alexScanUser user__ input__ IBOX(sc) + = case alex_scan_tkn user__ input__ ILIT(0) input__ sc AlexNone of + (AlexNone, input__') -> + case alexGetByte input__ of + Nothing -> +#ifdef ALEX_DEBUG + Debug.Trace.trace ("End of input.") $ +#endif + AlexEOF + Just _ -> +#ifdef ALEX_DEBUG + Debug.Trace.trace ("Error.") $ +#endif + AlexError input__' + + (AlexLastSkip input__'' len, _) -> +#ifdef ALEX_DEBUG + Debug.Trace.trace ("Skipping.") $ +#endif + AlexSkip input__'' len + + (AlexLastAcc k input__''' len, _) -> +#ifdef ALEX_DEBUG + Debug.Trace.trace ("Accept.") $ +#endif + AlexToken input__''' len ((Data.Array.!) alex_actions k) + + +-- Push the input through the DFA, remembering the most recent accepting +-- state it encountered. + +alex_scan_tkn user__ orig_input len input__ s last_acc = + input__ `seq` -- strict in the input + let + new_acc = (check_accs (alex_accept `quickIndex` IBOX(s))) + in + new_acc `seq` + case alexGetByte input__ of + Nothing -> (new_acc, input__) + Just (c, new_input) -> +#ifdef ALEX_DEBUG + Debug.Trace.trace ("State: " ++ show IBOX(s) ++ ", char: " ++ show c ++ " " ++ (show . Data.Char.chr . fromIntegral) c) $ +#endif + case fromIntegral c of { IBOX(ord_c) -> + let + base = alexIndexInt32OffAddr alex_base s + offset = PLUS(base,ord_c) + + new_s = if GTE(offset,ILIT(0)) + && let check = alexIndexInt16OffAddr alex_check offset + in EQ(check,ord_c) + then alexIndexInt16OffAddr alex_table offset + else alexIndexInt16OffAddr alex_deflt s + in + case new_s of + ILIT(-1) -> (new_acc, input__) + -- on an error, we want to keep the input *before* the + -- character that failed, not after. + _ -> alex_scan_tkn user__ orig_input +#ifdef ALEX_LATIN1 + PLUS(len,ILIT(1)) + -- issue 119: in the latin1 encoding, *each* byte is one character +#else + (if c < 0x80 || c >= 0xC0 then PLUS(len,ILIT(1)) else len) + -- note that the length is increased ONLY if this is the 1st byte in a char encoding) +#endif + new_input new_s new_acc + } + where + check_accs (AlexAccNone) = last_acc + check_accs (AlexAcc a ) = AlexLastAcc a input__ IBOX(len) + check_accs (AlexAccSkip) = AlexLastSkip input__ IBOX(len) +#ifndef ALEX_NOPRED + check_accs (AlexAccPred a predx rest) + | predx user__ orig_input IBOX(len) input__ + = AlexLastAcc a input__ IBOX(len) + | otherwise + = check_accs rest + check_accs (AlexAccSkipPred predx rest) + | predx user__ orig_input IBOX(len) input__ + = AlexLastSkip input__ IBOX(len) + | otherwise + = check_accs rest +#endif + +data AlexLastAcc + = AlexNone + | AlexLastAcc !Int !AlexInput !Int + | AlexLastSkip !AlexInput !Int + +data AlexAcc user + = AlexAccNone + | AlexAcc Int + | AlexAccSkip +#ifndef ALEX_NOPRED + | AlexAccPred Int (AlexAccPred user) (AlexAcc user) + | AlexAccSkipPred (AlexAccPred user) (AlexAcc user) + +type AlexAccPred user = user -> AlexInput -> Int -> AlexInput -> Bool + +-- ----------------------------------------------------------------------------- +-- Predicates on a rule + +alexAndPred p1 p2 user__ in1 len in2 + = p1 user__ in1 len in2 && p2 user__ in1 len in2 + +--alexPrevCharIsPred :: Char -> AlexAccPred _ +alexPrevCharIs c _ input__ _ _ = c == alexInputPrevChar input__ + +alexPrevCharMatches f _ input__ _ _ = f (alexInputPrevChar input__) + +--alexPrevCharIsOneOfPred :: Array Char Bool -> AlexAccPred _ +alexPrevCharIsOneOf arr _ input__ _ _ = arr Data.Array.! alexInputPrevChar input__ + +--alexRightContext :: Int -> AlexAccPred _ +alexRightContext IBOX(sc) user__ _ _ input__ = + case alex_scan_tkn user__ input__ ILIT(0) input__ sc AlexNone of + (AlexNone, _) -> False + _ -> True + -- TODO: there's no need to find the longest + -- match when checking the right context, just + -- the first match will do. +#endif +{-# LINE 153 "src/Distribution/Fields/Lexer.x" #-} +-- | Tokens of outer cabal file structure. Field values are treated opaquely. +data Token = TokSym !ByteString -- ^ Haskell-like identifier, number or operator + | TokStr !ByteString -- ^ String in quotes + | TokOther !ByteString -- ^ Operators and parens + | Indent !Int -- ^ Indentation token + | TokFieldLine !ByteString -- ^ Lines after @:@ + | Colon + | OpenBrace + | CloseBrace + | EOF + | LexicalError InputStream --TODO: add separate string lexical error + deriving Show + +data LToken = L !Position !Token + deriving Show + +toki :: (ByteString -> Token) -> Position -> Int -> ByteString -> Lex LToken +toki t pos len input = return $! L pos (t (B.take len input)) + +tok :: Token -> Position -> Int -> ByteString -> Lex LToken +tok t pos _len _input = return $! L pos t + +checkLeadingWhitespace :: Position -> Int -> ByteString -> Lex Int +checkLeadingWhitespace pos len bs + | B.any (== 9) (B.take len bs) = do + addWarningAt pos LexWarningTab + checkWhitespace pos len bs + | otherwise = checkWhitespace pos len bs + +checkWhitespace :: Position -> Int -> ByteString -> Lex Int +checkWhitespace pos len bs + -- UTF8 NBSP is 194 160. This function is called on whitespace bytestrings, + -- therefore counting 194 bytes is enough to count non-breaking spaces. + -- We subtract the amount of 194 bytes to convert bytes length into char length + | B.any (== 194) (B.take len bs) = do + addWarningAt pos LexWarningNBSP + return $ len - B.count 194 (B.take len bs) + | otherwise = return len + +-- ----------------------------------------------------------------------------- +-- The input type + +type AlexInput = InputStream + +alexInputPrevChar :: AlexInput -> Char +alexInputPrevChar _ = error "alexInputPrevChar not used" + +alexGetByte :: AlexInput -> Maybe (Word.Word8,AlexInput) +alexGetByte = B.uncons + +lexicalError :: Position -> InputStream -> Lex LToken +lexicalError pos inp = do + setInput B.empty + return $! L pos (LexicalError inp) + +lexToken :: Lex LToken +lexToken = do + pos <- getPos + inp <- getInput + st <- getStartCode + case alexScan inp st of + AlexEOF -> return (L pos EOF) + AlexError inp' -> + let !len_bytes = B.length inp - B.length inp' in + --FIXME: we want len_chars here really + -- need to decode utf8 up to this point + lexicalError (incPos len_bytes pos) inp' + AlexSkip inp' len_chars -> do + checkPosition pos inp inp' len_chars + adjustPos (incPos len_chars) + setInput inp' + lexToken + AlexToken inp' len_chars action -> do + checkPosition pos inp inp' len_chars + adjustPos (incPos len_chars) + setInput inp' + let !len_bytes = B.length inp - B.length inp' + t <- action pos len_bytes inp + --traceShow t $ return tok + return t + + +checkPosition :: Position -> ByteString -> ByteString -> Int -> Lex () +#ifdef CABAL_PARSEC_DEBUG +checkPosition pos@(Position lineno colno) inp inp' len_chars = do + text_lines <- getDbgText + let len_bytes = B.length inp - B.length inp' + pos_txt | lineno-1 < V.length text_lines = T.take len_chars (T.drop (colno-1) (text_lines V.! (lineno-1))) + | otherwise = T.empty + real_txt = B.take len_bytes inp + when (pos_txt /= T.decodeUtf8 real_txt) $ + traceShow (pos, pos_txt, T.decodeUtf8 real_txt) $ + traceShow (take 3 (V.toList text_lines)) $ return () + where + getDbgText = Lex $ \s@LexState{ dbgText = txt } -> LexResult s txt +#else +checkPosition _ _ _ _ = return () +#endif + +lexAll :: Lex [LToken] +lexAll = do + t <- lexToken + case t of + L _ EOF -> return [t] + _ -> do ts <- lexAll + return (t : ts) + +ltest :: Int -> String -> Prelude.IO () +ltest code s = + let (ws, xs) = execLexer (setStartCode code >> lexAll) (B.Char8.pack s) + in traverse_ print ws >> traverse_ print xs + + +mkLexState :: ByteString -> LexState +mkLexState input = LexState + { curPos = Position 1 1 + , curInput = input + , curCode = 0 + , warnings = [] +#ifdef CABAL_PARSEC_DEBUG + , dbgText = V.fromList . lines' . T.decodeUtf8With T.lenientDecode $ input +#endif + } + +#ifdef CABAL_PARSEC_DEBUG +lines' :: T.Text -> [T.Text] +lines' s1 + | T.null s1 = [] + | otherwise = case T.break (\c -> c == '\r' || c == '\n') s1 of + (l, s2) | Just (c,s3) <- T.uncons s2 + -> case T.uncons s3 of + Just ('\n', s4) | c == '\r' -> l `T.snoc` '\r' `T.snoc` '\n' : lines' s4 + _ -> l `T.snoc` c : lines' s3 + + | otherwise + -> [l] +#endif diff --git a/Cabal-syntax/src/Distribution/Fields/Pretty.hs b/Cabal-syntax/src/Distribution/Fields/Pretty.hs index 46e68cf641e..a43e17b5c5a 100644 --- a/Cabal-syntax/src/Distribution/Fields/Pretty.hs +++ b/Cabal-syntax/src/Distribution/Fields/Pretty.hs @@ -19,6 +19,7 @@ module Distribution.Fields.Pretty , prettySectionArgs ) where +import Data.Foldable (Foldable) import Distribution.Compat.Prelude import Distribution.Pretty (showToken) import Prelude () diff --git a/Cabal-syntax/src/Distribution/PackageDescription/FieldGrammar.hs b/Cabal-syntax/src/Distribution/PackageDescription/FieldGrammar.hs index 6b3ea299c16..a57235d37cd 100644 --- a/Cabal-syntax/src/Distribution/PackageDescription/FieldGrammar.hs +++ b/Cabal-syntax/src/Distribution/PackageDescription/FieldGrammar.hs @@ -1,5 +1,5 @@ {-# LANGUAGE ApplicativeDo #-} -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} @@ -109,6 +109,67 @@ packageDescriptionFieldGrammar , c CompatDataDir ) => g PackageDescription PackageDescription +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +packageDescriptionFieldGrammar = + mkPackageDescription + <$> optionalFieldDefAla "cabal-version" SpecVersion L.specVersion CabalSpecV1_0 + <*> blurFieldGrammar L.package packageIdentifierGrammar + <*> optionalFieldDefAla "license" SpecLicense L.licenseRaw (Left SPDX.NONE) + <*> licenseFilesGrammar + <*> freeTextFieldDef "copyright" L.copyright + <*> freeTextFieldDef "maintainer" L.maintainer + <*> freeTextFieldDef "author" L.author + <*> freeTextFieldDef "stability" L.stability + <*> monoidalFieldAla "tested-with" (alaList' FSep TestedWith) L.testedWith + <*> freeTextFieldDef "homepage" L.homepage + <*> freeTextFieldDef "package-url" L.pkgUrl + <*> freeTextFieldDef "bug-reports" L.bugReports + <*> freeTextFieldDef "synopsis" L.synopsis + <*> freeTextFieldDef "description" L.description + <*> freeTextFieldDef "category" L.category + <*> (map (bimap T.unpack T.unpack) <$> prefixedFields "x-" L.customFieldsPDText) + <*> optionalField "build-type" L.buildTypeRaw + <*> monoidalFieldAla "data-files" (alaList' VCat RelativePathNT) L.dataFiles + <*> ( optionalFieldDefAla "data-dir" CompatDataDir L.dataDir sameDirectory + ^^^ fmap (\x -> if null (getSymbolicPath x) then sameDirectory else x) -- map empty directories to "." + ) + <*> monoidalFieldAla "extra-source-files" formatExtraSourceFiles L.extraSrcFiles + <*> monoidalFieldAla "extra-tmp-files" (alaList' VCat RelativePathNT) L.extraTmpFiles + <*> monoidalFieldAla "extra-doc-files" formatExtraSourceFiles L.extraDocFiles + <*> ( monoidalFieldAla "extra-files" formatExtraSourceFiles L.extraFiles + ^^^ availableSince CabalSpecV3_14 [] + ) + where + mkPackageDescription specVersion package licenseRaw licenseFiles copyright maintainer author stability testedWith homepage pkgUrl bugReports synopsis description category customFieldsPD buildTypeRaw dataFiles dataDir extraSrcFiles extraTmpFiles extraDocFiles extraFiles = + PackageDescription{..} + where + sourceRepos = [] + setupBuildInfo = Nothing + -- components + library = Nothing + subLibraries = [] + executables = [] + foreignLibs = [] + testSuites = [] + benchmarks = [] + + packageIdentifierGrammar = + PackageIdentifier + <$> uniqueField "name" L.pkgName + <*> uniqueField "version" L.pkgVersion + + licenseFilesGrammar = + (++) + -- TODO: neither field is deprecated + -- should we pretty print license-file if there's single license file + -- and license-files when more + <$> monoidalFieldAla "license-file" CompatLicenseFile L.licenseFiles + <*> monoidalFieldAla "license-files" (alaList' FSep RelativePathNT) L.licenseFiles + ^^^ hiddenField +#else packageDescriptionFieldGrammar = do specVersion <- optionalFieldDefAla "cabal-version" SpecVersion L.specVersion CabalSpecV1_0 package <- blurFieldGrammar L.package packageIdentifierGrammar @@ -162,37 +223,69 @@ packageDescriptionFieldGrammar = do <$> monoidalFieldAla "license-file" CompatLicenseFile L.licenseFiles <*> monoidalFieldAla "license-files" (alaList' FSep RelativePathNT) L.licenseFiles ^^^ hiddenField +#endif ------------------------------------------------------------------------------- -- Library ------------------------------------------------------------------------------- +-- MicroHs supports tuples only up to 15 elements, so constraints beyond +-- that are nested into smaller tuples. Both GHC and MicroHs accept +-- nested constraint tuples with identical meaning. libraryFieldGrammar - :: ( FieldGrammar c g - , c (Identity LibraryVisibility) - , c (List CommaFSep (Identity ExeDependency) ExeDependency) - , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) - , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) - , c (List CommaVCat (Identity Dependency) Dependency) - , c (List CommaVCat (Identity Mixin) Mixin) - , c (List CommaVCat (Identity ModuleReexport) ModuleReexport) - , c (List FSep (MQuoted Extension) Extension) - , c (List FSep (MQuoted Language) Language) - , c (List NoCommaFSep Token' Text) - , c (List VCat (MQuoted ModuleName) ModuleName) - , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) - , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) - , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) - , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) - , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) - , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) - , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) - , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) - , c (List VCat Token Text) - , c (MQuoted Language) + :: ( ( FieldGrammar c g + , c (Identity LibraryVisibility) + , c (List CommaFSep (Identity ExeDependency) ExeDependency) + , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) + , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) + , c (List CommaVCat (Identity Dependency) Dependency) + , c (List CommaVCat (Identity Mixin) Mixin) + , c (List CommaVCat (Identity ModuleReexport) ModuleReexport) + , c (List FSep (MQuoted Extension) Extension) + , c (List FSep (MQuoted Language) Language) + , c (List NoCommaFSep Token' Text) + ) + , ( c (List VCat (MQuoted ModuleName) ModuleName) + , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) + , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) + , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) + , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) + , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) + , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) + , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) + , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) + , c (List VCat Token Text) + , c (MQuoted Language) + ) ) => LibraryName -> g Library Library +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +libraryFieldGrammar libName = + mkLibrary + <$> monoidalFieldAla "exposed-modules" formatExposedModules L.exposedModules + <*> monoidalFieldAla "reexported-modules" (alaList CommaVCat) L.reexportedModules + <*> ( monoidalFieldAla "signatures" (alaList' VCat MQuoted) L.signatures + ^^^ availableSince CabalSpecV2_0 [] + ) + <*> booleanFieldDef "exposed" L.libExposed True + <*> visibilityField + <*> blurFieldGrammar L.libBuildInfo buildInfoFieldGrammar + where + mkLibrary exposedModules reexportedModules signatures libExposed libVisibility libBuildInfo = + Library{..} + + visibilityField = case libName of + -- nameless/"main" libraries are public + LMainLibName -> pure LibraryVisibilityPublic + -- named libraries have the field + LSubLibName _ -> + optionalFieldDef "visibility" L.libVisibility LibraryVisibilityPrivate + ^^^ availableSince CabalSpecV3_0 LibraryVisibilityPrivate +#else libraryFieldGrammar libName = do exposedModules <- monoidalFieldAla "exposed-modules" formatExposedModules L.exposedModules reexportedModules <- monoidalFieldAla "reexported-modules" (alaList CommaVCat) L.reexportedModules @@ -211,6 +304,7 @@ libraryFieldGrammar libName = do LSubLibName _ -> optionalFieldDef "visibility" L.libVisibility LibraryVisibilityPrivate ^^^ availableSince CabalSpecV3_0 LibraryVisibilityPrivate +#endif {-# SPECIALIZE libraryFieldGrammar :: LibraryName -> ParsecFieldGrammar' Library #-} {-# SPECIALIZE libraryFieldGrammar :: LibraryName -> PrettyFieldGrammar' Library #-} @@ -219,34 +313,49 @@ libraryFieldGrammar libName = do ------------------------------------------------------------------------------- foreignLibFieldGrammar - :: ( FieldGrammar c g - , c (Identity ForeignLibType) - , c (Identity LibVersionInfo) - , c (Identity Version) - , c (List CommaFSep (Identity ExeDependency) ExeDependency) - , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) - , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) - , c (List CommaVCat (Identity Dependency) Dependency) - , c (List CommaVCat (Identity Mixin) Mixin) - , c (List FSep (Identity ForeignLibOption) ForeignLibOption) - , c (List FSep (MQuoted Extension) Extension) - , c (List FSep (MQuoted Language) Language) - , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) - , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) - , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) - , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) - , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) - , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) - , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) - , c (List FSep (RelativePathNT Source File) (RelativePath Source File)) - , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) - , c (List NoCommaFSep Token' Text) - , c (List VCat (MQuoted ModuleName) ModuleName) - , c (List VCat Token Text) - , c (MQuoted Language) + :: ( ( FieldGrammar c g + , c (Identity ForeignLibType) + , c (Identity LibVersionInfo) + , c (Identity Version) + , c (List CommaFSep (Identity ExeDependency) ExeDependency) + , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) + , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) + , c (List CommaVCat (Identity Dependency) Dependency) + , c (List CommaVCat (Identity Mixin) Mixin) + , c (List FSep (Identity ForeignLibOption) ForeignLibOption) + , c (List FSep (MQuoted Extension) Extension) + , c (List FSep (MQuoted Language) Language) + , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) + ) + , ( c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) + , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) + , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) + , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) + , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) + , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) + , c (List FSep (RelativePathNT Source File) (RelativePath Source File)) + , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) + , c (List NoCommaFSep Token' Text) + , c (List VCat (MQuoted ModuleName) ModuleName) + , c (List VCat Token Text) + , c (MQuoted Language) + ) ) => UnqualComponentName -> g ForeignLib ForeignLib +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +foreignLibFieldGrammar foreignLibName = + ForeignLib foreignLibName + <$> optionalFieldDef "type" L.foreignLibType ForeignLibTypeUnknown + <*> monoidalFieldAla "options" (alaList FSep) L.foreignLibOptions + <*> blurFieldGrammar L.foreignLibBuildInfo buildInfoFieldGrammar + <*> optionalField "lib-version-info" L.foreignLibVersionInfo + <*> optionalField "lib-version-linux" L.foreignLibVersionLinux + <*> monoidalFieldAla "mod-def-file" (alaList' FSep RelativePathNT) L.foreignLibModDefFile +#else foreignLibFieldGrammar foreignLibName = do foreignLibType <- optionalFieldDef "type" L.foreignLibType ForeignLibTypeUnknown foreignLibOptions <- monoidalFieldAla "options" (alaList FSep) L.foreignLibOptions @@ -255,6 +364,7 @@ foreignLibFieldGrammar foreignLibName = do foreignLibVersionLinux <- optionalField "lib-version-linux" L.foreignLibVersionLinux foreignLibModDefFile <- monoidalFieldAla "mod-def-file" (alaList' FSep RelativePathNT) L.foreignLibModDefFile pure ForeignLib{..} +#endif {-# SPECIALIZE foreignLibFieldGrammar :: UnqualComponentName -> ParsecFieldGrammar' ForeignLib #-} {-# SPECIALIZE foreignLibFieldGrammar :: UnqualComponentName -> PrettyFieldGrammar' ForeignLib #-} @@ -263,31 +373,46 @@ foreignLibFieldGrammar foreignLibName = do ------------------------------------------------------------------------------- executableFieldGrammar - :: ( FieldGrammar c g - , c (Identity ExecutableScope) - , c (List CommaFSep (Identity ExeDependency) ExeDependency) - , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) - , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) - , c (List CommaVCat (Identity Dependency) Dependency) - , c (List CommaVCat (Identity Mixin) Mixin) - , c (List FSep (MQuoted Extension) Extension) - , c (List FSep (MQuoted Language) Language) - , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) - , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) - , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) - , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) - , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) - , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) - , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) - , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) - , c (RelativePathNT Source File) - , c (List NoCommaFSep Token' Text) - , c (List VCat (MQuoted ModuleName) ModuleName) - , c (List VCat Token Text) - , c (MQuoted Language) + :: ( ( FieldGrammar c g + , c (Identity ExecutableScope) + , c (List CommaFSep (Identity ExeDependency) ExeDependency) + , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) + , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) + , c (List CommaVCat (Identity Dependency) Dependency) + , c (List CommaVCat (Identity Mixin) Mixin) + , c (List FSep (MQuoted Extension) Extension) + , c (List FSep (MQuoted Language) Language) + , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) + , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) + ) + , ( c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) + , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) + , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) + , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) + , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) + , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) + , c (RelativePathNT Source File) + , c (List NoCommaFSep Token' Text) + , c (List VCat (MQuoted ModuleName) ModuleName) + , c (List VCat Token Text) + , c (MQuoted Language) + ) ) => UnqualComponentName -> g Executable Executable +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +executableFieldGrammar exeName = + Executable exeName + -- main-is is optional as conditional blocks don't have it + <$> optionalFieldDefAla "main-is" RelativePathNT L.modulePath (modulePath mempty) + <*> ( optionalFieldDef "scope" L.exeScope ExecutablePublic + ^^^ availableSince CabalSpecV2_0 ExecutablePublic + ) + <*> blurFieldGrammar L.buildInfo buildInfoFieldGrammar +#else executableFieldGrammar exeName = do -- main-is is optional as conditional blocks don't have it modulePath <- optionalFieldDefAla "main-is" RelativePathNT L.modulePath (modulePath mempty) @@ -296,6 +421,7 @@ executableFieldGrammar exeName = do ^^^ availableSince CabalSpecV2_0 ExecutablePublic buildInfo <- blurFieldGrammar L.buildInfo buildInfoFieldGrammar pure Executable{..} +#endif {-# SPECIALIZE executableFieldGrammar :: UnqualComponentName -> ParsecFieldGrammar' Executable #-} {-# SPECIALIZE executableFieldGrammar :: UnqualComponentName -> PrettyFieldGrammar' Executable #-} @@ -337,32 +463,48 @@ testStanzaCodeGenerators f s = fmap (\x -> s{_testStanzaCodeGenerators = x}) (f {-# INLINE testStanzaCodeGenerators #-} testSuiteFieldGrammar - :: ( FieldGrammar c g - , c (Identity ModuleName) - , c (Identity TestType) - , c (List CommaFSep (Identity ExeDependency) ExeDependency) - , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) - , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) - , c (List CommaFSep Token Text) - , c (List CommaVCat (Identity Dependency) Dependency) - , c (List CommaVCat (Identity Mixin) Mixin) - , c (List FSep (MQuoted Extension) Extension) - , c (List FSep (MQuoted Language) Language) - , c (List NoCommaFSep Token' Text) - , c (List VCat (MQuoted ModuleName) ModuleName) - , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) - , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) - , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) - , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) - , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) - , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) - , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) - , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) - , c (RelativePathNT Source File) - , c (List VCat Token Text) - , c (MQuoted Language) + :: ( ( FieldGrammar c g + , c (Identity ModuleName) + , c (Identity TestType) + , c (List CommaFSep (Identity ExeDependency) ExeDependency) + , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) + , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) + , c (List CommaFSep Token Text) + , c (List CommaVCat (Identity Dependency) Dependency) + , c (List CommaVCat (Identity Mixin) Mixin) + , c (List FSep (MQuoted Extension) Extension) + , c (List FSep (MQuoted Language) Language) + , c (List NoCommaFSep Token' Text) + ) + , ( c (List VCat (MQuoted ModuleName) ModuleName) + , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) + , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) + , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) + , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) + , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) + , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) + , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) + , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) + , c (RelativePathNT Source File) + , c (List VCat Token Text) + , c (MQuoted Language) + ) ) => g TestSuiteStanza TestSuiteStanza +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +testSuiteFieldGrammar = + TestSuiteStanza + <$> optionalField "type" testStanzaTestType + <*> optionalFieldAla "main-is" RelativePathNT testStanzaMainIs + <*> optionalField "test-module" testStanzaTestModule + <*> blurFieldGrammar testStanzaBuildInfo buildInfoFieldGrammar + <*> ( monoidalFieldAla "code-generators" (alaList' CommaFSep Token) testStanzaCodeGenerators + ^^^ availableSince CabalSpecV3_8 [] + ) +#else testSuiteFieldGrammar = do _testStanzaTestType <- optionalField "type" testStanzaTestType _testStanzaMainIs <- optionalFieldAla "main-is" RelativePathNT testStanzaMainIs @@ -372,6 +514,7 @@ testSuiteFieldGrammar = do monoidalFieldAla "code-generators" (alaList' CommaFSep Token) testStanzaCodeGenerators ^^^ availableSince CabalSpecV3_8 [] pure TestSuiteStanza{..} +#endif validateTestSuite :: CabalSpecVersion -> Position -> TestSuiteStanza -> ParseResult src TestSuite validateTestSuite cabalSpecVersion pos stanza = case testSuiteType of @@ -485,37 +628,51 @@ benchmarkStanzaBuildInfo f s = fmap (\x -> s{_benchmarkStanzaBuildInfo = x}) (f {-# INLINE benchmarkStanzaBuildInfo #-} benchmarkFieldGrammar - :: ( FieldGrammar c g - , c (Identity BenchmarkType) - , c (Identity ModuleName) - , c (List CommaFSep (Identity ExeDependency) ExeDependency) - , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) - , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) - , c (List CommaVCat (Identity Dependency) Dependency) - , c (List CommaVCat (Identity Mixin) Mixin) - , c (List FSep (MQuoted Extension) Extension) - , c (List FSep (MQuoted Language) Language) - , c (List NoCommaFSep Token' Text) - , c (List VCat (MQuoted ModuleName) ModuleName) - , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) - , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) - , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) - , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) - , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) - , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) - , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) - , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) - , c (RelativePathNT Source File) - , c (List VCat Token Text) - , c (MQuoted Language) + :: ( ( FieldGrammar c g + , c (Identity BenchmarkType) + , c (Identity ModuleName) + , c (List CommaFSep (Identity ExeDependency) ExeDependency) + , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) + , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) + , c (List CommaVCat (Identity Dependency) Dependency) + , c (List CommaVCat (Identity Mixin) Mixin) + , c (List FSep (MQuoted Extension) Extension) + , c (List FSep (MQuoted Language) Language) + , c (List NoCommaFSep Token' Text) + , c (List VCat (MQuoted ModuleName) ModuleName) + ) + , ( c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) + , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) + , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) + , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) + , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) + , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) + , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) + , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) + , c (RelativePathNT Source File) + , c (List VCat Token Text) + , c (MQuoted Language) + ) ) => g BenchmarkStanza BenchmarkStanza +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +benchmarkFieldGrammar = + BenchmarkStanza + <$> optionalField "type" benchmarkStanzaBenchmarkType + <*> optionalFieldAla "main-is" RelativePathNT benchmarkStanzaMainIs + <*> optionalField "benchmark-module" benchmarkStanzaBenchmarkModule + <*> blurFieldGrammar benchmarkStanzaBuildInfo buildInfoFieldGrammar +#else benchmarkFieldGrammar = do _benchmarkStanzaBenchmarkType <- optionalField "type" benchmarkStanzaBenchmarkType _benchmarkStanzaMainIs <- optionalFieldAla "main-is" RelativePathNT benchmarkStanzaMainIs _benchmarkStanzaBenchmarkModule <- optionalField "benchmark-module" benchmarkStanzaBenchmarkModule _benchmarkStanzaBuildInfo <- blurFieldGrammar benchmarkStanzaBuildInfo buildInfoFieldGrammar pure BenchmarkStanza{..} +#endif validateBenchmark :: CabalSpecVersion -> Position -> BenchmarkStanza -> ParseResult src Benchmark validateBenchmark cabalSpecVersion pos stanza = case benchmarkStanzaType of @@ -592,28 +749,146 @@ unvalidateBenchmark b = ------------------------------------------------------------------------------- buildInfoFieldGrammar - :: ( FieldGrammar c g - , c (List CommaFSep (Identity ExeDependency) ExeDependency) - , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) - , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) - , c (List CommaVCat (Identity Dependency) Dependency) - , c (List CommaVCat (Identity Mixin) Mixin) - , c (List FSep (MQuoted Extension) Extension) - , c (List FSep (MQuoted Language) Language) - , c (List NoCommaFSep Token' Text) - , c (List VCat (MQuoted ModuleName) ModuleName) - , c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) - , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) - , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) - , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) - , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) - , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) - , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) - , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) - , c (List VCat Token Text) - , c (MQuoted Language) + :: ( ( FieldGrammar c g + , c (List CommaFSep (Identity ExeDependency) ExeDependency) + , c (List CommaFSep (Identity LegacyExeDependency) LegacyExeDependency) + , c (List CommaFSep (Identity PkgconfigDependency) PkgconfigDependency) + , c (List CommaVCat (Identity Dependency) Dependency) + , c (List CommaVCat (Identity Mixin) Mixin) + , c (List FSep (MQuoted Extension) Extension) + , c (List FSep (MQuoted Language) Language) + , c (List NoCommaFSep Token' Text) + , c (List VCat (MQuoted ModuleName) ModuleName) + ) + , ( c (List FSep (SymbolicPathNT Pkg (Dir Framework)) (SymbolicPath Pkg (Dir Framework))) + , c (List FSep (SymbolicPathNT Pkg (Dir Lib)) (SymbolicPath Pkg (Dir Lib))) + , c (List FSep (SymbolicPathNT Pkg (Dir Source)) (SymbolicPath Pkg (Dir Source))) + , c (List FSep (SymbolicPathNT Pkg (Dir Include)) (SymbolicPath Pkg (Dir Include))) + , c (List FSep (SymbolicPathNT Include File) (SymbolicPath Include File)) + , c (List FSep (RelativePathNT Framework File) (RelativePath Framework File)) + , c (List FSep (RelativePathNT Include File) (RelativePath Include File)) + , c (List VCat (SymbolicPathNT Pkg File) (SymbolicPath Pkg File)) + , c (List VCat Token Text) + , c (MQuoted Language) + ) ) => g BuildInfo BuildInfo +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +buildInfoFieldGrammar = + mkBuildInfo + <$> booleanFieldDef "buildable" L.buildable True + <*> ( monoidalFieldAla "build-tools" (alaList CommaFSep) L.buildTools + ^^^ deprecatedSince + CabalSpecV2_0 + "Please use 'build-tool-depends' field" + ^^^ removedIn + CabalSpecV3_0 + "Please use 'build-tool-depends' field." + ) + -- {- ^^^ availableSince [2,0] [] -} + -- here, we explicitly want to recognise build-tool-depends for all Cabal files + -- as otherwise cabal new-build cannot really work. + -- + -- I.e. we don't want trigger unknown field warning + <*> monoidalFieldAla "build-tool-depends" (alaList CommaFSep) L.buildToolDepends + <*> monoidalFieldAla "cpp-options" (alaList' NoCommaFSep Token') L.cppOptions + <*> ( monoidalFieldAla "asm-options" (alaList' NoCommaFSep Token') L.asmOptions + ^^^ availableSince CabalSpecV3_0 [] + ) + <*> ( monoidalFieldAla "cmm-options" (alaList' NoCommaFSep Token') L.cmmOptions + ^^^ availableSince CabalSpecV3_0 [] + ) + <*> monoidalFieldAla "cc-options" (alaList' NoCommaFSep Token') L.ccOptions + <*> ( monoidalFieldAla "cxx-options" (alaList' NoCommaFSep Token') L.cxxOptions + ^^^ availableSince CabalSpecV2_2 [] + ) + <*> ( monoidalFieldAla "jspp-options" (alaList' NoCommaFSep Token') L.jsppOptions + ^^^ availableSince CabalSpecV3_16 [] + ) + <*> monoidalFieldAla "ld-options" (alaList' NoCommaFSep Token') L.ldOptions + <*> ( monoidalFieldAla "hsc2hs-options" (alaList' NoCommaFSep Token') L.hsc2hsOptions + ^^^ availableSince CabalSpecV3_6 [] + ) + <*> monoidalFieldAla "pkgconfig-depends" (alaList CommaFSep) L.pkgconfigDepends + <*> monoidalFieldAla "frameworks" (alaList' FSep RelativePathNT) L.frameworks + <*> monoidalFieldAla "extra-framework-dirs" (alaList' FSep SymbolicPathNT) L.extraFrameworkDirs + <*> ( monoidalFieldAla "asm-sources" (alaList' VCat SymbolicPathNT) L.asmSources + ^^^ availableSince CabalSpecV3_0 [] + ) + <*> ( monoidalFieldAla "cmm-sources" (alaList' VCat SymbolicPathNT) L.cmmSources + ^^^ availableSince CabalSpecV3_0 [] + ) + <*> monoidalFieldAla "c-sources" (alaList' VCat SymbolicPathNT) L.cSources + <*> ( monoidalFieldAla "cxx-sources" (alaList' VCat SymbolicPathNT) L.cxxSources + ^^^ availableSince CabalSpecV2_2 [] + ) + <*> monoidalFieldAla "js-sources" (alaList' VCat SymbolicPathNT) L.jsSources + <*> hsSourceDirsGrammar + <*> monoidalFieldAla "other-modules" formatOtherModules L.otherModules + <*> ( monoidalFieldAla "virtual-modules" (alaList' VCat MQuoted) L.virtualModules + ^^^ availableSince CabalSpecV2_2 [] + ) + <*> ( monoidalFieldAla "autogen-modules" (alaList' VCat MQuoted) L.autogenModules + ^^^ availableSince CabalSpecV2_0 [] + ) + <*> ( optionalFieldAla "default-language" MQuoted L.defaultLanguage + ^^^ availableSince CabalSpecV1_10 Nothing + ) + <*> ( monoidalFieldAla "other-languages" (alaList' FSep MQuoted) L.otherLanguages + ^^^ availableSince CabalSpecV1_10 [] + ) + <*> ( monoidalFieldAla "default-extensions" (alaList' FSep MQuoted) L.defaultExtensions + ^^^ availableSince CabalSpecV1_10 [] + ) + <*> ( monoidalFieldAla "other-extensions" formatOtherExtensions L.otherExtensions + ^^^ availableSinceWarn CabalSpecV1_10 + ) + <*> ( monoidalFieldAla "extensions" (alaList' FSep MQuoted) L.oldExtensions + ^^^ deprecatedSince + CabalSpecV1_12 + "Please use 'default-extensions' or 'other-extensions' fields." + ^^^ removedIn + CabalSpecV3_0 + "Please use 'default-extensions' or 'other-extensions' fields." + ) + <*> monoidalFieldAla "extra-libraries" (alaList' VCat Token) L.extraLibs + <*> ( monoidalFieldAla "extra-libraries-static" (alaList' VCat Token) L.extraLibsStatic + ^^^ availableSince CabalSpecV3_8 [] + ) + <*> monoidalFieldAla "extra-ghci-libraries" (alaList' VCat Token) L.extraGHCiLibs + <*> monoidalFieldAla "extra-bundled-libraries" (alaList' VCat Token) L.extraBundledLibs + <*> monoidalFieldAla "extra-library-flavours" (alaList' VCat Token) L.extraLibFlavours + <*> ( monoidalFieldAla "extra-dynamic-library-flavours" (alaList' VCat Token) L.extraDynLibFlavours + ^^^ availableSince CabalSpecV3_0 [] + ) + <*> monoidalFieldAla "extra-lib-dirs" (alaList' FSep SymbolicPathNT) L.extraLibDirs + <*> ( monoidalFieldAla "extra-lib-dirs-static" (alaList' FSep SymbolicPathNT) L.extraLibDirsStatic + ^^^ availableSince CabalSpecV3_8 [] + ) + <*> monoidalFieldAla "include-dirs" (alaList' FSep SymbolicPathNT) L.includeDirs + <*> monoidalFieldAla "includes" (alaList' FSep SymbolicPathNT) L.includes + <*> ( monoidalFieldAla "autogen-includes" (alaList' FSep RelativePathNT) L.autogenIncludes + ^^^ availableSince CabalSpecV3_0 [] + ) + <*> monoidalFieldAla "install-includes" (alaList' FSep RelativePathNT) L.installIncludes + <*> optionsFieldGrammar + <*> profOptionsFieldGrammar + <*> sharedOptionsFieldGrammar + <*> profSharedOptionsFieldGrammar + <*> prefixedFields "x-" L.customFieldsBI + <*> monoidalFieldAla "build-depends" formatDependencyList L.targetBuildDepends + <*> ( monoidalFieldAla "mixins" formatMixinList L.mixins + ^^^ availableSince CabalSpecV2_0 [] + ) + where + mkBuildInfo buildable buildTools buildToolDepends cppOptions asmOptions cmmOptions ccOptions cxxOptions jsppOptions ldOptions hsc2hsOptions pkgconfigDepends frameworks extraFrameworkDirs asmSources cmmSources cSources cxxSources jsSources hsSourceDirs otherModules virtualModules autogenModules defaultLanguage otherLanguages defaultExtensions otherExtensions oldExtensions extraLibs extraLibsStatic extraGHCiLibs extraBundledLibs extraLibFlavours extraDynLibFlavours extraLibDirs extraLibDirsStatic includeDirs includes autogenIncludes installIncludes options profOptions sharedOptions profSharedOptions customFieldsBI targetBuildDepends mixins = + BuildInfo{..} + where + staticOptions = mempty +#else buildInfoFieldGrammar = do buildable <- booleanFieldDef "buildable" L.buildable True buildTools <- @@ -721,6 +996,7 @@ buildInfoFieldGrammar = do monoidalFieldAla "mixins" formatMixinList L.mixins ^^^ availableSince CabalSpecV2_0 [] pure BuildInfo{..} +#endif {-# SPECIALIZE buildInfoFieldGrammar :: ParsecFieldGrammar' BuildInfo #-} {-# SPECIALIZE buildInfoFieldGrammar :: PrettyFieldGrammar' BuildInfo #-} @@ -809,11 +1085,22 @@ flagFieldGrammar :: FieldGrammar c g => FlagName -> g PackageFlag PackageFlag +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +flagFieldGrammar flagName = + MkPackageFlag flagName + <$> (T.unpack <$> freeTextFieldDef "description" L.flagDescription) + <*> booleanFieldDef "default" L.flagDefault True + <*> booleanFieldDef "manual" L.flagManual False +#else flagFieldGrammar flagName = do flagDescription <- T.unpack <$> freeTextFieldDef "description" L.flagDescription flagDefault <- booleanFieldDef "default" L.flagDefault True flagManual <- booleanFieldDef "manual" L.flagManual False pure MkPackageFlag{..} +#endif {-# SPECIALIZE flagFieldGrammar :: FlagName -> ParsecFieldGrammar' PackageFlag #-} {-# SPECIALIZE flagFieldGrammar :: FlagName -> PrettyFieldGrammar' PackageFlag #-} @@ -825,6 +1112,19 @@ sourceRepoFieldGrammar :: (FieldGrammar c g, c (Identity RepoType)) => RepoKind -> g SourceRepo SourceRepo +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +sourceRepoFieldGrammar repoKind = + SourceRepo repoKind + <$> optionalField "type" L.repoType + <*> freeTextField "location" L.repoLocation + <*> optionalFieldAla "module" Token L.repoModule + <*> optionalFieldAla "branch" Token L.repoBranch + <*> optionalFieldAla "tag" Token L.repoTag + <*> optionalFieldAla "subdir" FilePathNT L.repoSubdir +#else sourceRepoFieldGrammar repoKind = do repoType <- optionalField "type" L.repoType repoLocation <- freeTextField "location" L.repoLocation @@ -833,6 +1133,7 @@ sourceRepoFieldGrammar repoKind = do repoTag <- optionalFieldAla "tag" Token L.repoTag repoSubdir <- optionalFieldAla "subdir" FilePathNT L.repoSubdir pure SourceRepo{..} +#endif {-# SPECIALIZE sourceRepoFieldGrammar :: RepoKind -> ParsecFieldGrammar' SourceRepo #-} {-# SPECIALIZE sourceRepoFieldGrammar :: RepoKind -> PrettyFieldGrammar' SourceRepo #-} diff --git a/Cabal-syntax/src/Distribution/PackageDescription/Quirks.hs b/Cabal-syntax/src/Distribution/PackageDescription/Quirks.hs index 2fc15a6c303..87b424bc42b 100644 --- a/Cabal-syntax/src/Distribution/PackageDescription/Quirks.hs +++ b/Cabal-syntax/src/Distribution/PackageDescription/Quirks.hs @@ -7,7 +7,6 @@ module Distribution.PackageDescription.Quirks (patchQuirks) where import Distribution.Compat.Prelude import Distribution.Utils.MD5 -import GHC.Fingerprint (Fingerprint (..)) import Prelude () import qualified Data.ByteString as BS diff --git a/Cabal-syntax/src/Distribution/SPDX/LicenseExceptionId.hs b/Cabal-syntax/src/Distribution/SPDX/LicenseExceptionId.hs index 2578279240a..d1d5e56d00f 100644 --- a/Cabal-syntax/src/Distribution/SPDX/LicenseExceptionId.hs +++ b/Cabal-syntax/src/Distribution/SPDX/LicenseExceptionId.hs @@ -1,4 +1,5 @@ -- This file is generated. See Makefile's spdx rule +{-# LANGUAGE CPP #-} {- FOURMOLU_DISABLE -} module Distribution.SPDX.LicenseExceptionId ( LicenseExceptionId (..), @@ -15,7 +16,7 @@ import Distribution.Compat.Lens (set) import Distribution.Pretty import Distribution.Parsec import Distribution.Utils.Generic (isAsciiAlphaNum) -import Distribution.Utils.Structured (Structured (..), nominalStructure, typeVersion) +import Distribution.Utils.Structured (nominalStructure, typeVersion) import Distribution.SPDX.LicenseListVersion import qualified Data.Binary.Get as Binary @@ -24,6 +25,10 @@ import qualified Data.Map.Strict as Map import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp +#ifdef __MHS__ +import Data.Data (Constr, Data (..), DataType, Fixity (Prefix), constrIndex, mkConstrTag, mkDataType) +#endif + ------------------------------------------------------------------------------- -- LicenseExceptionId ------------------------------------------------------------------------------- @@ -114,7 +119,16 @@ data LicenseExceptionId | Vsftpd_openssl_exception -- ^ @vsftpd-openssl-exception@, vsftpd OpenSSL exception, SPDX License List 3.23, SPDX License List 3.25, SPDX License List 3.26, SPDX License List 3.28 | WxWindows_exception_3_1 -- ^ @WxWindows-exception-3.1@, WxWindows Library Exception 3.1 | X11vnc_openssl_exception -- ^ @x11vnc-openssl-exception@, x11vnc OpenSSL Exception, SPDX License List 3.23, SPDX License List 3.25, SPDX License List 3.26, SPDX License List 3.28 - deriving (Eq, Ord, Enum, Bounded, Show, Read, Data, Generic) + deriving (Eq, +#ifdef __MHS__ + -- No derived Ord/Data: same per-constructor compile cost as + -- LicenseId at scale; hand-written instances below keep the + -- semantics and the Data instance downstream deriving requires. + Enum, Bounded, Show, Read, Generic +#else + Ord, Enum, Bounded, Show, Read, Data, Generic +#endif + ) instance Binary LicenseExceptionId where put = Binary.putWord8 . fromIntegral . fromEnum @@ -124,6 +138,47 @@ instance Binary LicenseExceptionId where then fail "Too large LicenseExceptionId tag" else return (toEnum (fromIntegral i)) +#ifdef __MHS__ +-- Hand-written Ord/Data mirror the derived instances (declaration-order +-- tags, constructor names as declared) without the measured +-- end-to-end compile cost of the derived versions at scale +-- (~10s user each at 150 constructors; root cause not isolated to a +-- compiler phase). Compare via the derived Enum tags; Data round-trips +-- via the tag index. Semantics match the derived instances; Binary +-- (which also uses fromEnum) and all constructors are unchanged. +instance Ord LicenseExceptionId where + compare a b = compare (fromEnum a) (fromEnum b) + +instance Data LicenseExceptionId where + gfoldl k z x = z x + gunfold _k z c = z (toEnum (constrIndex c - 1)) + toConstr x = licenseExceptionIdConstrs !! fromEnum x + dataTypeOf _ = tyLicenseExceptionId + +tyLicenseExceptionId :: DataType +tyLicenseExceptionId = mkDataType "Distribution.SPDX.LicenseExceptionId" licenseExceptionIdConstrs + +licenseExceptionIdConstrs :: [Constr] +licenseExceptionIdConstrs = + [ mkConstrTag tyLicenseExceptionId name i [] Prefix + | (i, name) <- zip [1 ..] licenseExceptionIdConstrNames + ] + +licenseExceptionIdConstrNames :: [String] +licenseExceptionIdConstrNames = + [ "N_389_exception", "Asterisk_exception", "Asterisk_linking_protocols_exception", "Autoconf_exception_2_0", "Autoconf_exception_3_0", "Autoconf_exception_generic_3_0", "Autoconf_exception_generic", "Autoconf_exception_macro" + , "Bison_exception_1_24", "Bison_exception_2_2", "Bootloader_exception", "CGAL_linking_exception", "Classpath_exception_2_0_short", "Classpath_exception_2_0", "CLISP_exception_2_0", "Cryptsetup_OpenSSL_exception" + , "Digia_Qt_LGPL_exception_1_1", "DigiRule_FOSS_exception", "ECos_exception_2_0", "Erlang_otp_linking_exception", "Fawkes_Runtime_exception", "FLTK_exception", "Fmt_exception", "Font_exception_2_0" + , "Freertos_exception_2_0", "GCC_exception_2_0_note", "GCC_exception_2_0", "GCC_exception_3_1", "Gmsh_exception", "GNAT_exception", "GNOME_examples_exception", "GNU_compiler_exception" + , "Gnu_javamail_exception", "GPL_3_0_389_ds_base_exception", "GPL_3_0_interface_exception", "GPL_3_0_linking_exception", "GPL_3_0_linking_source_exception", "GPL_CC_1_0", "GStreamer_exception_2005", "GStreamer_exception_2008" + , "Harbour_exception", "I2p_gpl_java_exception", "Independent_modules_exception", "KiCad_libraries_exception", "Kvirc_openssl_exception", "LGPL_3_0_linking_exception", "Libpri_OpenH323_exception", "Libtool_exception" + , "Linux_syscall_note", "LLGPL", "LLVM_exception", "LZMA_exception", "Mif_exception", "Nokia_Qt_exception_1_1", "Mxml_exception", "OCaml_LGPL_linking_exception" + , "OCCT_exception_1_0", "OpenJDK_assembly_exception_1_0", "Openvpn_openssl_exception", "PCRE2_exception", "Polyparse_exception", "PS_or_PDF_font_exception_20170817", "QPL_1_0_INRIA_2004_exception", "Qt_GPL_exception_1_0" + , "Qt_LGPL_exception_1_1", "Qwt_exception_1_0", "Romic_exception", "RRDtool_FLOSS_exception_2_0", "Rsync_linking_exception", "SANE_exception", "SHL_2_0", "SHL_2_1" + , "Simple_Library_Usage_exception", "Sqlitestudio_OpenSSL_exception", "Stunnel_exception", "SWI_exception", "Swift_exception", "Texinfo_exception", "U_boot_exception_2_0", "UBDL_exception" + , "Universal_FOSS_exception_1_0", "Vsftpd_openssl_exception", "WxWindows_exception_3_1", "X11vnc_openssl_exception" ] +#endif + -- note: remember to bump version each time the definition changes instance Structured LicenseExceptionId where structure p = set typeVersion 308 $ nominalStructure p diff --git a/Cabal-syntax/src/Distribution/SPDX/LicenseId.hs b/Cabal-syntax/src/Distribution/SPDX/LicenseId.hs index 2ce8b1397c3..8bad3d76c62 100644 --- a/Cabal-syntax/src/Distribution/SPDX/LicenseId.hs +++ b/Cabal-syntax/src/Distribution/SPDX/LicenseId.hs @@ -1,4 +1,5 @@ -- This file is generated. See Makefile's spdx rule +{-# LANGUAGE CPP #-} {- FOURMOLU_DISABLE -} module Distribution.SPDX.LicenseId ( LicenseId (..), @@ -19,7 +20,7 @@ import Distribution.Compat.Lens (set) import Distribution.Pretty import Distribution.Parsec import Distribution.Utils.Generic (isAsciiAlphaNum) -import Distribution.Utils.Structured (Structured (..), nominalStructure, typeVersion) +import Distribution.Utils.Structured (nominalStructure, typeVersion) import Distribution.SPDX.LicenseListVersion import qualified Data.Binary.Get as Binary @@ -28,6 +29,10 @@ import qualified Data.Map.Strict as Map import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp +#ifdef __MHS__ +import Data.Data (Constr, Data (..), DataType, Fixity (Prefix), constrIndex, mkConstrTag, mkDataType) +#endif + ------------------------------------------------------------------------------- -- LicenseId ------------------------------------------------------------------------------- @@ -734,7 +739,20 @@ data LicenseId | ZPL_1_1 -- ^ @ZPL-1.1@, Zope Public License 1.1 | ZPL_2_0 -- ^ @ZPL-2.0@, Zope Public License 2.0 | ZPL_2_1 -- ^ @ZPL-2.1@, Zope Public License 2.1 - deriving (Eq, Ord, Enum, Bounded, Show, Read, Data) + deriving (Eq, +#ifdef __MHS__ + -- No Ord: MicroHs compiles the derived Ord for this ~700-constructor + -- type pathologically slowly (see instance below). + -- No derived Data: costs as much as derived Ord at scale (~9s + -- user at 150 constructors); a hand-written instance below keeps + -- the Data LicenseId instance that downstream deriving + -- (LicenseExpression) requires. Nothing in the tree calls Data + -- methods on LicenseId. + Enum, Bounded, Show, Read +#else + Ord, Enum, Bounded, Show, Read, Data +#endif + ) instance Binary LicenseId where -- Word16 is encoded in big endianness @@ -746,6 +764,133 @@ instance Binary LicenseId where then fail "Too large LicenseId tag" else return (toEnum (fromIntegral i)) +#ifdef __MHS__ +-- MicroHs takes pathologically long to compile the derived Ord for +-- this ~700-constructor type (measured end to end: ~548s user for a +-- 700-constructor synthetic analogue vs ~0.4s with this instance; +-- root cause not isolated to a compiler phase). Compare via the +-- derived Enum tags instead. Semantics are identical to derived Ord +-- for a plain enumeration (declaration order); Binary (which also +-- uses fromEnum) and all constructors are unchanged. +instance Ord LicenseId where + compare a b = compare (fromEnum a) (fromEnum b) +#endif + +#ifdef __MHS__ +-- Hand-written Data mirrors the derived instance (declaration-order +-- tags, constructor names as declared) without the measured +-- end-to-end compile cost (~9s user at 150 constructors for derived +-- Data; root cause not isolated to a compiler phase). +-- toConstr/fromConstr round-trip via the tag index; gfoldl is trivial +-- for nullary constructors. Nothing in the tree calls Data methods +-- on LicenseId; the instance exists for downstream deriving. +instance Data LicenseId where + gfoldl k z x = z x + gunfold _k z c = z (toEnum (constrIndex c - 1)) + toConstr x = licenseIdConstrs !! fromEnum x + dataTypeOf _ = tyLicenseId + +tyLicenseId :: DataType +tyLicenseId = mkDataType "Distribution.SPDX.LicenseId" licenseIdConstrs + +licenseIdConstrs :: [Constr] +licenseIdConstrs = + [ mkConstrTag tyLicenseId name i [] Prefix + | (i, name) <- zip [1 ..] licenseIdConstrNames + ] + +licenseIdConstrNames :: [String] +licenseIdConstrNames = + [ "N_0BSD", "N_3D_Slicer_1_0", "AAL", "Abstyles", "AdaCore_doc", "Adobe_2006", "Adobe_Display_PostScript", "Adobe_Glyph" + , "Adobe_Utopia", "ADSL", "Advanced_Cryptics_Dictionary", "AFL_1_1", "AFL_1_2", "AFL_2_0", "AFL_2_1", "AFL_3_0" + , "Afmparse", "AGPL_1_0", "AGPL_1_0_only", "AGPL_1_0_or_later", "AGPL_3_0_only", "AGPL_3_0_or_later", "Aladdin", "ALGLIB_Documentation" + , "AMD_newlib", "AMDPLPA", "AML_glslang", "AML", "AMPAS", "ANTLR_PD_fallback", "ANTLR_PD", "Any_OSI_perl_modules" + , "Any_OSI", "Apache_1_0", "Apache_1_1", "Apache_2_0", "APAFML", "APL_1_0", "App_s2p", "APSL_1_0" + , "APSL_1_1", "APSL_1_2", "APSL_2_0", "Arphic_1999", "Artistic_1_0_cl8", "Artistic_1_0_Perl", "Artistic_1_0", "Artistic_2_0" + , "Artistic_dist", "Aspell_RU", "ASWF_Digital_Assets_1_0", "ASWF_Digital_Assets_1_1", "Baekmuk", "Bahyph", "Barr", "Bcrypt_Solar_Designer" + , "Beerware", "Bitstream_Charter", "Bitstream_Vera", "BitTorrent_1_0", "BitTorrent_1_1", "Blessing", "BlueOak_1_0_0", "Boehm_GC_without_fee" + , "Boehm_GC", "BOLA_1_1", "Borceux", "Brian_Gladman_2_Clause", "Brian_Gladman_3_Clause", "BSD_1_Clause", "BSD_2_Clause_FreeBSD", "BSD_2_Clause_NetBSD" + , "BSD_2_Clause_Darwin", "BSD_2_Clause_first_lines", "BSD_2_Clause_Patent", "BSD_2_Clause_pkgconf_disclaimer", "BSD_2_Clause_Views", "BSD_2_Clause", "BSD_3_Clause_acpica", "BSD_3_Clause_Attribution" + , "BSD_3_Clause_Clear", "BSD_3_Clause_flex", "BSD_3_Clause_HP", "BSD_3_Clause_LBNL", "BSD_3_Clause_Modification", "BSD_3_Clause_No_Military_License", "BSD_3_Clause_No_Nuclear_License_2014", "BSD_3_Clause_No_Nuclear_License" + , "BSD_3_Clause_No_Nuclear_Warranty", "BSD_3_Clause_Open_MPI", "BSD_3_Clause_Sun", "BSD_3_Clause_Tso", "BSD_3_Clause", "BSD_4_Clause_Shortened", "BSD_4_Clause_UC", "BSD_4_Clause" + , "BSD_4_3RENO", "BSD_4_3TAHOE", "BSD_Advertising_Acknowledgement", "BSD_Attribution_HPND_disclaimer", "BSD_Inferno_Nettverk", "BSD_Mark_Modifications", "BSD_Protection", "BSD_Source_beginning_file" + , "BSD_Source_Code", "BSD_Systemics_W3Works", "BSD_Systemics", "BSL_1_0", "Bzip2_1_0_5", "Buddy", "BUSL_1_1", "Bzip2_1_0_6" + , "C_UDA_1_0", "CAL_1_0_Combined_Work_Exception", "CAL_1_0", "Caldera_no_preamble", "Caldera", "CAPEC_tou", "Catharon", "CATOSL_1_1" + , "CC_BY_1_0", "CC_BY_2_0", "CC_BY_2_5_AU", "CC_BY_2_5", "CC_BY_3_0_AT", "CC_BY_3_0_AU", "CC_BY_3_0_DE", "CC_BY_3_0_IGO" + , "CC_BY_3_0_NL", "CC_BY_3_0_US", "CC_BY_3_0", "CC_BY_4_0", "CC_BY_NC_1_0", "CC_BY_NC_2_0", "CC_BY_NC_2_5", "CC_BY_NC_3_0_DE" + , "CC_BY_NC_3_0", "CC_BY_NC_4_0", "CC_BY_NC_ND_1_0", "CC_BY_NC_ND_2_0", "CC_BY_NC_ND_2_5", "CC_BY_NC_ND_3_0_DE", "CC_BY_NC_ND_3_0_IGO", "CC_BY_NC_ND_3_0" + , "CC_BY_NC_ND_4_0", "CC_BY_NC_SA_1_0", "CC_BY_NC_SA_2_0_DE", "CC_BY_NC_SA_2_0_FR", "CC_BY_NC_SA_2_0_UK", "CC_BY_NC_SA_2_0", "CC_BY_NC_SA_2_5", "CC_BY_NC_SA_3_0_DE" + , "CC_BY_NC_SA_3_0_IGO", "CC_BY_NC_SA_3_0", "CC_BY_NC_SA_4_0", "CC_BY_ND_1_0", "CC_BY_ND_2_0", "CC_BY_ND_2_5", "CC_BY_ND_3_0_DE", "CC_BY_ND_3_0" + , "CC_BY_ND_4_0", "CC_BY_SA_1_0", "CC_BY_SA_2_0_UK", "CC_BY_SA_2_0", "CC_BY_SA_2_1_JP", "CC_BY_SA_2_5", "CC_BY_SA_3_0_AT", "CC_BY_SA_3_0_DE" + , "CC_BY_SA_3_0_IGO", "CC_BY_SA_3_0", "CC_BY_SA_4_0", "CC_PDDC", "CC_PDM_1_0", "CC_SA_1_0", "CC0_1_0", "CDDL_1_0" + , "CDDL_1_1", "CDL_1_0", "CDLA_Permissive_1_0", "CDLA_Permissive_2_0", "CDLA_Sharing_1_0", "CECILL_1_0", "CECILL_1_1", "CECILL_2_0" + , "CECILL_2_1", "CECILL_B", "CECILL_C", "CERN_OHL_1_1", "CERN_OHL_1_2", "CERN_OHL_P_2_0", "CERN_OHL_S_2_0", "CERN_OHL_W_2_0" + , "CFITSIO", "Check_cvs", "Checkmk", "ClArtistic", "Clips", "CMU_Mach_nodoc", "CMU_Mach", "CNRI_Jython" + , "CNRI_Python_GPL_Compatible", "CNRI_Python", "COIL_1_0", "Community_Spec_1_0", "Condor_1_1", "Copyleft_next_0_3_0", "Copyleft_next_0_3_1", "Cornell_Lossless_JPEG" + , "CPAL_1_0", "CPL_1_0", "CPOL_1_02", "Cronyx", "Crossword", "CryptoSwift", "CrystalStacker", "CUA_OPL_1_0" + , "Cube", "Curl", "Cve_tou", "D_FSL_1_0", "DEC_3_Clause", "Diffmark", "DL_DE_BY_2_0", "DL_DE_ZERO_2_0" + , "DocBook_DTD", "DocBook_Schema", "DocBook_Stylesheet", "DocBook_XML", "DOC", "Dotseqn", "DRL_1_0", "DRL_1_1" + , "DSDP", "Dtoa", "Dvipdfm", "ECL_1_0", "ECL_2_0", "EFL_1_0", "EFL_2_0", "EGenix" + , "Elastic_2_0", "Entessa", "EPICS", "EPL_1_0", "EPL_2_0", "ErlPL_1_1", "ESA_PL_permissive_2_4", "ESA_PL_strong_copyleft_2_4" + , "ESA_PL_weak_copyleft_2_4", "Etalab_2_0", "EUDatagrid", "EUPL_1_0", "EUPL_1_1", "EUPL_1_2", "Eurosym", "Fair" + , "FBM", "FDK_AAC", "Ferguson_Twofish", "Frameworx_1_0", "FreeBSD_DOC", "FreeImage", "FSFAP_no_warranty_disclaimer", "FSFAP" + , "FSFULLRSD", "FSFULLRWD", "FSFULLR", "FSFUL", "FSL_1_1_ALv2", "FSL_1_1_MIT", "FTL", "Furuseth" + , "Fwlw", "Game_Programming_Gems", "GCR_docs", "GD", "Generic_xts", "GFDL_1_1_invariants_only", "GFDL_1_1_invariants_or_later", "GFDL_1_1_no_invariants_only" + , "GFDL_1_1_no_invariants_or_later", "GFDL_1_1_only", "GFDL_1_1_or_later", "GFDL_1_2_invariants_only", "GFDL_1_2_invariants_or_later", "GFDL_1_2_no_invariants_only", "GFDL_1_2_no_invariants_or_later", "GFDL_1_2_only" + , "GFDL_1_2_or_later", "GFDL_1_3_invariants_only", "GFDL_1_3_invariants_or_later", "GFDL_1_3_no_invariants_only", "GFDL_1_3_no_invariants_or_later", "GFDL_1_3_only", "GFDL_1_3_or_later", "Giftware" + , "GL2PS", "Glide", "Glulxe", "GLWTPL", "Gnuplot", "GPL_1_0_only", "GPL_1_0_or_later", "GPL_2_0_only" + , "GPL_2_0_or_later", "GPL_3_0_only", "GPL_3_0_or_later", "Graphics_Gems", "GSOAP_1_3b", "Gtkbook", "Gutmann", "HaskellReport" + , "HDF5", "Hdparm", "HIDAPI", "Hippocratic_2_1", "HP_1986", "HP_1989", "HPND_DEC", "HPND_doc_sell" + , "HPND_doc", "HPND_export_US_acknowledgement", "HPND_export_US_modify", "HPND_export_US", "HPND_export2_US", "HPND_Fenneberg_Livingston", "HPND_INRIA_IMAG", "HPND_Intel" + , "HPND_Kevlin_Henney", "HPND_Markus_Kuhn", "HPND_merchantability_variant", "HPND_MIT_disclaimer", "HPND_Netrek", "HPND_Pbmplus", "HPND_sell_MIT_disclaimer_xserver", "HPND_sell_regexpr" + , "HPND_sell_variant_critical_systems", "HPND_sell_variant_MIT_disclaimer_rev", "HPND_sell_variant_MIT_disclaimer", "HPND_sell_variant", "HPND_SMC", "HPND_UC_export_US", "HPND_UC", "HPND" + , "HTMLTIDY", "Hyphen_bulgarian", "IBM_pibs", "ICU", "IEC_Code_Components_EULA", "IJG_short", "IJG", "ImageMagick" + , "IMatix", "Imlib2", "Info_ZIP", "Inner_Net_2_0", "InnoSetup", "Intel_ACPI", "Intel", "Interbase_1_0" + , "IPA", "IPL_1_0", "ISC_Veillard", "ISC", "ISO_permission", "Jam", "JasPer_2_0", "Jove" + , "JPL_image", "JPNIC", "JSON", "Kastrup", "Kazlib", "Knuth_CTAN", "LAL_1_2", "LAL_1_3" + , "Latex2e_translated_notice", "Latex2e", "Leptonica", "LGPL_2_0_only", "LGPL_2_0_or_later", "LGPL_2_1_only", "LGPL_2_1_or_later", "LGPL_3_0_only" + , "LGPL_3_0_or_later", "LGPLLR", "Libpng_1_6_35", "Libpng_2_0", "Libpng", "Libselinux_1_0", "Libtiff", "Libutil_David_Nugent" + , "LiLiQ_P_1_1", "LiLiQ_R_1_1", "LiLiQ_Rplus_1_1", "Linux_man_pages_1_para", "Linux_man_pages_copyleft_2_para", "Linux_man_pages_copyleft_var", "Linux_man_pages_copyleft", "Linux_OpenIB" + , "LOOP", "LPD_document", "LPL_1_02", "LPL_1_0", "LPPL_1_0", "LPPL_1_1", "LPPL_1_2", "LPPL_1_3a" + , "LPPL_1_3c", "Lsof", "Lucida_Bitmap_Fonts", "LZMA_SDK_9_11_to_9_20", "LZMA_SDK_9_22", "Mackerras_3_Clause_acknowledgment", "Mackerras_3_Clause", "Magaz" + , "Mailprio", "MakeIndex", "Man2html", "Martin_Birgmeier", "McPhee_slideshow", "Metamail", "Minpack", "MIPS" + , "MirOS", "MIT_0", "MIT_advertising", "MIT_Click", "MIT_CMU", "MIT_enna", "MIT_feh", "MIT_Festival" + , "MIT_Khronos_old", "MIT_Modern_Variant", "MIT_open_group", "MIT_STK", "MIT_testregex", "MIT_Wu", "MITNFA", "MIT" + , "MMIXware", "MMPL_1_0_1", "Motosoto", "MPEG_SSG", "Mpi_permissive", "Mpich2", "MPL_1_0", "MPL_1_1" + , "MPL_2_0_no_copyleft_exception", "MPL_2_0", "Mplus", "MS_LPL", "MS_PL", "MS_RL", "MTLL", "MulanPSL_1_0" + , "MulanPSL_2_0", "Multics", "Mup", "NAIST_2003", "NASA_1_3", "Naumen", "NBPL_1_0", "NCBI_PD" + , "NCGL_UK_2_0", "NCL", "NCSA", "Net_SNMP", "NetCDF", "Newsletr", "NGPL", "Ngrep" + , "NICTA_1_0", "NIST_PD_fallback", "NIST_PD_TNT", "NIST_PD", "NIST_Software", "NLOD_1_0", "NLOD_2_0", "NLPL" + , "Nokia", "NOSL", "Noweb", "NPL_1_0", "NPL_1_1", "NPOSL_3_0", "NRL", "NTIA_PD" + , "NTP_0", "NTP", "O_UDA_1_0", "OAR", "OCCT_PL", "OCLC_2_0", "ODbL_1_0", "ODC_By_1_0" + , "OFFIS", "OFL_1_0_no_RFN", "OFL_1_0_RFN", "OFL_1_0", "OFL_1_1_no_RFN", "OFL_1_1_RFN", "OFL_1_1", "OGC_1_0" + , "OGDL_Taiwan_1_0", "OGL_Canada_2_0", "OGL_UK_1_0", "OGL_UK_2_0", "OGL_UK_3_0", "OGTSL", "OLDAP_1_1", "OLDAP_1_2" + , "OLDAP_1_3", "OLDAP_1_4", "OLDAP_2_0_1", "OLDAP_2_0", "OLDAP_2_1", "OLDAP_2_2_1", "OLDAP_2_2_2", "OLDAP_2_2" + , "OLDAP_2_3", "OLDAP_2_4", "OLDAP_2_5", "OLDAP_2_6", "OLDAP_2_7", "OLDAP_2_8", "OLFL_1_3", "OML" + , "OpenMDW_1_0", "OpenPBS_2_3", "OpenSSL_standalone", "OpenSSL", "OpenVision", "OPL_1_0", "OPL_UK_3_0", "OPUBL_1_0" + , "OSC_1_0", "OSET_PL_2_1", "OSL_1_0", "OSL_1_1", "OSL_2_0", "OSL_2_1", "OSL_3_0", "OSSP" + , "PADL", "ParaType_Free_Font_1_3", "Parity_6_0_0", "Parity_7_0_0", "PDDL_1_0", "PHP_3_01", "PHP_3_0", "Pixar" + , "Pkgconf", "Plexus", "Pnmstitch", "PolyForm_Noncommercial_1_0_0", "PolyForm_Small_Business_1_0_0", "PostgreSQL", "PPL", "PSF_2_0" + , "Psfrag", "Psutils", "Python_2_0_1", "Python_2_0", "Python_ldap", "Qhull", "QPL_1_0_INRIA_2004", "QPL_1_0" + , "Radvd", "Rdisc", "RHeCos_1_1", "RPL_1_1", "RPL_1_5", "RPSL_1_0", "RSA_MD", "RSCPL" + , "Ruby_pty", "Ruby", "SAX_PD_2_0", "SAX_PD", "Saxpath", "SCEA", "SchemeReport", "Sendmail_8_23" + , "Sendmail_Open_Source_1_1", "Sendmail", "SGI_B_1_0", "SGI_B_1_1", "SGI_B_2_0", "SGI_OpenGL", "SGMLUG_PM", "SGP4" + , "SHL_0_51", "SHL_0_5", "SimPL_2_0", "SISSL_1_2", "SISSL", "Sleepycat", "SL", "SMAIL_GPL" + , "SMLNJ", "SMPPL", "SNIA", "Snprintf", "SOFA", "SoftSurfer", "Soundex", "Spencer_86" + , "Spencer_94", "Spencer_99", "SPL_1_0", "Ssh_keyscan", "SSH_OpenSSH", "SSH_short", "SSLeay_standalone", "SSPL_1_0" + , "SugarCRM_1_1_3", "SUL_1_0", "Sun_PPP_2000", "Sun_PPP", "SunPro", "SWL", "Swrule", "Symlinks" + , "TAPR_OHL_1_0", "TCL", "TCP_wrappers", "TekHVC", "TermReadKey", "TGPPL_1_0", "ThirdEye", "Threeparttable" + , "TMate", "TORQUE_1_1", "TOSL", "TPDL", "TPL_1_0", "TrustedQSL", "TTWL", "TTYP0" + , "TU_Berlin_1_0", "TU_Berlin_2_0", "Ubuntu_font_1_0", "UCAR", "UCL_1_0", "Ulem", "UMich_Merit", "Unicode_3_0" + , "Unicode_DFS_2015", "Unicode_DFS_2016", "Unicode_TOU", "UnixCrypt", "Unlicense_libtelnet", "Unlicense_libwhirlpool", "Unlicense", "UnRAR" + , "UPL_1_0", "URT_RLE", "Vim", "Vixie_Cron", "VOSTROM", "VSL_1_0", "W3C_19980720", "W3C_20150513" + , "W3C", "W3m", "Watcom_1_0", "Widget_Workshop", "WordNet", "Wsuipa", "WTFNMFPL", "WTFPL" + , "Wwl", "X11_distribute_modifications_variant", "X11_no_permit_persons", "X11_swapped", "X11", "Xdebug_1_03", "Xerox", "Xfig" + , "XFree86_1_1", "Xinetd", "Xkeyboard_config_Zinoviev", "Xlock", "Xnet", "Xpp", "XSkat", "Xzoom" + , "YPL_1_0", "YPL_1_1", "Zed", "Zeeff", "Zend_2_0", "Zimbra_1_3", "Zimbra_1_4", "Zlib_acknowledgement" + , "Zlib", "ZPL_1_1", "ZPL_2_0", "ZPL_2_1" ] +#endif + -- note: remember to bump version each time the definition changes instance Structured LicenseId where structure p = set typeVersion 308 $ nominalStructure p diff --git a/Cabal-syntax/src/Distribution/Types/BenchmarkInterface.hs b/Cabal-syntax/src/Distribution/Types/BenchmarkInterface.hs index 15d6ebcecd1..c3f8fc3ff6e 100644 --- a/Cabal-syntax/src/Distribution/Types/BenchmarkInterface.hs +++ b/Cabal-syntax/src/Distribution/Types/BenchmarkInterface.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.BenchmarkInterface ( BenchmarkInterface (..) ) where diff --git a/Cabal-syntax/src/Distribution/Types/BuildInfo.hs b/Cabal-syntax/src/Distribution/Types/BuildInfo.hs index 99f030d8e14..149c19d7943 100644 --- a/Cabal-syntax/src/Distribution/Types/BuildInfo.hs +++ b/Cabal-syntax/src/Distribution/Types/BuildInfo.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.BuildInfo ( BuildInfo (..) , emptyBuildInfo diff --git a/Cabal-syntax/src/Distribution/Types/BuildInfo/Lens.hs b/Cabal-syntax/src/Distribution/Types/BuildInfo/Lens.hs index 72cfebb865d..8365d83339d 100644 --- a/Cabal-syntax/src/Distribution/Types/BuildInfo/Lens.hs +++ b/Cabal-syntax/src/Distribution/Types/BuildInfo/Lens.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.BuildInfo.Lens ( BuildInfo , HasBuildInfo (..) diff --git a/Cabal-syntax/src/Distribution/Types/ComponentId.hs b/Cabal-syntax/src/Distribution/Types/ComponentId.hs index 736ec31c592..6560a947803 100644 --- a/Cabal-syntax/src/Distribution/Types/ComponentId.hs +++ b/Cabal-syntax/src/Distribution/Types/ComponentId.hs @@ -62,7 +62,7 @@ instance Pretty ComponentId where instance Parsec ComponentId where parsec = mkComponentId `fmap` P.munch1 abi_char where - abi_char c = isAlphaNum c || c `elem` "-_." + abi_char c = isAlphaNum c || c `elem` ['-', '_', '.'] instance NFData ComponentId where rnf = rnf . unComponentId diff --git a/Cabal-syntax/src/Distribution/Types/CondTree.hs b/Cabal-syntax/src/Distribution/Types/CondTree.hs index 5569d54666d..b69538c2337 100644 --- a/Cabal-syntax/src/Distribution/Types/CondTree.hs +++ b/Cabal-syntax/src/Distribution/Types/CondTree.hs @@ -1,3 +1,6 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE StandaloneDeriving #-} + module Distribution.Types.CondTree ( CondTree (..) , CondBranch (..) @@ -17,6 +20,7 @@ module Distribution.Types.CondTree , ignoreConditions ) where +import Data.Foldable (Foldable) import Distribution.Compat.Prelude import Prelude () @@ -52,7 +56,17 @@ data CondTree v a = CondNode { condTreeData :: a , condTreeComponents :: [CondBranch v a] } - deriving (Show, Eq, Data, Generic, Functor, Foldable, Traversable) + deriving (Show, Eq, Generic, Functor, Foldable, Traversable +#ifndef __MHS__ + , Data +#endif + ) + +#ifdef __MHS__ +-- MicroHs cannot derive 'Data' for parameterised types (it drops the +-- required context), so the instances are spelled out explicitly. +deriving instance (Data v, Data a) => Data (CondTree v a) +#endif instance (Binary v, Binary a) => Binary (CondTree v a) instance (Structured v, Structured a) => Structured (CondTree v a) @@ -72,7 +86,15 @@ data CondBranch v a = CondBranch , condBranchIfTrue :: CondTree v a , condBranchIfFalse :: Maybe (CondTree v a) } - deriving (Show, Eq, Data, Generic, Functor, Traversable, Foldable) + deriving (Show, Eq, Generic, Functor, Traversable, Foldable +#ifndef __MHS__ + , Data +#endif + ) + +#ifdef __MHS__ +deriving instance (Data v, Data a) => Data (CondBranch v a) +#endif instance (Binary v, Binary a) => Binary (CondBranch v a) instance (Structured v, Structured a) => Structured (CondBranch v a) diff --git a/Cabal-syntax/src/Distribution/Types/Condition.hs b/Cabal-syntax/src/Distribution/Types/Condition.hs index cca96594890..375c162a0ee 100644 --- a/Cabal-syntax/src/Distribution/Types/Condition.hs +++ b/Cabal-syntax/src/Distribution/Types/Condition.hs @@ -1,3 +1,6 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE StandaloneDeriving #-} + module Distribution.Types.Condition ( Condition (..) , cNot @@ -6,6 +9,7 @@ module Distribution.Types.Condition , simplifyCondition ) where +import Data.Foldable (Foldable) import Distribution.Compat.Prelude import Prelude () @@ -16,7 +20,17 @@ data Condition c | CNot (Condition c) | COr (Condition c) (Condition c) | CAnd (Condition c) (Condition c) - deriving (Show, Eq, Data, Generic) + deriving (Show, Eq, Generic +#ifndef __MHS__ + , Data +#endif + ) + +#ifdef __MHS__ +-- MicroHs cannot derive 'Data' for parameterised types (it drops the +-- required context), so the instance is spelled out explicitly. +deriving instance Data c => Data (Condition c) +#endif -- | Boolean negation of a 'Condition' value. cNot :: Condition a -> Condition a diff --git a/Cabal-syntax/src/Distribution/Types/Executable.hs b/Cabal-syntax/src/Distribution/Types/Executable.hs index e49535718ae..f069e69d410 100644 --- a/Cabal-syntax/src/Distribution/Types/Executable.hs +++ b/Cabal-syntax/src/Distribution/Types/Executable.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.Executable ( Executable (..) , emptyExecutable diff --git a/Cabal-syntax/src/Distribution/Types/Executable/Lens.hs b/Cabal-syntax/src/Distribution/Types/Executable/Lens.hs index 3683522ac8d..5678683b020 100644 --- a/Cabal-syntax/src/Distribution/Types/Executable/Lens.hs +++ b/Cabal-syntax/src/Distribution/Types/Executable/Lens.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.Executable.Lens ( Executable , module Distribution.Types.Executable.Lens diff --git a/Cabal-syntax/src/Distribution/Types/ForeignLib.hs b/Cabal-syntax/src/Distribution/Types/ForeignLib.hs index 85a5cb44e40..fada204512e 100644 --- a/Cabal-syntax/src/Distribution/Types/ForeignLib.hs +++ b/Cabal-syntax/src/Distribution/Types/ForeignLib.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.ForeignLib ( ForeignLib (..) , emptyForeignLib diff --git a/Cabal-syntax/src/Distribution/Types/ForeignLib/Lens.hs b/Cabal-syntax/src/Distribution/Types/ForeignLib/Lens.hs index b7f4fee3197..d1433f3fe67 100644 --- a/Cabal-syntax/src/Distribution/Types/ForeignLib/Lens.hs +++ b/Cabal-syntax/src/Distribution/Types/ForeignLib/Lens.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.ForeignLib.Lens ( ForeignLib , module Distribution.Types.ForeignLib.Lens diff --git a/Cabal-syntax/src/Distribution/Types/InstalledPackageInfo.hs b/Cabal-syntax/src/Distribution/Types/InstalledPackageInfo.hs index 15cedf8ec7e..ee4535e492e 100644 --- a/Cabal-syntax/src/Distribution/Types/InstalledPackageInfo.hs +++ b/Cabal-syntax/src/Distribution/Types/InstalledPackageInfo.hs @@ -1,5 +1,4 @@ {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeFamilies #-} module Distribution.Types.InstalledPackageInfo ( InstalledPackageInfo (..) @@ -113,8 +112,7 @@ instance Package.HasUnitId InstalledPackageInfo where instance Package.PackageInstalled InstalledPackageInfo where installedDepends = depends -instance IsNode InstalledPackageInfo where - type Key InstalledPackageInfo = UnitId +instance IsNode UnitId InstalledPackageInfo where nodeKey = installedUnitId nodeNeighbors = depends diff --git a/Cabal-syntax/src/Distribution/Types/InstalledPackageInfo/FieldGrammar.hs b/Cabal-syntax/src/Distribution/Types/InstalledPackageInfo/FieldGrammar.hs index 691f0e2b0d6..1c1000c8634 100644 --- a/Cabal-syntax/src/Distribution/Types/InstalledPackageInfo/FieldGrammar.hs +++ b/Cabal-syntax/src/Distribution/Types/InstalledPackageInfo/FieldGrammar.hs @@ -1,4 +1,5 @@ {-# LANGUAGE ApplicativeDo #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} @@ -52,24 +53,30 @@ infixl 4 <@> f <@> x = f <*> x {-# NOINLINE (<@>) #-} +-- MicroHs supports tuples only up to 15 elements, so the 17-part +-- constraint is nested into two smaller tuples. Both GHC and MicroHs +-- accept nested constraint tuples; the meaning is identical to the +-- flat tuple: conjunction of the same constraints. ipiFieldGrammar - :: ( FieldGrammar c g - , c (Identity AbiHash) - , c (Identity LibraryVisibility) - , c (Identity PackageName) - , c (Identity UnitId) - , c (Identity UnqualComponentName) - , c (List FSep (Identity AbiDependency) AbiDependency) - , c (List FSep (Identity UnitId) UnitId) - , c (List FSep (MQuoted ModuleName) ModuleName) - , c (List FSep FilePathNT String) - , c (List FSep Token Text) - , c (MQuoted MungedPackageName) - , c (MQuoted Version) - , c CompatPackageKey - , c ExposedModules - , c InstWith - , c SpecLicenseLenient + :: ( ( FieldGrammar c g + , c (Identity AbiHash) + , c (Identity LibraryVisibility) + , c (Identity PackageName) + , c (Identity UnitId) + , c (Identity UnqualComponentName) + , c (List FSep (Identity AbiDependency) AbiDependency) + , c (List FSep (Identity UnitId) UnitId) + , c (List FSep (MQuoted ModuleName) ModuleName) + ) + , ( c (List FSep FilePathNT String) + , c (List FSep Token Text) + , c (MQuoted MungedPackageName) + , c (MQuoted Version) + , c CompatPackageKey + , c ExposedModules + , c InstWith + , c SpecLicenseLenient + ) ) => g InstalledPackageInfo InstalledPackageInfo ipiFieldGrammar = @@ -297,6 +304,36 @@ basicFieldGrammar , c (MQuoted Version) ) => g Basic Basic +#ifdef __MHS__ +-- MicroHs does not implement ApplicativeDo, so the do-block below is +-- spelled out with explicit Applicative combinators. Semantics are +-- identical to the ApplicativeDo desugaring GHC performs. +basicFieldGrammar = + mkBasic + <$> optionalFieldDefAla "name" MQuoted basicName (mungedPackageName emptyInstalledPackageInfo) + <*> optionalFieldDefAla "version" MQuoted basicVersion nullVersion + <*> optionalField "package-name" basicPkgName + <*> (maybe LMainLibName LSubLibName <$> optionalField "lib-name" basicLibName) + <*> optionalFieldDef "visibility" basicLibVisibility LibraryVisibilityPrivate + where + mkBasic _basicName _basicVersion _basicPkgName _basicLibName _basicLibVisibility' = + Basic + { -- 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. + _basicLibVisibility = + if let MungedPackageName _ mln = _basicName + in -- We need to check both because on ghc<8.2 _basicLibName will always + -- be LMainLibName + _basicLibName == LMainLibName && mln == LMainLibName + then LibraryVisibilityPublic + else _basicLibVisibility' + , .. + } +#else basicFieldGrammar = do _basicName <- optionalFieldDefAla "name" MQuoted basicName (mungedPackageName emptyInstalledPackageInfo) _basicVersion <- optionalFieldDefAla "version" MQuoted basicVersion nullVersion @@ -321,6 +358,8 @@ basicFieldGrammar = do , .. } +#endif + fromTextLens :: Lens' Text String fromTextLens f = fmap T.pack . f . T.unpack {-# INLINE fromTextLens #-} diff --git a/Cabal-syntax/src/Distribution/Types/PackageDescription.hs b/Cabal-syntax/src/Distribution/Types/PackageDescription.hs index f824604e155..e0bd8fcbce0 100644 --- a/Cabal-syntax/src/Distribution/Types/PackageDescription.hs +++ b/Cabal-syntax/src/Distribution/Types/PackageDescription.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Types.PackageDescription -- Copyright : Isaac Jones 2003-2005 diff --git a/Cabal-syntax/src/Distribution/Types/PackageDescription/Lens.hs b/Cabal-syntax/src/Distribution/Types/PackageDescription/Lens.hs index 02de5bde241..983135b351f 100644 --- a/Cabal-syntax/src/Distribution/Types/PackageDescription/Lens.hs +++ b/Cabal-syntax/src/Distribution/Types/PackageDescription/Lens.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.PackageDescription.Lens ( PackageDescription , module Distribution.Types.PackageDescription.Lens diff --git a/Cabal-syntax/src/Distribution/Types/TestSuiteInterface.hs b/Cabal-syntax/src/Distribution/Types/TestSuiteInterface.hs index 05f3b6a2036..a3d4abb7d87 100644 --- a/Cabal-syntax/src/Distribution/Types/TestSuiteInterface.hs +++ b/Cabal-syntax/src/Distribution/Types/TestSuiteInterface.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Types.TestSuiteInterface ( TestSuiteInterface (..) ) where diff --git a/Cabal-syntax/src/Distribution/Types/VersionRange/Internal.hs b/Cabal-syntax/src/Distribution/Types/VersionRange/Internal.hs index 742698db3a2..87f2dfb6482 100644 --- a/Cabal-syntax/src/Distribution/Types/VersionRange/Internal.hs +++ b/Cabal-syntax/src/Distribution/Types/VersionRange/Internal.hs @@ -32,8 +32,9 @@ module Distribution.Types.VersionRange.Internal , wildcardUpperBound ) where +import Data.Foldable (Foldable, foldr1) import Data.Functor (($>)) -import Distribution.Compat.Prelude +import Distribution.Compat.Prelude hiding (foldr1) import Distribution.Types.Version import Prelude () diff --git a/Cabal-syntax/src/Distribution/Utils/Base62.hs b/Cabal-syntax/src/Distribution/Utils/Base62.hs index 757528e750f..1cd8c2f6d5e 100644 --- a/Cabal-syntax/src/Distribution/Utils/Base62.hs +++ b/Cabal-syntax/src/Distribution/Utils/Base62.hs @@ -1,9 +1,14 @@ +{-# LANGUAGE CPP #-} -- | Implementation of base-62 encoding, which we use when computing hashes -- for fully instantiated unit ids. module Distribution.Utils.Base62 (hashToBase62) where import Data.Char (chr) +#ifdef __MHS__ +import Distribution.Utils.MD5 (Fingerprint (..), fingerprintString) +#else import GHC.Fingerprint (Fingerprint (..), fingerprintString) +#endif import Numeric (showIntAtBase) -- | Hash a string using GHC's fingerprinting algorithm (a 128-bit diff --git a/Cabal-syntax/src/Distribution/Utils/Generic.hs b/Cabal-syntax/src/Distribution/Utils/Generic.hs index 0d95147a2eb..af46afb860f 100644 --- a/Cabal-syntax/src/Distribution/Utils/Generic.hs +++ b/Cabal-syntax/src/Distribution/Utils/Generic.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- | -- Module : Distribution.Utils.Generic -- Copyright : Isaac Jones, Simon Marlow 2003-2004 @@ -97,12 +98,16 @@ import qualified Data.Text.Encoding.Error as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import GHC.IO.Exception (IOErrorType (UnsupportedOperation)) -import System.Directory +import Distribution.Compat.Directory ( copyFile , getTemporaryDirectory , removeFile , renameFile ) +import Distribution.Compat.Internal.LazyByteString + ( hGetContentsLBS + , readFileLBS + ) import System.FilePath ( takeFileName , (<.>) @@ -111,7 +116,13 @@ import System.IO ( IOMode (ReadMode) , hClose , hGetContents +#ifndef __MHS__ + -- MicroHs lacks this; a compatible replacement is defined below. , openBinaryTempFileWithDefaultPermissions +#else + , Handle + , openBinaryTempFile +#endif , withBinaryFile , withFile ) @@ -180,6 +191,13 @@ withFileContents name action = withFile name ReadMode (hGetContents >=> action) -- - If the temp directory (@TMP@/@TEMP@/..., see haddocks on -- 'getTemporaryDirectory') is in a different drive than the destination path, -- the write will be emulated via 'copyFile', then 'deleteFile'. +#ifdef __MHS__ +-- MicroHs has no 'System.IO.openBinaryTempFileWithDefaultPermissions'; +-- its 'openBinaryTempFile' already creates files with default +-- permissions, so it is used directly. +openBinaryTempFileWithDefaultPermissions :: FilePath -> String -> IO (FilePath, Handle) +openBinaryTempFileWithDefaultPermissions = openBinaryTempFile +#endif writeFileAtomic :: FilePath -> LBS.ByteString -> IO () writeFileAtomic targetPath content = do let targetFile = takeFileName targetPath @@ -299,7 +317,7 @@ ignoreBOM string = string -- -- Reads lazily using ordinary 'readFile'. readUTF8File :: FilePath -> IO String -readUTF8File f = ignoreBOM . fromUTF8LBS <$> LBS.readFile f +readUTF8File f = ignoreBOM . fromUTF8LBS <$> readFileLBS f -- | Reads a UTF8 encoded text file as a Unicode String -- @@ -309,7 +327,7 @@ withUTF8FileContents name action = withBinaryFile name ReadMode - (LBS.hGetContents >=> action . ignoreBOM . fromUTF8LBS) + (hGetContentsLBS >=> action . ignoreBOM . fromUTF8LBS) -- | Writes a Unicode String as a UTF8 encoded text file. -- diff --git a/Cabal-syntax/src/Distribution/Utils/MD5.hs b/Cabal-syntax/src/Distribution/Utils/MD5.hs index ea3c5a52485..a4903f6c0fa 100644 --- a/Cabal-syntax/src/Distribution/Utils/MD5.hs +++ b/Cabal-syntax/src/Distribution/Utils/MD5.hs @@ -1,7 +1,11 @@ +{-# LANGUAGE CPP #-} + module Distribution.Utils.MD5 ( MD5 + , Fingerprint (..) , showMD5 , md5 + , fingerprintString -- * Helpers , md5FromInteger @@ -16,13 +20,36 @@ import Data.Binary.Get (getWord64le) import Data.Binary.Put (putWord64le) import Data.Bits (complement, shiftR, (.&.)) import Foreign.Ptr (castPtr) -import GHC.Fingerprint (Fingerprint (..), fingerprintData) +#ifndef __MHS__ +import GHC.Fingerprint (Fingerprint (..), fingerprintData, fingerprintString) +#endif +#ifdef __MHS__ +import Data.Char (ord) +#endif import Numeric (showHex) import System.IO.Unsafe (unsafeDupablePerformIO) import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BS +#ifdef __MHS__ +import Control.Exception (bracket) +import Data.Word (Word8, Word64) +import Distribution.Compat.Directory (getTemporaryDirectory, removeFile) +import Foreign.Marshal.Array (allocaArray) +import Foreign.Ptr (Ptr) +import Foreign.Storable (peekElemOff, poke) +import System.IO (hClose, openTempFile) +import System.IO.Error (catchIOError) +import System.IO.MD5 (MD5CheckSum, md5File) + +-- | MicroHS does not provide 'GHC.Fingerprint', so we define our own +-- fingerprint type with the same two-word layout. The first word holds the +-- first eight digest bytes (big-endian) and the second word the last eight, +-- matching the 'GHC.Fingerprint' order observed through 'showMD5'. +data Fingerprint = Fingerprint !Word64 !Word64 deriving (Eq, Ord) +#endif + type MD5 = Fingerprint -- | Show 'MD5' in human readable form @@ -43,8 +70,73 @@ showMD5 (Fingerprint a b) = pad a' ++ pad b' -- | @since 3.2.0.0 md5 :: BS.ByteString -> MD5 +#ifdef __MHS__ +-- MicroHS has no 'GHC.Fingerprint.fingerprintData', so the digest is +-- computed by the @md5Array@ function from the MicroHS runtime through our +-- own 'foreign import'. If hashing the input buffer fails, we fall back to +-- spilling the input to a temporary file and hashing that instead. +md5 bs = unsafeDupablePerformIO $ + md5Buffer bs `catchIOError` \_ -> md5TempFile bs + +-- | Hash the input bytes directly with the @md5Array@ runtime function. +foreign import ccall "md5Array" c_md5Array :: Ptr Word8 -> Ptr Word64 -> Int -> IO () + +md5Buffer :: BS.ByteString -> IO MD5 +md5Buffer bs = + BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> + allocaArray 2 $ \out -> do + c_md5Array (castPtr ptr) out len + fromDigestBytes <$> mapM (peekElemOff (castPtr out)) [0 .. 15] + +-- | Fallback: spill the input to a temporary file and hash the file with +-- the runtime's file hashing ('System.IO.MD5.md5File'). +md5TempFile :: BS.ByteString -> IO MD5 +md5TempFile bs = do + tmpdir <- getTemporaryDirectory + bracket + (openTempFile tmpdir "cabal-md5") + (\(path, h) -> (hClose h `catchIOError` \_ -> pure ()) >> removeFile path) + (\(path, h) -> do + BS.hPut h bs + hClose h + mcs <- md5File path + case mcs of + Nothing -> ioError (userError "Distribution.Utils.MD5.md5: md5File failed") + Just cs -> checksumToFingerprint cs) + +-- | Convert a runtime checksum to a 'Fingerprint' by reading out its 16 +-- digest bytes in order. +checksumToFingerprint :: MD5CheckSum -> IO MD5 +checksumToFingerprint cs = + allocaArray 16 $ \out -> do + poke (castPtr out) cs + fromDigestBytes <$> mapM (peekElemOff out) [0 .. 15] + +-- | Split 16 digest bytes into two big-endian words, matching the word +-- order 'GHC.Fingerprint' exposes through 'showMD5'. +fromDigestBytes :: [Word8] -> MD5 +fromDigestBytes ws = + case splitAt 8 ws of + (hi, lo) -> Fingerprint (fromBE hi) (fromBE lo) + where + fromBE = foldl (\a b -> a * 256 + fromIntegral b) 0 +#else md5 bs = unsafeDupablePerformIO $ BS.unsafeUseAsCStringLen bs $ \(ptr, len) -> fingerprintData (castPtr ptr) len +#endif + +#ifdef __MHS__ +-- | Hash a 'String' exactly like 'GHC.Fingerprint.fingerprintString': +-- MD5 over the UTF-32BE encoding of the string, split big-endian +-- into two 'Word64's. Verified byte-identical against GHC output. +fingerprintString :: String -> Fingerprint +fingerprintString = md5 . BS.pack . concatMap w32be + where + w32be c = [byte 24, byte 16, byte 8, byte 0] + where + o = ord c + byte s = fromIntegral ((o `shiftR` s) .&. 0xff) :: Word8 +#endif -- | @since 3.2.0.0 binaryPutMD5 :: MD5 -> Put diff --git a/Cabal-syntax/src/Distribution/Utils/Path.hs b/Cabal-syntax/src/Distribution/Utils/Path.hs index 8f15460513f..807f694389d 100644 --- a/Cabal-syntax/src/Distribution/Utils/Path.hs +++ b/Cabal-syntax/src/Distribution/Utils/Path.hs @@ -1,13 +1,16 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE RoleAnnotations #-} -{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Distribution.Utils.Path ( -- * Symbolic path endpoints - FileOrDir (..) - , AllowAbsolute (..) + FileOrDir + , File + , Dir + , AllowAbsolute + , OnlyRelative -- ** Abstract directory locations , CWD @@ -69,6 +72,7 @@ import Distribution.Compat.Prelude import Prelude () import Data.Coerce +import Data.Kind (Type) import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as ModuleName @@ -80,18 +84,22 @@ import Distribution.Utils.Generic (isAbsoluteOnAnyPlatform) import qualified Distribution.Compat.CharParsing as P -import qualified System.Directory as Directory +import qualified Distribution.Compat.Directory as Directory import qualified System.FilePath as FilePath -import Data.Kind - ( Type - ) import Data.List ( stripPrefix ) +#ifdef __MHS__ +-- MicroHs has no 'GHC.Stack'; the 'HasCallStack' constraint on +-- 'makeRelativePathEx' is vestigial there. +class HasCallStack +instance HasCallStack +#else import GHC.Stack ( HasCallStack ) +#endif ------------------------------------------------------------------------------- @@ -159,16 +167,19 @@ In practice, we often use: Note [Symbolic relative paths] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -This module defines: +This module defines plain phantom marker types (no @DataKinds@ +promotion, so this module stays parsable by MicroHs): - data kind AllowAbsolute = AllowAbsolute | OnlyRelative - data kind FileOrDir = File | Dir Symbol + data File + data Dir (dir :: Type) + data AllowAbsolute + data OnlyRelative - type SymbolicPathX :: AllowAbsolute -> Symbol -> FileOrDir -> Type - newtype SymbolicPathX allowAbsolute from to = SymbolicPath FilePath + newtype SymbolicPathX (allowAbsolute :: Type) (from :: Type) (to :: Type) + = SymbolicPath FilePath - type RelativePath = SymbolicPathX 'OnlyRelative - type SymbolicPath = SymbolicPathX 'AllowAbsolute + type RelativePath = SymbolicPathX OnlyRelative + type SymbolicPath = SymbolicPathX AllowAbsolute A 'SymbolicPath' is thus a symbolic path that is allowed to be absolute, whereas a 'RelativePath' is a symbolic path that is additionally required to be relative. @@ -177,30 +188,56 @@ This distinction allows us to keep track of which filepaths must be kept relative. -} --- | A type-level symbolic name, to an abstract file or directory --- (e.g. the Cabal package directory). -data FileOrDir - = -- | A file (with no further information). - File - | -- | The abstract name of a directory or category of directories, - -- e.g. the package directory or a source directory. - Dir Type - --- | Is this symbolic path allowed to be absolute, or must it be relative? -data AllowAbsolute - = -- | The path may be absolute, or it may be relative. - AllowAbsolute - | -- | The path must be relative. - OnlyRelative +-- | Phantom marker for 'SymbolicPathX': the path refers to a file. +data File deriving Data + +-- | Phantom marker for 'SymbolicPathX': the path refers to a +-- directory or category of directories, e.g. the package directory +-- or a source directory. The parameter names which directory. +data Dir (dir :: Type) +#ifndef __MHS__ + deriving Data +#endif + +#ifdef __MHS__ +-- MicroHs cannot derive 'Data' for parameterised types (it drops the +-- required context), so the instance is spelled out explicitly. +deriving instance Data dir => Data (Dir dir) +#endif + +-- | Phantom marker for 'SymbolicPathX': the path may be absolute, +-- or it may be relative. +data AllowAbsolute deriving Data + +-- | Phantom marker for 'SymbolicPathX': the path must be relative. +data OnlyRelative deriving Data + +-- | Compatibility shim: 'FileOrDir' used to be a datatype whose +-- constructors were promoted to the type level with @DataKinds@. +-- The markers are now the plain types above; this empty datatype is +-- kept so that existing @FileOrDir (..)@ imports keep working. +data FileOrDir deriving Data -- | A symbolic path, possibly relative to an abstract location specified -- by the @from@ type parameter. -- -- They are *symbolic*, which means we cannot perform any 'IO' -- until we interpret them (using e.g. 'interpretSymbolicPath'). -newtype SymbolicPathX (allowAbsolute :: AllowAbsolute) (from :: Type) (to :: FileOrDir) +newtype SymbolicPathX (allowAbsolute :: Type) (from :: Type) (to :: Type) = SymbolicPath FilePath - deriving (Generic, Show, Read, Eq, Ord, Data) + deriving (Generic, Show, Read, Eq, Ord +#ifndef __MHS__ + , Data +#endif + ) + +#ifdef __MHS__ +-- MicroHs cannot derive 'Data' for parameterised types (it drops the +-- required context), so the instance is spelled out explicitly. +deriving instance + (Data allowAbsolute, Data from, Data to) => + Data (SymbolicPathX allowAbsolute from to) +#endif type role SymbolicPathX nominal nominal nominal @@ -209,15 +246,15 @@ type role SymbolicPathX nominal nominal nominal -- -- They are *symbolic*, which means we cannot perform any 'IO' -- until we interpret them (using e.g. 'interpretSymbolicPath'). -type RelativePath = SymbolicPathX 'OnlyRelative +type RelativePath = SymbolicPathX OnlyRelative -- | A symbolic path which is allowed to be absolute. -- -- They are *symbolic*, which means we cannot perform any 'IO' -- until we interpret them (using e.g. 'interpretSymbolicPath'). -type SymbolicPath = SymbolicPathX 'AllowAbsolute +type SymbolicPath = SymbolicPathX AllowAbsolute -newtype AbsolutePath (to :: FileOrDir) = AbsolutePath (forall from. SymbolicPath from to) +newtype AbsolutePath to = AbsolutePath (forall (from :: Type). SymbolicPath from to) unsafeMakeAbsolutePath :: FilePath -> AbsolutePath to unsafeMakeAbsolutePath fp = AbsolutePath (makeSymbolicPath fp) @@ -392,7 +429,7 @@ tryMakeRelative mbWorkDir (SymbolicPath fp) = do ------------------------------------------------------------------------------- -instance Parsec (SymbolicPathX 'OnlyRelative from to) where +instance Parsec (SymbolicPathX OnlyRelative from to) where parsec = do token <- parsecToken if null token @@ -402,7 +439,7 @@ instance Parsec (SymbolicPathX 'OnlyRelative from to) where then P.unexpected "absolute FilePath" else return (SymbolicPath token) -instance Parsec (SymbolicPathX 'AllowAbsolute from to) where +instance Parsec (SymbolicPathX AllowAbsolute from to) where parsec = do token <- parsecToken if null token @@ -428,7 +465,7 @@ class FileLike p where instance FileLike FilePath where (<.>) = (FilePath.<.>) -instance p ~ File => FileLike (SymbolicPathX allowAbsolute dir p) where +instance FileLike (SymbolicPathX allowAbsolute dir File) where SymbolicPath p <.> ext = SymbolicPath (p <.> ext) infixr 5 @@ -446,7 +483,7 @@ instance PathLike FilePath FilePath FilePath where -- -- (Recall that @a b = b@ whenever @b@ is absolute.) instance - (b1 ~ 'Dir b2, a3 ~ a1, c2 ~ c3, midAbsolute ~ OnlyRelative) + (b1 ~ Dir b2, a3 ~ a1, c2 ~ c3, midAbsolute ~ OnlyRelative) => PathLike (SymbolicPathX allowAbsolute a1 b1) (SymbolicPathX midAbsolute b2 c2) @@ -455,7 +492,7 @@ instance SymbolicPath p1 SymbolicPath p2 = SymbolicPath (p1 p2) instance - (b1 ~ 'Dir b2, c2 ~ c3, midAbsolute ~ OnlyRelative) + (b1 ~ Dir b2, c2 ~ c3, midAbsolute ~ OnlyRelative) => PathLike (AbsolutePath b1) (SymbolicPathX midAbsolute b2 c2) @@ -470,79 +507,79 @@ instance -- | Abstract directory: current working directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data CWD +data CWD deriving Data -- | Abstract directory: package directory (e.g. a directory containing the @.cabal@ file). -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Pkg +data Pkg deriving Data -- | Abstract directory: dist directory (e.g. @dist-newstyle@). -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Dist +data Dist deriving Data -- | Abstract directory: source directory (a search directory for source files). -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Source +data Source deriving Data -- | Abstract directory: include directory (a search directory for CPP includes like header files, e.g. with @ghc -I@). -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Include +data Include deriving Data -- | Abstract directory: search directory for extra libraries. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Lib +data Lib deriving Data -- | Abstract directory: MacOS framework directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Framework +data Framework deriving Data -- | Abstract directory: build directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Build +data Build deriving Data -- | Abstract directory: directory for build artifacts, such as documentation or @.hie@ files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Artifacts +data Artifacts deriving Data -- | Abstract directory: package database directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data PkgDB +data PkgDB deriving Data -- | Abstract directory: data files directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data DataDir +data DataDir deriving Data -- | Abstract directory: directory for HPC @.mix@ files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Mix +data Mix deriving Data -- | Abstract directory: directory for HPC @.tix@ files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Tix +data Tix deriving Data -- | Abstract directory: a temporary directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Tmp +data Tmp deriving Data -- | Abstract directory: directory for response files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Response +data Response deriving Data -- | Abstract directory: directory for pkg-config files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data PkgConf +data PkgConf deriving Data diff --git a/Cabal-syntax/src/Distribution/Utils/String.hs b/Cabal-syntax/src/Distribution/Utils/String.hs index 1756d74a462..97a8eb41471 100644 --- a/Cabal-syntax/src/Distribution/Utils/String.hs +++ b/Cabal-syntax/src/Distribution/Utils/String.hs @@ -2,8 +2,8 @@ module Distribution.Utils.String ( trim ) where +import Data.Char (isSpace) import Data.List (dropWhileEnd) -import GHC.Unicode (isSpace) -- @since 3.8.0.0 trim :: String -> String diff --git a/Cabal-syntax/src/Distribution/Utils/Structured.hs b/Cabal-syntax/src/Distribution/Utils/Structured.hs index ad70892e498..e2fe7fd2e1b 100644 --- a/Cabal-syntax/src/Distribution/Utils/Structured.hs +++ b/Cabal-syntax/src/Distribution/Utils/Structured.hs @@ -1,6 +1,5 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE DefaultSignatures #-} -{-# LANGUAGE TypeFamilies #-} -- | -- @@ -49,8 +48,10 @@ module Distribution.Utils.Structured , MD5 , structureHash , structureBuilder +#ifndef __MHS__ , genericStructure , GStructured +#endif , nominalStructure , containerStructure @@ -91,6 +92,7 @@ import qualified Data.Text as T import qualified Data.Text.Lazy as LT import qualified Data.Time as Time import qualified Distribution.Compat.Binary as Binary +import Distribution.Compat.Internal.LazyByteString (readFileLBS) #ifdef MIN_VERSION_aeson import qualified Data.Aeson as Aeson @@ -98,6 +100,9 @@ import qualified Data.Aeson as Aeson import Data.Kind (Type) import Data.Typeable (TypeRep, Typeable, typeRep) +#ifdef __MHS__ +import Data.Typeable (_mkTyCon) +#endif import Distribution.Utils.MD5 @@ -222,19 +227,35 @@ structureBuilder s0 = State.evalState (go s0) Map.empty -- @since 3.2.0.0 class Typeable a => Structured a where structure :: Proxy a -> Structure +#ifdef __MHS__ + -- MicroHs has no GHC.Generics metadata ('Datatype' etc.), so the + -- generic default below is unavailable; instances without an explicit + -- method throw if called at runtime. + structure = error "Distribution.Utils.Structured.structure: generic structures are not supported under MicroHs" +#else default structure :: GStructured (Rep a) => Proxy a -> Structure structure = genericStructure +#endif +#ifndef __MHS__ -- This member is hidden. It's there to precalc structureHash' :: Tagged a MD5 structureHash' = Tagged (hashStructure (structure (Proxy :: Proxy a))) +#endif -- private Tagged newtype Tagged a b = Tagged {untag :: b} -- | Semantically @'hashStructure' . 'structure'@. structureHash :: forall a. Structured a => Proxy a -> MD5 +#ifdef __MHS__ +-- MicroHs does not provide the class constraint to default method +-- bodies, so the 'structureHash'' method cannot be implemented there; +-- inline its definition instead. +structureHash p = hashStructure (structure p) +#else structureHash _ = untag (structureHash' :: Tagged a MD5) +#endif ------------------------------------------------------------------------------- -- Functions @@ -272,7 +293,7 @@ structuredDecodeOrFailIO bs = -- | Lazily reconstruct a value previously written to a file. structuredDecodeFileOrFail :: (Binary.Binary a, Structured a) => FilePath -> IO (Either String a) -structuredDecodeFileOrFail f = structuredDecodeOrFailIO =<< LBS.readFile f +structuredDecodeFileOrFail f = structuredDecodeOrFailIO =<< readFileLBS f ------------------------------------------------------------------------------- -- Helper data @@ -294,11 +315,19 @@ instance Structured a => Binary.Binary (Tag a) where , showMD5 expected ] where +#ifdef __MHS__ + expected = hashStructure (structure (Proxy :: Proxy a)) +#else expected = untag (structureHash' :: Tagged a MD5) +#endif put _ = binaryPutMD5 expected where +#ifdef __MHS__ + expected = hashStructure (structure (Proxy :: Proxy a)) +#else expected = untag (structureHash' :: Tagged a MD5) +#endif ------------------------------------------------------------------------------- -- Smart constructors @@ -326,6 +355,10 @@ containerStructure _ = -- Generic ------------------------------------------------------------------------------- +#ifndef __MHS__ +-- MicroHs has no GHC.Generics metadata ('Datatype', 'Constructor', +-- 'Selector'), so none of the generic machinery below is available. + -- | Derive 'structure' generically. genericStructure :: forall a. (Typeable a, GStructured (Rep a)) => Proxy a -> Structure genericStructure _ = gstructured (typeRep (Proxy :: Proxy a)) (Proxy :: Proxy (Rep a)) 0 @@ -334,22 +367,22 @@ genericStructure _ = gstructured (typeRep (Proxy :: Proxy a)) (Proxy :: Proxy (R class GStructured (f :: Type -> Type) where gstructured :: TypeRep -> Proxy f -> TypeVersion -> Structure -instance (i ~ D, Datatype c, GStructuredSum f) => GStructured (M1 i c f) where +instance (Datatype c, GStructuredSum f) => GStructured (M1 D c f) where gstructured tr _ v = case sop of [(_, [s])] | isNewtype p -> Newtype tr v name s _ -> Structure tr v name sop where - p = undefined :: M1 i c f () + p = undefined :: M1 D c f () name = datatypeName p sop = gstructuredSum (Proxy :: Proxy f) [] class GStructuredSum (f :: Type -> Type) where gstructuredSum :: Proxy f -> SopStructure -> SopStructure -instance (i ~ C, Constructor c, GStructuredProd f) => GStructuredSum (M1 i c f) where +instance (Constructor c, GStructuredProd f) => GStructuredSum (M1 C c f) where gstructuredSum _ xs = (name, prod) : xs where - name = conName (undefined :: M1 i c f ()) + name = conName (undefined :: M1 C c f ()) prod = gstructuredProd (Proxy :: Proxy f) [] instance (GStructuredSum f, GStructuredSum g) => GStructuredSum (f :+: g) where @@ -363,7 +396,7 @@ instance GStructuredSum V1 where class GStructuredProd (f :: Type -> Type) where gstructuredProd :: Proxy f -> [Structure] -> [Structure] -instance (i ~ S, GStructuredProd f) => GStructuredProd (M1 i c f) where +instance GStructuredProd f => GStructuredProd (M1 S c f) where gstructuredProd _ = gstructuredProd (Proxy :: Proxy f) instance Structured c => GStructuredProd (K1 i c) where @@ -376,6 +409,7 @@ instance (GStructuredProd f, GStructuredProd g) => GStructuredProd (f :*: g) whe gstructuredProd _ xs = gstructuredProd (Proxy :: Proxy f) $ gstructuredProd (Proxy :: Proxy g) xs +#endif /* __MHS__ */ ------------------------------------------------------------------------------- -- instances @@ -418,6 +452,14 @@ instance Structured a => Structured (NonEmpty a) where structure = containerStru -- By defining our own instances the STuple2 identifier will be used in the hash and -- hence the same on all GHC versions. +#ifdef __MHS__ +-- MicroHs only provides 'Typeable' for tuples up to 5-tuples; the +-- 6- and 7-tuple 'Structured' instances below need these two, +-- written the same way as the ones in MicroHs's own Data.Typeable. +instance Typeable (,,,,,) where typeRep = _mkTyCon "Data.Tuple" ",,,,," +instance Typeable (,,,,,,) where typeRep = _mkTyCon "Data.Tuple" ",,,,,," +#endif + data STuple2 a b = STuple2 a b deriving (Generic) data STuple3 a b c = STuple3 a b c deriving (Generic) data STuple4 a b c d = STuple4 a b c d deriving (Generic) diff --git a/Cabal-tests/Cabal-tests.cabal b/Cabal-tests/Cabal-tests.cabal index 3fffcf3ff6b..37ce8bfe322 100644 --- a/Cabal-tests/Cabal-tests.cabal +++ b/Cabal-tests/Cabal-tests.cabal @@ -32,7 +32,9 @@ test-suite unit-tests Test.Laws UnitTests.Distribution.CabalSpecVersion UnitTests.Distribution.Compat.CopyFile + UnitTests.Distribution.Compat.Directory UnitTests.Distribution.Compat.Graph + UnitTests.Distribution.Compat.Prelude UnitTests.Distribution.Compat.Time UnitTests.Distribution.Described UnitTests.Distribution.PackageDescription.Check diff --git a/Cabal-tests/lib/Test/Utils/TempTestDir.hs b/Cabal-tests/lib/Test/Utils/TempTestDir.hs index 7b7faeb97a1..20bf8caf9de 100644 --- a/Cabal-tests/lib/Test/Utils/TempTestDir.hs +++ b/Cabal-tests/lib/Test/Utils/TempTestDir.hs @@ -14,7 +14,7 @@ import Control.Monad (unless, when) import Control.Monad.Catch ( bracket, MonadMask) import Control.Monad.IO.Class -import System.Directory +import Distribution.Compat.Directory import System.IO.Error import System.FilePath (()) import qualified System.Info (os) diff --git a/Cabal-tests/tests/CheckTests.hs b/Cabal-tests/tests/CheckTests.hs index dfc716f6e33..3894979037e 100644 --- a/Cabal-tests/tests/CheckTests.hs +++ b/Cabal-tests/tests/CheckTests.hs @@ -12,7 +12,7 @@ import Distribution.PackageDescription.Parsec (parseGenericPackageDescription) import Distribution.Parsec import Distribution.Parsec.Source import Distribution.Utils.Generic (fromUTF8BS, toUTF8BS) -import System.Directory (setCurrentDirectory) +import Distribution.Compat.Directory (setCurrentDirectory) import System.Environment (getArgs, withArgs) import System.FilePath (replaceExtension, ()) diff --git a/Cabal-tests/tests/HackageTests.hs b/Cabal-tests/tests/HackageTests.hs index e6468d7b161..bbbb6c06be8 100644 --- a/Cabal-tests/tests/HackageTests.hs +++ b/Cabal-tests/tests/HackageTests.hs @@ -30,7 +30,7 @@ import Distribution.Simple.Utils (fromUTF8BS, toUTF8BS) import Distribution.Fields.ParseResult import Distribution.Parsec.Source import Numeric (showFFloat) -import System.Directory (getXdgDirectory, XdgDirectory(XdgCache, XdgConfig), getAppUserDataDirectory, doesDirectoryExist) +import Distribution.Compat.Directory (getXdgDirectory, XdgDirectory(XdgCache, XdgConfig), getAppUserDataDirectory, doesDirectoryExist) import System.Environment (lookupEnv) import System.Exit (exitFailure) import System.FilePath (()) diff --git a/Cabal-tests/tests/ParserTests.hs b/Cabal-tests/tests/ParserTests.hs index a6e54ffafdf..be059fc565c 100644 --- a/Cabal-tests/tests/ParserTests.hs +++ b/Cabal-tests/tests/ParserTests.hs @@ -29,7 +29,7 @@ import Distribution.Parsec (PWarnType (..), PWarning (.. import Distribution.Pretty (prettyShow) import Distribution.Fields.ParseResult import Distribution.Utils.Generic (fromUTF8BS, toUTF8BS) -import System.Directory (setCurrentDirectory) +import Distribution.Compat.Directory (setCurrentDirectory) import System.Environment (getArgs, withArgs) import System.FilePath (replaceExtension, ()) import Distribution.Parsec.Source diff --git a/Cabal-tests/tests/UnitTests.hs b/Cabal-tests/tests/UnitTests.hs index 876d7cdee5b..71cadfaa5cc 100644 --- a/Cabal-tests/tests/UnitTests.hs +++ b/Cabal-tests/tests/UnitTests.hs @@ -9,7 +9,9 @@ import Data.Proxy import qualified UnitTests.Distribution.Compat.CopyFile import qualified UnitTests.Distribution.Compat.Time +import qualified UnitTests.Distribution.Compat.Directory import qualified UnitTests.Distribution.Compat.Graph +import qualified UnitTests.Distribution.Compat.Prelude import qualified UnitTests.Distribution.PackageDescription.Check import qualified UnitTests.Distribution.Simple.Command import qualified UnitTests.Distribution.Simple.Compiler @@ -41,8 +43,12 @@ tests = (UnitTests.Distribution.Compat.Time.tests mtimeChange) , testGroup "Distribution.Compat.CopyFile" UnitTests.Distribution.Compat.CopyFile.tests + , testGroup "Distribution.Compat.Directory" + UnitTests.Distribution.Compat.Directory.tests , testGroup "Distribution.Compat.Graph" UnitTests.Distribution.Compat.Graph.tests + , testGroup "Distribution.Compat.Prelude" + UnitTests.Distribution.Compat.Prelude.tests , testGroup "Distribution.Simple.Command" UnitTests.Distribution.Simple.Command.tests , testGroup "Distribution.Simple.Compiler" diff --git a/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs b/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs new file mode 100644 index 00000000000..bbd5de675f2 --- /dev/null +++ b/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs @@ -0,0 +1,114 @@ +module UnitTests.Distribution.Compat.Directory (tests) where + +import Control.Exception (IOException, try) +import System.Directory (doesDirectoryExist, doesFileExist) +import System.FilePath ((), isAbsolute) +import System.IO.Error (isAlreadyExistsError) + +import Distribution.Compat.Directory +import Distribution.Simple.Utils (withTempDirectory) + +import Test.Tasty +import Test.Tasty.HUnit + +tests :: [TestTree] +tests = + [ testCase "removePathForcibly removes a regular file" removeFileTest + , testCase "removePathForcibly removes a directory tree" removeTreeTest + , testCase "removePathForcibly ignores missing paths" removeMissingTest + , testCase "canonicalizePath tolerates missing paths" canonMissingTest + , testCase "canonicalizePath resolves existing files" canonExistingTest + , testCase "createDirectoryIfMissing rejects existing files" mkdirOnFileTest + , testCase "createDirectoryIfMissing accepts existing directories" mkdirOnDirTest + , testCase "getPermissions gates searchable on directories" permsSearchableTest + ] + +removeFileTest :: Assertion +removeFileTest = + withTempDirectory "." "removefile-" $ \dir -> do + let fileName = dir "victim.txt" + writeFile fileName "content" + removePathForcibly fileName + gone <- doesFileExist fileName + assertBool "expected regular file to be removed" (not gone) + +removeTreeTest :: Assertion +removeTreeTest = + withTempDirectory "." "removetree-" $ \dir -> do + let sub = dir "sub" "nested" + createDirectoryIfMissing True sub + writeFile (sub "f") "x" + removePathForcibly (dir "sub") + gone <- doesDirectoryExist (dir "sub") + assertBool "expected directory tree to be removed" (not gone) + +removeMissingTest :: Assertion +removeMissingTest = + withTempDirectory "." "removemissing-" $ \dir -> + -- Must not throw. + removePathForcibly (dir "does-not-exist") + +canonMissingTest :: Assertion +canonMissingTest = + withTempDirectory "." "canonmissing-" $ \dir -> do + resolved <- canonicalizePath (dir "does-not-exist") + assertBool "expected an absolute path" (isAbsolute resolved) + +canonExistingTest :: Assertion +canonExistingTest = + withTempDirectory "." "canonexisting-" $ \dir -> do + let fileName = dir "present.txt" + writeFile fileName "content" + resolved <- canonicalizePath fileName + assertBool "expected an absolute path" (isAbsolute resolved) + present <- doesFileExist resolved + assertBool "expected resolved path to exist" present + +mkdirOnFileTest :: Assertion +mkdirOnFileTest = + withTempDirectory "." "mkdironfile-" $ \dir -> do + let fileName = dir "file.txt" + writeFile fileName "content" + result <- try (createDirectoryIfMissing False fileName) :: IO (Either IOException ()) + case result of + Left err -> assertBool "expected AlreadyExists" (isAlreadyExistsError err) + Right _ -> assertFailure "expected creating over a file to fail" + +mkdirOnDirTest :: Assertion +mkdirOnDirTest = + withTempDirectory "." "mkdirondir-" $ \dir -> do + let sub = dir "sub" + createDirectoryIfMissing True sub + -- Creating it again (and non-recursively) must be a no-op. + createDirectoryIfMissing False sub + present <- doesDirectoryExist sub + assertBool "expected directory to exist" present + +-- | Only directories can be searchable, matching @directory@: an +-- owner-executable regular file reports @executable = True@ but +-- @searchable = False@, even when @searchable@ was requested. +permsSearchableTest :: Assertion +permsSearchableTest = + withTempDirectory "." "permssearch-" $ \dir -> do + let fileName = dir "script.sh" + sub = dir "sub" + writeFile fileName "x" + createDirectoryIfMissing False sub + -- Owner-executable regular file: executable but not searchable. + -- (Record update: directory hides the Permissions constructor.) + setPermissions fileName (emptyPermissions { readable = True, executable = True }) + fp <- getPermissions fileName + assertBool "expected file to be executable" (executable fp) + assertBool "expected file to not be searchable" (not (searchable fp)) + -- Requesting searchable on a file is a no-op. + setPermissions fileName (emptyPermissions { readable = True, executable = True, searchable = True }) + fp2 <- getPermissions fileName + assertBool "expected file to stay executable" (executable fp2) + assertBool "expected file to stay non-searchable" (not (searchable fp2)) + -- Owner-executable directory: searchable but not executable + -- (matching @directory@: @executable = x && not isDir@, + -- @searchable = x && isDir@). + setPermissions sub (emptyPermissions { readable = True, executable = True, searchable = True }) + dp <- getPermissions sub + assertBool "expected dir to not be executable" (not (executable dp)) + assertBool "expected dir to be searchable" (searchable dp) diff --git a/Cabal-tests/tests/UnitTests/Distribution/Compat/Graph.hs b/Cabal-tests/tests/UnitTests/Distribution/Compat/Graph.hs index be890fe65b7..4e2a853fa5d 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/Compat/Graph.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/Compat/Graph.hs @@ -9,30 +9,44 @@ import Distribution.Compat.Graph import qualified Prelude import Prelude hiding (null) import Test.Tasty +import Test.Tasty.HUnit import Test.Tasty.QuickCheck +import qualified Data.List.NonEmpty as NE import qualified Data.Set as Set import Control.Monad import qualified Data.Graph as G import Data.Array ((!)) import Data.Maybe import Data.List (sort) +import Data.Proxy (Proxy (..)) +import Distribution.Utils.Structured (Structure (Nominal), Structured (..), nominalStructure) tests :: [TestTree] tests = - [ testProperty "arbitrary unbroken" (prop_arbitrary_unbroken :: Graph (Node Int ()) -> Bool) - , testProperty "nodes consistent" (prop_nodes_consistent :: Graph (Node Int ()) -> Bool) - , testProperty "edges consistent" (prop_edges_consistent :: Graph (Node Int ()) -> Property) - , testProperty "closure consistent" (prop_closure_consistent :: Graph (Node Int ()) -> Property) + [ testProperty "arbitrary unbroken" (prop_arbitrary_unbroken :: Graph Int (Node Int ()) -> Bool) + , testProperty "nodes consistent" (prop_nodes_consistent :: Graph Int (Node Int ()) -> Bool) + , testProperty "edges consistent" (prop_edges_consistent :: Graph Int (Node Int ()) -> Property) + , testProperty "closure consistent" (prop_closure_consistent :: Graph Int (Node Int ()) -> Property) + , testProperty "structure tag" prop_structure_tag + -- The properties above fix the key to the 'Node' payload index. + -- Below they are re-run with 'TKey'/'TNode', where the key is a + -- dedicated type independent of the node payload, plus unit + -- tests over a hand-built 'Graph TKey TNode'. + , testProperty "TKey arbitrary unbroken" (prop_arbitrary_unbroken :: Graph TKey TNode -> Bool) + , testProperty "TKey nodes consistent" (prop_nodes_consistent :: Graph TKey TNode -> Bool) + , testProperty "TKey edges consistent" (prop_edges_consistent :: Graph TKey TNode -> Property) + , testProperty "TKey closure consistent" (prop_closure_consistent :: Graph TKey TNode -> Property) + , testGroup "key parameter" keyParamTests ] -- Our arbitrary instance does not generate broken graphs -prop_arbitrary_unbroken :: Graph a -> Bool +prop_arbitrary_unbroken :: Graph k a -> Bool prop_arbitrary_unbroken g = Prelude.null (broken g) -- Every node from 'toList' maps to a vertex which -- is present in the constructed graph, and maps back -- to a node correctly. -prop_nodes_consistent :: (Eq a, IsNode a) => Graph a -> Bool +prop_nodes_consistent :: (Eq a, IsNode k a) => Graph k a -> Bool prop_nodes_consistent g = all p (toList g) where (_, vtn, ktv) = toGraph g @@ -42,7 +56,7 @@ prop_nodes_consistent g = all p (toList g) -- A non-broken graph has the 'nodeNeighbors' of each node -- equal the recorded adjacent edges in the node graph. -prop_edges_consistent :: IsNode a => Graph a -> Property +prop_edges_consistent :: IsNode k a => Graph k a -> Property prop_edges_consistent g = Prelude.null (broken g) ==> all p (toList g) where (gr, vtn, ktv) = toGraph g @@ -50,7 +64,7 @@ prop_edges_consistent g = Prelude.null (broken g) ==> all p (toList g) == sort (map (nodeKey . vtn) (gr ! fromJust (ktv (nodeKey n)))) -- Closure is consistent with reachable -prop_closure_consistent :: (Show a, IsNode a) => Graph a -> Property +prop_closure_consistent :: (Show a, IsNode k a) => Graph k a -> Property prop_closure_consistent g = not (null g) ==> forAll (elements (toList g)) $ \n -> @@ -71,7 +85,7 @@ hasNoDups = loop Set.empty -- | Produces a graph of size @len@. We sample with 'suchThat'; if we -- dropped duplicate entries our size could be smaller. arbitraryGraph :: (Ord k, Show k, Arbitrary k, Arbitrary a) - => Int -> Gen (Graph (Node k a)) + => Int -> Gen (Graph k (Node k a)) arbitraryGraph len = do -- Careful! Assume k is much larger than size. ks <- vectorOf len arbitrary `suchThat` hasNoDups @@ -83,7 +97,122 @@ arbitraryGraph len = do return (fromDistinctList ns) instance (Ord k, Show k, Arbitrary k, Arbitrary a) - => Arbitrary (Graph (Node k a)) where + => Arbitrary (Graph k (Node k a)) where arbitrary = sized $ \n -> do len <- choose (0, n) arbitraryGraph len + +instance Arbitrary TKey where + arbitrary = TKey <$> arbitrary + +-- | Produces an unbroken graph over 'TNode's, mirroring +-- 'arbitraryGraph' but with a key type independent of the node +-- payload. +arbitraryTGraph :: Int -> Gen (Graph TKey TNode) +arbitraryTGraph len = do + ks <- vectorOf len arbitrary `suchThat` hasNoDups + nodes <- forM ks $ \k -> do + ns <- if Prelude.null ks then pure [] else listOf (elements ks) + pure (TNode k ns) + pure (fromDistinctList nodes) + +instance Arbitrary (Graph TKey TNode) where + arbitrary = sized $ \n -> do + len <- choose (0, n) + arbitraryTGraph len + +-- | A small hand-built graph with a dedicated key type: +-- 1 -> {2, 3}, 2 -> {3}, 3 -> {}. +keyGraph :: Graph TKey TNode +keyGraph = fromDistinctList + [ TNode (TKey 1) [TKey 2, TKey 3] + , TNode (TKey 2) [TKey 3] + , TNode (TKey 3) [] + ] + +-- | A graph with a dangling reference: 1 -> {2}, with 2 missing. +brokenKeyGraph :: Graph TKey TNode +brokenKeyGraph = fromDistinctList [TNode (TKey 1) [TKey 2]] + +keyParamTests :: [TestTree] +keyParamTests = + [ testCase "empty/null/size" $ do + null (empty :: Graph TKey TNode) @?= True + null keyGraph @?= False + size keyGraph @?= 3 + keys keyGraph @?= [TKey 1, TKey 2, TKey 3] + keysSet keyGraph @?= Set.fromList [TKey 1, TKey 2, TKey 3] + , testCase "member/lookup" $ do + member (TKey 1) keyGraph @?= True + member (TKey 9) keyGraph @?= False + lookup (TKey 2) keyGraph @?= Just (TNode (TKey 2) [TKey 3]) + lookup (TKey 9) keyGraph @?= Nothing + , testCase "insert/deleteKey/deleteLookup" $ do + let g' = insert (TNode (TKey 9) []) keyGraph + member (TKey 9) g' @?= True + size g' @?= 4 + let g'' = deleteKey (TKey 2) g' + member (TKey 2) g'' @?= False + size g'' @?= 3 + let (mdeleted, g''') = deleteLookup (TKey 1) g'' + mdeleted @?= Just (TNode (TKey 1) [TKey 2, TKey 3]) + member (TKey 1) g''' @?= False + , testCase "neighbors/revNeighbors" $ do + neighbors keyGraph (TKey 1) @?= Just [TNode (TKey 2) [TKey 3], TNode (TKey 3) []] + neighbors keyGraph (TKey 3) @?= Just [] + neighbors keyGraph (TKey 9) @?= Nothing + (Set.fromList <$> revNeighbors keyGraph (TKey 3)) + @?= Just (Set.fromList [TNode (TKey 1) [TKey 2, TKey 3], TNode (TKey 2) [TKey 3]]) + revNeighbors keyGraph (TKey 9) @?= Nothing + , testCase "closure/revClosure" $ do + (Set.fromList . map nodeKey <$> closure keyGraph [TKey 1]) + @?= Just (Set.fromList [TKey 1, TKey 2, TKey 3]) + (Set.fromList . map nodeKey <$> revClosure keyGraph [TKey 3]) + @?= Just (Set.fromList [TKey 1, TKey 2, TKey 3]) + closure keyGraph [TKey 9] @?= Nothing + , testCase "topSort/revTopSort/cycles" $ do + -- 1 has no incoming edges and 3 has no outgoing edges, so + -- every topological order starts with 1 and ends with 3. + let sorted = map nodeKey (topSort keyGraph) + sort sorted @?= [TKey 1, TKey 2, TKey 3] + head sorted @?= TKey 1 + last sorted @?= TKey 3 + sort (map nodeKey (revTopSort keyGraph)) @?= [TKey 1, TKey 2, TKey 3] + cycles keyGraph @?= [] + , testCase "broken" $ do + broken keyGraph @?= [] + broken brokenKeyGraph @?= [(TNode (TKey 1) [TKey 2], TKey 2 NE.:| [])] + , testCase "union" $ do + let left = fromDistinctList [TNode (TKey 1) [TKey 2], TNode (TKey 2) []] + right = fromDistinctList [TNode (TKey 2) [TKey 1], TNode (TKey 3) []] + lookup (TKey 2) (unionLeft left right) @?= Just (TNode (TKey 2) []) + lookup (TKey 2) (unionRight left right) @?= Just (TNode (TKey 2) [TKey 1]) + lookup (TKey 3) (unionLeft left right) @?= Just (TNode (TKey 3) []) + ] + +-- Test key/node pair with the smallest possible instances. +newtype TKey = TKey Int + deriving (Eq, Ord, Show) + +data TNode = TNode TKey [TKey] + deriving (Eq, Show) + +instance IsNode TKey TNode where + nodeKey (TNode k _) = k + nodeNeighbors (TNode _ ks) = ks + +instance Structured TNode where + structure = nominalStructure + +-- | The 'Structured' instance for 'Graph' must stay usable with only +-- 'Structured a' in scope (no 'Typeable k'), so that generically +-- derived plan types keep compiling. This helper only typechecks +-- while the instance head is weak enough. +graphStructureOf :: Structured a => Proxy (Graph k a) -> Structure +graphStructureOf = structure + +prop_structure_tag :: Bool +prop_structure_tag = + case graphStructureOf (Proxy :: Proxy (Graph TKey TNode)) of + Nominal _ 0 "Graph" [_] -> True + _ -> False diff --git a/Cabal-tests/tests/UnitTests/Distribution/Compat/Prelude.hs b/Cabal-tests/tests/UnitTests/Distribution/Compat/Prelude.hs new file mode 100644 index 00000000000..8b045a01a86 --- /dev/null +++ b/Cabal-tests/tests/UnitTests/Distribution/Compat/Prelude.hs @@ -0,0 +1,40 @@ +{-# OPTIONS_GHC -Wno-orphans #-} +module UnitTests.Distribution.Compat.Prelude + ( tests + ) where + +-- Regression coverage for the NonEmpty-specialised 'foldr1'/'foldl1': +-- they must agree with 'Data.Foldable' on every input. Importing the +-- compatibility Prelude the way library modules do (with an empty +-- 'Prelude' import) also keeps the re-export list honest: anything +-- removed from it by accident breaks this module's compile. +import Distribution.Compat.Prelude +import Prelude () + +import qualified Data.Foldable as Foldable +import qualified Data.List.NonEmpty as NE +import Test.Tasty +import Test.Tasty.QuickCheck + +instance Arbitrary a => Arbitrary (NE.NonEmpty a) where + arbitrary = (NE.:|) <$> arbitrary <*> arbitrary + +tests :: [TestTree] +tests = + [ testProperty "foldr1 matches Data.Foldable.foldr1" prop_foldr1_matches + , testProperty "foldl1 matches Data.Foldable.foldl1" prop_foldl1_matches + , testProperty "foldr1 singleton" prop_foldr1_singleton + , testProperty "foldl1 singleton" prop_foldl1_singleton + ] + +prop_foldr1_matches :: NE.NonEmpty Int -> Property +prop_foldr1_matches ne = foldr1 (-) ne === Foldable.foldr1 (-) ne + +prop_foldl1_matches :: NE.NonEmpty Int -> Property +prop_foldl1_matches ne = foldl1 (-) ne === Foldable.foldl1 (-) ne + +prop_foldr1_singleton :: Int -> Property +prop_foldr1_singleton x = foldr1 (-) (x NE.:| []) === x + +prop_foldl1_singleton :: Int -> Property +prop_foldl1_singleton x = foldl1 (-) (x NE.:| []) === x diff --git a/Cabal-tests/tests/UnitTests/Distribution/SPDX.hs b/Cabal-tests/tests/UnitTests/Distribution/SPDX.hs index 297f98c8078..601a2623436 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/SPDX.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/SPDX.hs @@ -1,6 +1,8 @@ {-# OPTIONS_GHC -Wno-deprecations #-} module UnitTests.Distribution.SPDX (spdxTests) where +import Data.Data (fromConstr, toConstr) +import Data.List (sort) import Distribution.Compat.Prelude.Internal import Prelude () @@ -22,6 +24,8 @@ spdxTests = , testProperty "LicenseExpression roundtrip" licenseExpressionRoundtrip , testProperty "isAcceptableLicense l = True" shouldAcceptProp , testProperty "isAcceptableLicense l = False" shouldRejectProp + , testProperty "LicenseId Ord matches Enum order" licenseIdOrdMatchesEnum + , testCase "LicenseId enumeration is dense and ordered" licenseIdEnumerationOrder ] licenseIdRoundtrip :: LicenseId -> Property @@ -29,6 +33,25 @@ licenseIdRoundtrip x = counterexample (prettyShow x) $ Right x === eitherParsec (prettyShow x) +-- The MicroHs build replaces the derived Ord for LicenseId (a +-- ~700-constructor type) with comparison via fromEnum; pin the two +-- to agree so the seam cannot silently change ordering. +licenseIdOrdMatchesEnum :: LicenseId -> LicenseId -> Property +licenseIdOrdMatchesEnum x y = + counterexample (prettyShow x ++ " vs " ++ prettyShow y) $ + compare x y === compare (fromEnum x) (fromEnum y) + +-- | The full enumeration must be dense, ordered, and round-trip +-- through 'toConstr'/'fromConstr'. This pins the constructor-name +-- table used by the MicroHs hand-written 'Data' instance: every +-- constructor must appear exactly once, in declaration order. +licenseIdEnumerationOrder :: Assertion +licenseIdEnumerationOrder = do + let ids = [minBound .. maxBound] :: [LicenseId] + assertEqual "sort is the identity" ids (sort ids) + assertEqual "fromEnum tags are 0-based and dense" [0 .. length ids - 1] (map fromEnum ids) + assertEqual "toConstr/fromConstr round-trips" ids (map (fromConstr . toConstr) ids) + licenseExceptionIdRoundtrip :: LicenseExceptionId -> Property licenseExceptionIdRoundtrip x = counterexample (prettyShow x) $ diff --git a/Cabal-tests/tests/UnitTests/Distribution/Simple/Glob.hs b/Cabal-tests/tests/UnitTests/Distribution/Simple/Glob.hs index e853040c1d6..1740f9a4b7e 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/Simple/Glob.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/Simple/Glob.hs @@ -11,7 +11,7 @@ import Data.Maybe (mapMaybe) import Distribution.Simple.Glob import qualified Distribution.Verbosity as Verbosity import Distribution.CabalSpecVersion -import System.Directory (createDirectoryIfMissing) +import Distribution.Compat.Directory (createDirectoryIfMissing) import System.FilePath ((), splitFileName, normalise) import System.IO.Temp (withSystemTempDirectory) import Test.Tasty diff --git a/Cabal-tests/tests/UnitTests/Distribution/Simple/Utils.hs b/Cabal-tests/tests/UnitTests/Distribution/Simple/Utils.hs index 97b083e0b1c..9629d50c713 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/Simple/Utils.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/Simple/Utils.hs @@ -9,7 +9,7 @@ import Distribution.System ( buildPlatform ) import Distribution.Verbosity import Data.IORef -import System.Directory ( doesDirectoryExist, doesFileExist +import Distribution.Compat.Directory ( doesDirectoryExist, doesFileExist , getTemporaryDirectory , removePathForcibly ) import System.FilePath ( (<.>) ) diff --git a/Cabal-tests/tests/custom-setup/CabalDoctestSetup.hs b/Cabal-tests/tests/custom-setup/CabalDoctestSetup.hs index 909a7b86025..c0e37c786c6 100644 --- a/Cabal-tests/tests/custom-setup/CabalDoctestSetup.hs +++ b/Cabal-tests/tests/custom-setup/CabalDoctestSetup.hs @@ -181,7 +181,7 @@ import Distribution.Types.LibraryName (libraryNameString) #endif -import System.Directory +import Distribution.Compat.Directory (makeAbsolute) findFile' :: Verbosity -> [FilePath] -> FilePath -> IO FilePath diff --git a/Cabal-tests/tests/custom-setup/IdrisSetup.hs b/Cabal-tests/tests/custom-setup/IdrisSetup.hs index 330265b4fde..a3fd51e60a9 100644 --- a/Cabal-tests/tests/custom-setup/IdrisSetup.hs +++ b/Cabal-tests/tests/custom-setup/IdrisSetup.hs @@ -71,9 +71,9 @@ import Distribution.Utils.Path import System.Environment import System.Exit import System.FilePath ((), splitDirectories,isAbsolute) -import System.Directory +import Distribution.Compat.Directory import qualified System.FilePath.Posix as Px -import System.Process +import Distribution.Compat.Process -- This is difference from vanilla idris-1.1.1 configConfigurationsFlags :: S.ConfigFlags -> [(FlagName, Bool)] diff --git a/Cabal/Cabal.cabal b/Cabal/Cabal.cabal index 3b95414f361..c32f528a061 100644 --- a/Cabal/Cabal.cabal +++ b/Cabal/Cabal.cabal @@ -24,6 +24,10 @@ build-type: Simple extra-doc-files: README.md ChangeLog.md +extra-source-files: + cbits/mhs_spawn.h + cbits/mhs_handle.h + source-repository head type: git location: https://github.com/haskell/cabal/ @@ -34,32 +38,70 @@ flag git-rev default: False manual: True +flag mhs + description: MicroHs build (uses -mhs package variants for array/binary/pretty) + default: False + manual: True + library default-language: GHC2021 -- Disabling ImportQualifiedPost, otherwise fourmolu jumps ahead to apply it everywhere default-extensions: NoImportQualifiedPost hs-source-dirs: src + -- C helpers for the MHS (MicroHs) build, which cannot use the + -- @process@ package. The POSIX bodies are used there; other + -- platforms compile the stubs. The matching headers + -- (cbits/mhs_spawn.h and cbits/mhs_handle.h, shipped in + -- extra-source-files) carry the prototypes for MicroHs-generated + -- FFI call sites. + c-sources: + cbits/mhs_spawn.c + cbits/mhs_handle.c + include-dirs: cbits + + -- Common deps available as separate MHS packages with the same + -- bounds on both backends (transformers/mtl/parsec stay in the + -- unconditional block below; they exist as mtl-2.3.2, + -- parsec-3.1.18.0, transformers-0.6.2.0 under MHS). build-depends: , Cabal-syntax ^>= 3.19 - , array >= 0.4.0.1 && < 0.6 , base >= 4.18 && < 5 - , bytestring >= 0.10.8 && < 0.13 , containers >= 0.5.8.2 && < 0.9 - , deepseq >= 1.4 && < 1.7 - , directory >= 1.3.8.5 && < 1.4 , filepath >= 1.4.301 && < 1.6 - , pretty >= 1.1.1 && < 1.2 - , process >= 1.6.29.0 && < 1.7 - , text >= 2.0.2 && < 2.2 , time >= 1.4.0.1 && < 1.17 - if os(windows) + -- MicroHs ships array/binary/pretty as -mhs variants; base-0.16.12.0 + -- provides bytestring, text, directory, deepseq, process, stm, so + -- those (plus unix, which has no MHS package) are GHC-only. + if flag(mhs) build-depends: - , Win32 >= 2.4.0.0 && < 2.15 + array-mhs >= 0.5.8 && < 0.6, + binary-mhs >= 0.8.1 && < 0.9, + pretty-mhs >= 1.1.3.6 && < 1.2 else build-depends: - , unix >= 2.8.6.0 && < 2.9 + , array >= 0.4.0.1 && < 0.6 + , binary >= 0.8.1 && < 0.9 + , bytestring >= 0.10.8 && < 0.13 + , deepseq >= 1.4 && < 1.7 + , directory >= 1.2.7 && < 1.4 + , pretty >= 1.1.1 && < 1.2 + , process >= 1.6.29.0 && < 1.7 + , text >= 2.0.2 && < 2.2 + + -- No unix/Win32 under MHS: base-0.16.12.0 provides System.Directory + -- and System.Process (via Distribution.Compat.Directory / MhsProcess + -- shims); unix-only code is behind !__MHS__. os-string-2.0.10 exists + -- in the MHS package db but Cabal/ has no System.OsString/OsPath + -- imports, so it is not required. + if !flag(mhs) + if os(windows) + build-depends: + , Win32 >= 2.4.0.0 && < 2.15 + else + build-depends: + , unix >= 2.8.6.0 && < 2.9 if flag(git-rev) build-depends: @@ -193,6 +235,7 @@ library Distribution.Compat.Binary, Distribution.Compat.CharParsing, Distribution.Compat.DList, + Distribution.Compat.Directory, Distribution.Compat.Exception, Distribution.Compat.Graph, Distribution.Compat.Lens, @@ -342,6 +385,7 @@ library Distribution.Compat.Async Distribution.Compat.CopyFile Distribution.Compat.GetShortPathName + Distribution.Compat.Internal.MhsProcess Distribution.GetOpt Distribution.Lex Distribution.PackageDescription.Check.Common @@ -410,3 +454,23 @@ library TypeOperators TypeSynonymInstances UndecidableInstances + +-- Process capture regression tests: dual-backend (GHC reference and +-- MicroHs) coverage for Distribution.Compat.Process capture +-- discipline, environment replacement, locale-correct text handling +-- and explicit CreatePipe rejection. POSIX-only: the tests drive +-- @sh@/@env@/@cat@. The same Main.hs also compiles directly with +-- @mhs@ (see the module header for the exact command). +test-suite process-capture-tests + type: exitcode-stdio-1.0 + hs-source-dirs: tests + main-is: ProcessCaptureTests.hs + -- POSIX-only: the tests drive sh/env/cat. + if !(os(linux) || os(darwin)) + buildable: False + default-language: GHC2021 + ghc-options: -Wall + build-depends: + , base >= 4.17 && < 5 + , bytestring >= 0.10.0.0 && < 0.13 + , Cabal ^>= 3.19 diff --git a/Cabal/cbits/mhs_handle.c b/Cabal/cbits/mhs_handle.c new file mode 100644 index 00000000000..e95bd8f4b24 --- /dev/null +++ b/Cabal/cbits/mhs_handle.c @@ -0,0 +1,108 @@ +/* Mode query for MicroHs handles, for the MHS (MicroHs) build of Cabal. + * + * MicroHs has no 'hSetBinaryMode' and exposes no Haskell-level query + * for a handle's text/binary mode. A text-mode handle (opened with + * 'openFile') carries the UTF-8 transducer layer (@c_add_utf8@) on top + * of the raw file layer; a binary-mode handle (opened with + * 'openBinaryFile') is the raw file layer itself. The transducer + * layer does not implement block reads/writes, so 'BS.hPut' and + * 'BS.hGetContents' silently corrupt non-ASCII bytes through it (see + * "Distribution.Compat.Internal.MhsProcess"). + * + * The outermost BFILE of each kind is identified by its @getb@ + * implementation: the transducer's is @getb_utf8@. This depends on + * the MicroHs 0.16.12.0 runtime layout (the method table starts the + * @BFILE@ struct, see @src/runtime/bfile.c@): a runtime upgrade that + * moves it breaks this probe, and the @T4b@ capture tests cover both + * handle kinds to catch that. + * + * On non-MHS toolchains (and when @__MHS__@ is unset) this compiles + * to a stub that is never called. + */ +#include "mhs_handle.h" + +#ifdef __MHS__ +#include +#include +#include + +/* MicroHs runtime symbols (src/runtime/bfile.c). */ +struct mhs_bfile_mets { + int (*getb)(void *); + void (*ungetb)(int, void *); + void (*putb)(int, void *); + void (*flushb)(void *); + void (*closeb)(void *); + size_t (*readb)(uint8_t *, size_t, void *); + size_t (*writeb)(const uint8_t *, size_t, void *); + int (*isattyb)(void *); + int64_t (*filesizeb)(void *); +}; + +struct mhs_bfile_file { + struct mhs_bfile_mets mets; + FILE *file; +}; + +struct mhs_bfile_utf8 { + struct mhs_bfile_mets mets; + struct mhs_bfile_mets *bfile; + int unget; + uint8_t pend[3]; + int npend; +}; + +extern int getb_utf8(void *); +extern int getb_file(void *); + +int +mhs_handle_is_text(void *p) +{ + return ((struct mhs_bfile_mets *)p)->getb == getb_utf8; +} + +int +mhs_handle_seek(void *p, int whence, int64_t offset) +{ + struct mhs_bfile_mets *bp = (struct mhs_bfile_mets *)p; + if (!bp) + return -1; + if (bp->getb == getb_utf8) { + struct mhs_bfile_utf8 *u = (struct mhs_bfile_utf8 *)bp; + u->unget = -1; + u->npend = 0; + bp = u->bfile; + } + if (!bp || bp->getb != getb_file) + return -1; + FILE *f = ((struct mhs_bfile_file *)bp)->file; + if (!f) + return -1; + int c_whence = SEEK_SET; + if (whence == 1) + c_whence = SEEK_CUR; + else if (whence == 2) + c_whence = SEEK_END; +#if defined(_WIN32) + return _fseeki64(f, (__int64)offset, c_whence); +#else + return fseeko(f, (off_t)offset, c_whence); +#endif +} +#else +int +mhs_handle_is_text(void *p) +{ + (void)p; + return 0; +} + +int +mhs_handle_seek(void *p, int whence, int64_t offset) +{ + (void)p; + (void)whence; + (void)offset; + return -1; +} +#endif diff --git a/Cabal/cbits/mhs_handle.h b/Cabal/cbits/mhs_handle.h new file mode 100644 index 00000000000..72dee7ce99c --- /dev/null +++ b/Cabal/cbits/mhs_handle.h @@ -0,0 +1,20 @@ +/* Mode query for MicroHs handles; see mhs_handle.c. Shipped in + * extra-source-files; carries the prototype for MicroHs-generated + * FFI call sites. */ +#ifndef MHS_HANDLE_H +#define MHS_HANDLE_H + +#include + +/* Nonzero when the handle's outermost BFILE layer is MicroHs' UTF-8 + * transducer (text mode), zero for the raw file layer (binary mode). + * Under @__MHS__@ this probes the 0.16.12.0 runtime layout; + * otherwise it is a stub returning 0. */ +int mhs_handle_is_text(void *p); + +/* Seek the underlying stdio FILE of a MicroHs BFILE handle. + * whence: 0 = SEEK_SET, 1 = SEEK_CUR, 2 = SEEK_END. + * Returns 0 on success, -1 on failure. */ +int mhs_handle_seek(void *p, int whence, int64_t offset); + +#endif diff --git a/Cabal/cbits/mhs_spawn.c b/Cabal/cbits/mhs_spawn.c new file mode 100644 index 00000000000..54b457407a6 --- /dev/null +++ b/Cabal/cbits/mhs_spawn.c @@ -0,0 +1,185 @@ +/* MHS process-spawning helpers for the Cabal library. + * + * The MHS (MicroHs) build of Cabal cannot use the @process@ package, so + * process creation is implemented on top of @posix_spawnp(3)@ plus + * @waitpid(2)@ and @kill(2)@. The @posix_spawn_file_actions_t@ type is + * opaque and its size and layout are platform specific, so all direct + * manipulation of it lives here in C rather than behind Haskell FFI. + * The Haskell side (Distribution.Compat.Internal.MhsProcess) only calls + * the three functions declared below, passing plain integers, file + * paths, and argument vectors. + * + * On non-POSIX platforms (notably Windows) these functions are stubs + * that fail; the MHS port targets POSIX systems. + */ + +#include "mhs_spawn.h" + +#if defined(_WIN32) + +/* Stubs so that the file still compiles where is missing. */ + +#include + +int mhs_spawn(const char *prog, char *const *argv, + const char *std_in, int std_in_fd, + const char *std_out, int std_out_fd, + const char *std_err, int std_err_fd, + char *const *envp) +{ + (void) prog; (void) argv; + (void) std_in; (void) std_in_fd; + (void) std_out; (void) std_out_fd; + (void) std_err; (void) std_err_fd; + (void) envp; + errno = ENOSYS; + return -1; +} + +int mhs_wait_exited(int pid, int *code) +{ + (void) pid; (void) code; + errno = ENOSYS; + return -1; +} + +int mhs_terminate(int pid) +{ + (void) pid; + errno = ENOSYS; + return -1; +} + +#else /* POSIX */ + +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#define MHS_ENVIRON (*_NSGetEnviron()) +#else +extern char **environ; +#define MHS_ENVIRON environ +#endif + +/* Redirect one standard stream for the child to be spawned. + * + * A non-NULL path redirects the stream to that file (read-only for + * file descriptor 0, write-only otherwise). Otherwise a non-negative + * fd is duplicated onto the target descriptor. Otherwise the stream + * is inherited unchanged. + */ +static int +mhs_add_redirect(posix_spawn_file_actions_t *fa, int target, + const char *path, int fd) +{ + if (path != 0) { + int flags = (target == 0) ? O_RDONLY : O_WRONLY; + /* The files are pre-created by the caller, so no O_CREAT here. */ + return posix_spawn_file_actions_addopen(fa, target, path, flags, 0600); + } + if (fd >= 0) { + return posix_spawn_file_actions_adddup2(fa, fd, target); + } + return 0; +} + +/* Spawn @prog@ (looked up along PATH) with the given argument vector. + * Returns the child pid, or -1 with errno set on failure. + */ +int +mhs_spawn(const char *prog, char *const *argv, + const char *std_in, int std_in_fd, + const char *std_out, int std_out_fd, + const char *std_err, int std_err_fd, + char *const *envp) +{ + posix_spawn_file_actions_t fa; + pid_t pid = (pid_t) -1; + int rc; + + rc = posix_spawn_file_actions_init(&fa); + if (rc != 0) { + errno = rc; + return -1; + } + + rc = mhs_add_redirect(&fa, 0, std_in, std_in_fd); + if (rc == 0) { + rc = mhs_add_redirect(&fa, 1, std_out, std_out_fd); + } + if (rc == 0) { + rc = mhs_add_redirect(&fa, 2, std_err, std_err_fd); + } + if (rc != 0) { + int e = rc; + posix_spawn_file_actions_destroy(&fa); + errno = e; + return -1; + } + + /* A NULL environment inherits the parent environment; otherwise + * the child gets exactly the given bindings. Executable lookup + * still uses the parent PATH, matching System.Process. */ + rc = posix_spawnp(&pid, prog, &fa, (const posix_spawnattr_t *) 0, + argv, envp ? envp : MHS_ENVIRON); + posix_spawn_file_actions_destroy(&fa); + if (rc != 0) { + errno = rc; + return -1; + } + return (int) pid; +} + +/* Non-blocking reaping probe. + * + * Returns 1 with @*code@ set when the child has exited (the exit + * status, or the negated signal number when killed by a signal), + * 0 when the child is still running, and -1 with errno set on error. + */ +int +mhs_wait_exited(int pid, int *code) +{ + int status; + pid_t r; + + do { + r = waitpid((pid_t) pid, &status, WNOHANG); + } while (r == (pid_t) -1 && errno == EINTR); + + if (r == 0) { + return 0; + } + if (r == (pid_t) -1) { + return -1; + } + if (WIFEXITED(status)) { + *code = WEXITSTATUS(status); + return 1; + } + if (WIFSIGNALED(status)) { + *code = -WTERMSIG(status); + return 1; + } + /* Stopped or continued: keep polling. */ + return 0; +} + +/* Deliver SIGTERM to the child. Returns 0 on success, -1 with errno + * set on failure. + */ +int +mhs_terminate(int pid) +{ + return kill((pid_t) pid, SIGTERM); +} + +#endif /* _WIN32 */ diff --git a/Cabal/cbits/mhs_spawn.h b/Cabal/cbits/mhs_spawn.h new file mode 100644 index 00000000000..c2eff0fb616 --- /dev/null +++ b/Cabal/cbits/mhs_spawn.h @@ -0,0 +1,21 @@ +/* Prototypes for the MicroHs process helpers in mhs_spawn.c. + * + * MicroHs emits a call for every 'foreign import ccall' into its + * generated C file, which is compiled as its own translation unit; + * without these prototypes the implicit declarations are rejected + * (and would be unsound for pointer-sized types). Include this + * header via a header-qualified import, e.g. + * foreign import ccall "mhs_spawn.h mhs_spawn" ... + */ +#ifndef MHS_SPAWN_H +#define MHS_SPAWN_H + +int mhs_spawn(const char *prog, char *const *argv, + const char *std_in, int std_in_fd, + const char *std_out, int std_out_fd, + const char *std_err, int std_err_fd, + char *const *envp); +int mhs_wait_exited(int pid, int *code); +int mhs_terminate(int pid); + +#endif /* MHS_SPAWN_H */ diff --git a/Cabal/src/Distribution/Backpack/ComponentsGraph.hs b/Cabal/src/Distribution/Backpack/ComponentsGraph.hs index aef3db817c6..93729ece6d1 100644 --- a/Cabal/src/Distribution/Backpack/ComponentsGraph.hs +++ b/Cabal/src/Distribution/Backpack/ComponentsGraph.hs @@ -22,6 +22,7 @@ import Distribution.Types.ComponentRequestedSpec import Distribution.Utils.Generic import Distribution.Pretty (pretty) +import Distribution.Utils.LogProgress import Text.PrettyPrint ------------------------------------------------------------------------------ @@ -30,7 +31,7 @@ import Text.PrettyPrint -- | A graph of source-level components by their source-level -- dependencies -type ComponentsGraph = Graph (Node ComponentName Component) +type ComponentsGraph = Graph ComponentName (Node ComponentName Component) -- | A list of components associated with the source level -- dependencies between them. diff --git a/Cabal/src/Distribution/Backpack/Configure.hs b/Cabal/src/Distribution/Backpack/Configure.hs index 47fb29db046..e64f85c85ca 100644 --- a/Cabal/src/Distribution/Backpack/Configure.hs +++ b/Cabal/src/Distribution/Backpack/Configure.hs @@ -1,6 +1,6 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE NondecreasingIndentation #-} {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE NoMonoLocalBinds #-} -- | See @@ -47,9 +47,11 @@ import Distribution.Types.MungedPackageName import Distribution.Utils.LogProgress import Distribution.Verbosity +#ifndef __MHS__ import Data.Either ( lefts ) +#endif import qualified Data.Map as Map import qualified Data.Set as Set import Distribution.Pretty @@ -231,12 +233,12 @@ toComponentLocalBuildInfos -- since we will pay for the ALL installed packages even if -- they are not related to what we are building. This was true -- in the old configure code. - external_graph :: Graph (Either InstalledPackageInfo ReadyComponent) + external_graph :: Graph UnitId (Either InstalledPackageInfo ReadyComponent) external_graph = Graph.fromDistinctList . map Left $ PackageIndex.allPackages installedPackageSet - internal_graph :: Graph (Either InstalledPackageInfo ReadyComponent) + internal_graph :: Graph UnitId (Either InstalledPackageInfo ReadyComponent) internal_graph = Graph.fromDistinctList . map Right diff --git a/Cabal/src/Distribution/Backpack/ConfiguredComponent.hs b/Cabal/src/Distribution/Backpack/ConfiguredComponent.hs index 308fbfa3171..dfbe02a3e8d 100644 --- a/Cabal/src/Distribution/Backpack/ConfiguredComponent.hs +++ b/Cabal/src/Distribution/Backpack/ConfiguredComponent.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + -- | See module Distribution.Backpack.ConfiguredComponent ( ConfiguredComponent (..) @@ -35,7 +37,11 @@ import qualified Data.Set as Set import Data.Traversable (mapAccumM) import qualified Distribution.Compat.NonEmptySet as NonEmptySet import Distribution.Pretty +#ifdef __MHS__ +import Text.PrettyPrint (Doc, hsep, quotes, text, vcat, ($$)) +#else import Text.PrettyPrint (Doc, hang, hsep, quotes, text, vcat, ($$)) +#endif import qualified Text.PrettyPrint as PP -- | A configured component, we know exactly what its 'ComponentId' is, diff --git a/Cabal/src/Distribution/Backpack/DescribeUnitId.hs b/Cabal/src/Distribution/Backpack/DescribeUnitId.hs index 9f6ce4a8ac2..ce88c62b8c7 100644 --- a/Cabal/src/Distribution/Backpack/DescribeUnitId.hs +++ b/Cabal/src/Distribution/Backpack/DescribeUnitId.hs @@ -9,6 +9,7 @@ import Distribution.Pretty import Distribution.Simple.Utils import Distribution.Types.ComponentName import Distribution.Types.PackageId +import Distribution.Utils.LogProgress import Distribution.Verbosity import Text.PrettyPrint diff --git a/Cabal/src/Distribution/Backpack/LinkedComponent.hs b/Cabal/src/Distribution/Backpack/LinkedComponent.hs index accec653279..a5789f3f8e3 100644 --- a/Cabal/src/Distribution/Backpack/LinkedComponent.hs +++ b/Cabal/src/Distribution/Backpack/LinkedComponent.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE CPP #-} -- | See module Distribution.Backpack.LinkedComponent @@ -39,7 +39,11 @@ import qualified Data.Map as Map import qualified Data.Set as Set import Data.Traversable (mapAccumM) import Distribution.Pretty (pretty) +#ifdef __MHS__ +import Text.PrettyPrint (Doc, hsep, quotes, text, vcat, ($+$)) +#else import Text.PrettyPrint (Doc, hang, hsep, quotes, text, vcat, ($+$)) +#endif -- | A linked component is a component that has been mix-in linked, at -- which point we have determined how all the dependencies of the diff --git a/Cabal/src/Distribution/Backpack/MixLink.hs b/Cabal/src/Distribution/Backpack/MixLink.hs index d6407a2d9a2..e7d18c2278d 100644 --- a/Cabal/src/Distribution/Backpack/MixLink.hs +++ b/Cabal/src/Distribution/Backpack/MixLink.hs @@ -18,9 +18,10 @@ import Distribution.Pretty import Distribution.Types.ComponentId import qualified Distribution.Utils.UnionFind as UnionFind -import Control.Monad +import Control.Monad hiding (mapM, sequence) import qualified Data.Foldable as F import qualified Data.Map as Map +import Distribution.Utils.LogProgress import Text.PrettyPrint ----------------------------------------------------------------------- diff --git a/Cabal/src/Distribution/Backpack/ModuleScope.hs b/Cabal/src/Distribution/Backpack/ModuleScope.hs index acd920abd26..04ef63ffef2 100644 --- a/Cabal/src/Distribution/Backpack/ModuleScope.hs +++ b/Cabal/src/Distribution/Backpack/ModuleScope.hs @@ -13,6 +13,7 @@ module Distribution.Backpack.ModuleScope , emptyModuleScope ) where +import Data.Foldable (Foldable) import Distribution.Compat.Prelude import Prelude () diff --git a/Cabal/src/Distribution/Backpack/ReadyComponent.hs b/Cabal/src/Distribution/Backpack/ReadyComponent.hs index e6291310a51..7912a6679c9 100644 --- a/Cabal/src/Distribution/Backpack/ReadyComponent.hs +++ b/Cabal/src/Distribution/Backpack/ReadyComponent.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} - -- | See module Distribution.Backpack.ReadyComponent ( ReadyComponent (..) @@ -39,9 +37,10 @@ import Distribution.ModuleName import Distribution.Package import Distribution.Simple.Utils -import Control.Monad +import Control.Monad hiding (mapM, sequence) import qualified Data.Map as Map import qualified Data.Set as Set +import Distribution.Utils.LogProgress import Text.PrettyPrint import Distribution.Pretty @@ -162,8 +161,7 @@ instance Package ReadyComponent where instance HasUnitId ReadyComponent where installedUnitId = rc_uid -instance IsNode ReadyComponent where - type Key ReadyComponent = UnitId +instance IsNode UnitId ReadyComponent where nodeKey = rc_uid nodeNeighbors rc = ( case rc_i rc of diff --git a/Cabal/src/Distribution/Backpack/UnifyM.hs b/Cabal/src/Distribution/Backpack/UnifyM.hs index a1b4c20f155..801800039ce 100644 --- a/Cabal/src/Distribution/Backpack/UnifyM.hs +++ b/Cabal/src/Distribution/Backpack/UnifyM.hs @@ -58,7 +58,7 @@ import qualified Data.IntMap as IntMap import qualified Data.Map as Map import Data.STRef import qualified Data.Set as Set -import Data.Traversable +import Distribution.Utils.LogProgress import Text.PrettyPrint -- TODO: more detailed trace output on high verbosity would probably diff --git a/Cabal/src/Distribution/Compat/Async.hs b/Cabal/src/Distribution/Compat/Async.hs index c1a667800b0..9fd54a39ed7 100644 --- a/Cabal/src/Distribution/Compat/Async.hs +++ b/Cabal/src/Distribution/Compat/Async.hs @@ -19,7 +19,7 @@ module Distribution.Compat.Async , withAsyncNF ) where -import Control.Concurrent (ThreadId, forkIO) +import Control.Concurrent (ThreadId, forkIO, throwTo) import Control.Concurrent.MVar (MVar, newEmptyMVar, putMVar, readMVar) import Control.DeepSeq (NFData, force) import Control.Exception @@ -32,7 +32,6 @@ import Control.Exception , evaluate , mask , throwIO - , throwTo , try , uninterruptibleMask_ ) diff --git a/Cabal/src/Distribution/Compat/CopyFile.hs b/Cabal/src/Distribution/Compat/CopyFile.hs index 582a07872e8..2d81d8e0354 100644 --- a/Cabal/src/Distribution/Compat/CopyFile.hs +++ b/Cabal/src/Distribution/Compat/CopyFile.hs @@ -17,8 +17,14 @@ module Distribution.Compat.CopyFile import Distribution.Compat.Prelude import Prelude () +#ifdef __MHS__ +-- Strict bytes only: lazy 'BSL.hGetContents' needs 'hGetSome', +-- which MicroHs does not implement. +import qualified Data.ByteString as BS +#else import qualified Data.ByteString.Lazy as BSL -import System.Directory +#endif +import Distribution.Compat.Directory ( doesFileExist ) import System.IO @@ -27,14 +33,16 @@ import System.IO , withBinaryFile ) -#ifndef mingw32_HOST_OS +#if !defined(mingw32_HOST_OS) && !defined(__MHS__) && !defined(MHS) +-- MicroHs has no @unix@ package ('System.Posix.*' are absent), so the +-- MHS build takes the fallback branch below, like Windows. import Control.Exception ( bracketOnError ) import Data.Bits ( (.|.) ) import System.IO.Error ( ioeSetLocation, isAlreadyExistsError, tryIOError ) -import System.Directory +import Distribution.Compat.Directory ( renameFile, removeFile ) import System.FilePath ( takeDirectory, () ) @@ -53,9 +61,27 @@ import System.Posix.Types import System.Posix.Files ( getFileStatus, fileMode, setFileMode ) +#elif defined(__MHS__) || defined(MHS) + +import Control.Exception + ( bracketOnError ) +import System.IO.Error + ( ioeSetLocation ) +import Distribution.Compat.Directory + ( addFileMode + , renameFile + , removeFile + ) +import Distribution.Compat.Internal.TempFile + ( openBinaryTempFile ) +import System.FilePath + ( takeDirectory ) +import System.IO + ( hClose ) + #else /* else mingw32_HOST_OS */ -import System.Directory +import Distribution.Compat.Directory ( copyFileWithMetadata ) #endif /* mingw32_HOST_OS */ @@ -65,7 +91,7 @@ copyOrdinaryFile src dest = copyFile src dest >> setFileOrdinary dest copyExecutableFile src dest = copyFile src dest >> setFileExecutable dest setFileOrdinary, setFileExecutable, setDirOrdinary :: FilePath -> IO () -#ifndef mingw32_HOST_OS +#if !defined(mingw32_HOST_OS) && !defined(__MHS__) && !defined(MHS) -- When running with a restrictive UMASK such as 0077 we still want to -- install files and directories that are accessible to other users. setFileOrdinary path = addFileMode path 0o644 -- file perms -rw-r--r-- @@ -75,6 +101,12 @@ addFileMode :: FilePath -> FileMode -> IO () addFileMode name m = do o <- fileMode <$> getFileStatus name setFileMode name (m .|. o) +#elif defined(__MHS__) || defined(MHS) +-- MHS lacks @unix@, but the Compat.Directory POSIX seam provides the +-- same OR-ing primitive over its own FFI, so installed files and +-- executables get the same permissions as on GHC. +setFileOrdinary path = addFileMode path 0o644 -- file perms -rw-r--r-- +setFileExecutable path = addFileMode path 0o755 -- file perms -rwxr-xr-x #else setFileOrdinary _ = return () setFileExecutable _ = return () @@ -85,7 +117,7 @@ setDirOrdinary = setFileExecutable -- | Copies a file to a new destination. -- Often you should use `copyFileChanged` instead. copyFile :: FilePath -> FilePath -> IO () -#ifndef mingw32_HOST_OS +#if !defined(mingw32_HOST_OS) && !defined(__MHS__) && !defined(MHS) copyFile fromFPath toFPath = copy `catchIO` (\ioe -> throwIO (ioeSetLocation ioe "copyFile")) @@ -128,6 +160,32 @@ openCopyTarget dir = getProcessID >>= \pid -> go (show pid) (0 :: Int) | isAlreadyExistsError ioe -> go pid (n + 1) | otherwise -> ioError ioe flags = defaultFileFlags{creat = Just 0o600, exclusive = True, cloexec = True} +#elif defined(__MHS__) || defined(MHS) +-- Atomic copy matching the POSIX branch above: stage the content in +-- an exclusively-created temporary file in the destination directory +-- (via 'openBinaryTempFile', which uses O_CREAT|O_EXCL so symlinks +-- are never followed), then atomically rename over the destination. +-- Renaming replaces a destination symlink instead of following it, +-- and never leaves a truncated destination behind. +-- Content is copied with strict 'Data.ByteString' handles: both +-- 'BS.readFile' (via 'openBinaryFile' plus raw 'c_readb') and 'BS.hPut' +-- (via raw 'c_writeb') bypass the UTF-8 transducer that text-mode +-- 'System.IO' handles wrap around every handle, so arbitrary bytes +-- round-trip unchanged. (Lazy 'BSL.hGetContents' is unusable here: +-- it needs 'hGetSome', which MicroHs does not implement.) +copyFile fromFPath toFPath = + copy + `catchIO` (\ioe -> throwIO (ioeSetLocation ioe "copyFile")) + where + copy = bracketOnError openTmp cleanTmp $ \(tmpFPath, hTmp) -> do + content <- BS.readFile fromFPath + BS.hPut hTmp content + hClose hTmp + renameFile tmpFPath toFPath + openTmp = openBinaryTempFile (takeDirectory toFPath) ".copyFile.tmp" + cleanTmp (tmpFPath, hTmp) = do + hClose hTmp `catchIO` \_ -> return () + removeFile tmpFPath `catchIO` \_ -> return () #else copyFile = copyFileWithMetadata #endif /* mingw32_HOST_OS */ @@ -156,6 +214,13 @@ filesEqual f1 f2 = do if s1 /= s2 then return False else do +#ifdef __MHS__ + -- Strict bytes: lazy 'BSL.hGetContents' needs 'hGetSome', + -- which MicroHs does not implement. + c1 <- BS.hGetContents h1 + c2 <- BS.hGetContents h2 +#else c1 <- BSL.hGetContents h1 c2 <- BSL.hGetContents h2 +#endif return $! c1 == c2 diff --git a/Cabal/src/Distribution/Compat/CreatePipe.hs b/Cabal/src/Distribution/Compat/CreatePipe.hs index 16d2ee042b5..3c2c335f0a2 100644 --- a/Cabal/src/Distribution/Compat/CreatePipe.hs +++ b/Cabal/src/Distribution/Compat/CreatePipe.hs @@ -1,5 +1,25 @@ +{-# LANGUAGE CPP #-} + +#if defined(__MHS__) || defined(MHS) +module Distribution.Compat.CreatePipe + {-# DEPRECATED "Use System.Process from package process directly" #-} + (createPipe) where + +import Distribution.Compat.Internal.MhsProcess (mhsCreatePipe) +import System.IO (Handle) + +-- | A 'CreatePipe' replacement based on temporary files: MHS +-- 'Handle's cannot be built on top of file descriptors, so each pipe +-- is a temporary file with a read 'Handle' and a write 'Handle' +-- opened on it. See "Distribution.Compat.Internal.MhsProcess" for +-- the semantic limits of this fallback. +createPipe :: IO (Handle, Handle) +createPipe = mhsCreatePipe + +#else module Distribution.Compat.CreatePipe {-# DEPRECATED "Use System.Process from package process directly" #-} (createPipe) where -import System.Process (createPipe) +import Distribution.Compat.Process (createPipe) +#endif diff --git a/Cabal/src/Distribution/Compat/Environment.hs b/Cabal/src/Distribution/Compat/Environment.hs index 5687fa978a2..42d9cf46ce9 100644 --- a/Cabal/src/Distribution/Compat/Environment.hs +++ b/Cabal/src/Distribution/Compat/Environment.hs @@ -9,7 +9,14 @@ import Prelude () import System.Environment (lookupEnv, unsetEnv) import qualified System.Environment as System +#ifdef __MHS__ +-- MicroHS provides no 'System.Environment.Blank'; its +-- 'System.Environment.setEnv' always overwrites, like 'Blank.setEnv' with +-- the overwrite flag set, so we use it directly. +import System.Environment (setEnv) +#else import qualified System.Environment.Blank as Blank (setEnv) +#endif getEnvironment :: IO [(String, String)] #ifdef mingw32_HOST_OS @@ -26,4 +33,8 @@ getEnvironment = System.getEnvironment -- | @setEnv name value@ sets the specified environment variable to @value@. setEnv :: String -> String -> IO () +#ifdef __MHS__ +setEnv = System.setEnv +#else setEnv key value = Blank.setEnv key value True +#endif diff --git a/Cabal/src/Distribution/Compat/Internal/MhsProcess.hs b/Cabal/src/Distribution/Compat/Internal/MhsProcess.hs new file mode 100644 index 00000000000..19eec4a2c94 --- /dev/null +++ b/Cabal/src/Distribution/Compat/Internal/MhsProcess.hs @@ -0,0 +1,501 @@ +{-# LANGUAGE CPP #-} +-- | Process spawning primitives for the MHS (MicroHs) build. +-- +-- MicroHs has no @process@ or @unix@ packages and its 'Handle's are +-- @stdio@-based, so there is no file-descriptor-to-'Handle' +-- conversion. Spawning is implemented on top of @posix_spawnp(3)@ +-- (via the @mhs_spawn@ C helper in @cbits/mhs_spawn.c@, which hides +-- the platform-specific @posix_spawn_file_actions_t@ layout), +-- termination via @kill(2)@, and waiting via @waitpid(2)@ with +-- @WNOHANG@ polled with 'threadDelay'. +-- +-- Pipes ('CreatePipe' streams) fall back to temporary files: the +-- child is redirected to a pre-created temporary file and the parent +-- communicates through 'Handle's opened on that file. This keeps +-- unidirectional, write-then-wait-then-read protocols working, but it +-- cannot reproduce the blocking/streaming semantics of real pipes; +-- see the note on 'mhsCreatePipe'. +-- +-- The imports used here are available both in GHC @base@ and in the +-- MicroHs base libraries (plus the @filepath@ package, which the MHS +-- build installs), so this module compiles unchanged on both sides. +-- It is shared plumbing for "Distribution.Compat.Process" and +-- "Distribution.Compat.CreatePipe"; it is not part of the public API. +module Distribution.Compat.Internal.MhsProcess + ( MhsRedirect (..) + , MhsChild + , mhsSpawn + , mhsWait + , mhsTryWait + , mhsJoin + , mhsRelease + , mhsTerminate + , mhsTempFile + , mhsRegisterTemp + , mhsLookupTemp + , mhsCreatePipe + , withMhsCwd +#ifdef __MHS__ + , hIsTextMode + , readBytes +#endif + ) where + +import Control.Concurrent (threadDelay) +import Control.Exception (bracket, catch) +import qualified Data.ByteString as BS +#ifdef __MHS__ +import Data.Char (chr, ord) +import System.IO.Internal (BFILE, withHandleAny) +#endif +import qualified Data.ByteString.Lazy as LBS +import Data.IORef (IORef, modifyIORef, newIORef, readIORef, writeIORef) +import Distribution.Compat.Directory (doesFileExist, getCurrentDirectory, getTemporaryDirectory, removeFile, setCurrentDirectory) +import Distribution.Compat.Internal.TempFile (openBinaryTempFile) +import Foreign.C.Error (throwErrnoIfMinus1, throwErrnoIfMinus1_) +import Foreign.C.String (CString, newCAString, withCAString) +import Foreign.C.Types (CInt (..)) +import Foreign.Marshal.Alloc (alloca, allocaBytes, free) +import Foreign.Marshal.Array (withArray0) +import Foreign.Ptr (Ptr, nullPtr) +import Foreign.Storable (peek, pokeElemOff, sizeOf) +import System.Environment (getEnvironment, setEnv, unsetEnv) +import System.Exit (ExitCode (..)) +import System.IO (BufferMode (..), Handle, IOMode (..), hClose, hSetBuffering, openFile +#ifdef __MHS__ + , hGetContents, hPutStr +#endif + ) +import System.IO.Unsafe (unsafePerformIO) + +-- | How one standard stream of the child is wired up. +data MhsRedirect + = MhsInherit + | -- | Inherit the stream from the parent. + MhsNull + | -- | Redirect the stream to @\/dev\/null@. + MhsFd Int + | -- | Duplicate an existing file descriptor (0, 1 or 2 for the + -- standard streams passed through as 'UseHandle'). + MhsFile FilePath + deriving (Eq, Show) + +-- | A spawned child: its pid, a cache for its exit code (so repeated +-- waits are cheap and idempotent), the temporary files created +-- for its pipe streams, removed once the child is reaped, and +-- @(path, handle)@ pairs whose contents are appended to the handle +-- on reap (for @UseHandle@ of regular files). +data MhsChild = MhsChild + { mhsPid :: Int + , mhsStatus :: IORef (Maybe ExitCode) + , mhsTempFiles :: [FilePath] + , mhsCopies :: [(FilePath, Handle)] + } + +foreign import ccall "mhs_spawn.h mhs_spawn" c_mhs_spawn + :: CString -> Ptr CString -> CString -> CInt -> CString -> CInt -> CString -> CInt -> Ptr CString -> IO CInt +foreign import ccall "mhs_spawn.h mhs_wait_exited" c_mhs_wait_exited + :: CInt -> Ptr CInt -> IO CInt +foreign import ccall "mhs_spawn.h mhs_terminate" c_mhs_terminate + :: CInt -> IO CInt + +-- | How often, in microseconds, 'mhsWait' polls @waitpid@. +mhsPollMicros :: Int +mhsPollMicros = 10000 + +-- | Marshal one stream redirection for the C helper: a path to open +-- (or 'nullPtr') plus a file descriptor to duplicate (or -1). +withMhsRedirect :: MhsRedirect -> (CString -> CInt -> IO a) -> IO a +withMhsRedirect MhsInherit io = io nullPtr (-1) +withMhsRedirect (MhsFd fd) io = io nullPtr (fromIntegral fd) +withMhsRedirect (MhsFile path) io = + withCAString path $ \cpath -> io cpath (-1) +withMhsRedirect MhsNull io = + withCAString "/dev/null" $ \cnull -> io cnull (-1) + +-- | Marshal an argument vector as a NULL-terminated array. +withArgv :: [String] -> (Ptr CString -> IO a) -> IO a +withArgv args io = + bracket + (mapM newCAString args) + (mapM_ free) + ( \cstrs -> + allocaBytes ((length cstrs + 1) * ptrSize) $ \arr -> do + mapM_ (\(i, cs) -> pokeElemOff arr i cs) (zip [0 ..] cstrs) + pokeElemOff arr (length cstrs) (nullPtr :: CString) + io arr + ) + where + ptrSize = sizeOf (nullPtr :: CString) + +-- | Run an action in a different working directory, restoring the +-- previous one afterwards. Like process creation itself this is not +-- safe against concurrent spawns with different directories from +-- other threads. +withMhsCwd :: Maybe FilePath -> IO a -> IO a +withMhsCwd Nothing io = io +withMhsCwd (Just dir) io = + bracket + getCurrentDirectory + setCurrentDirectory + (const (setCurrentDirectory dir >> io)) + +-- | Spawn a child with @posix_spawnp@ (so @prog@ is looked up along +-- @PATH@), wiring its standard streams as directed. @temps@ lists +-- temporary files to delete once the child is reaped. +mhsSpawn + :: FilePath + -> [String] + -> Maybe FilePath + -> Maybe [(String, String)] + -> MhsRedirect + -> MhsRedirect + -> MhsRedirect + -> [FilePath] + -> [(FilePath, Handle)] + -- ^ @(path, handle)@ copies performed on reap (see 'MhsChild') + -> IO MhsChild +-- | Marshal an explicit environment for the child: 'Nothing' passes +-- a null pointer (the child inherits the parent environment), +-- @Just []@ passes an empty environment, and @Just pairs@ passes +-- exactly those bindings. The parent environment is never modified, +-- so unlike clearing and restoring it this is safe with respect to +-- other threads. +withEnvp :: Maybe [(String, String)] -> (Ptr CString -> IO a) -> IO a +withEnvp Nothing io = io nullPtr +withEnvp (Just pairs) io = + withCStrings (map (\(k, v) -> k ++ "=" ++ v) pairs) $ \cstrs -> + withArray0 nullPtr cstrs io + where + withCStrings [] f = f [] + withCStrings (s : ss) f = + withCAString s $ \cs -> + withCStrings ss $ \css -> f (cs : css) + +mhsSpawn prog args mcwd menv redirIn redirOut redirErr temps copies = + withMhsCwd mcwd $ + withEnvp menv $ \cenvp -> + withCAString prog $ \cprog -> + withArgv (prog : args) $ \cargv -> + withMhsRedirect redirIn $ \cIn fdIn -> + withMhsRedirect redirOut $ \cOut fdOut -> + withMhsRedirect redirErr $ \cErr fdErr -> do + pid <- + throwErrnoIfMinus1 + "mhsSpawn" + (c_mhs_spawn cprog cargv cIn fdIn cOut fdOut cErr fdErr cenvp) + st <- newIORef Nothing + pure (MhsChild (fromIntegral pid) st temps copies) + +-- | Single non-blocking reap probe. +mhsProbe :: MhsChild -> IO (Maybe ExitCode) +mhsProbe (MhsChild pid _ _ _) = + alloca $ \pcode -> do + r <- throwErrnoIfMinus1 "mhsWait" (c_mhs_wait_exited (fromIntegral pid) pcode) + if r == 0 + then pure Nothing + else do + code <- peek pcode + pure (Just (if code == 0 then ExitSuccess else ExitFailure (fromIntegral code))) + +-- | Append a file's contents to a 'Handle', for flushing pipe +-- redirections of regular-file 'UseHandle's on reap. Missing files +-- (already flushed by an earlier reap observation) are skipped +-- silently; any other failure is returned so the caller can report +-- it instead of silently losing the child's output. +copyBack :: FilePath -> Handle -> IO (Maybe IOError) +copyBack fp h = do + exists <- doesFileExist fp + if not exists + then pure Nothing + -- Strict bytes: lazy 'LBS.readFile' needs 'hGetSome', which + -- MicroHs does not implement. +#ifdef __MHS__ + -- The destination handle may be in text mode (e.g. a build log + -- opened with 'withFile'), where @c_writeb@ falls back to + -- per-byte @putb_utf8@ and would double-encode every byte above + -- 0x7F; 'copyBytes' picks the exact writer per handle mode. + else catch (BS.readFile fp >>= copyBytes h >> pure Nothing) (pure . Just) +#else + else catch (BS.readFile fp >>= BS.hPutStr h >> pure Nothing) (pure . Just) +#endif + +#ifdef __MHS__ +-- | Append bytes to a handle of either text or binary mode. +-- +-- 'BS.hPut' uses @c_writeb@, which MicroHs' UTF-8 transducer layer +-- does not implement: on a text-mode handle it falls back to +-- per-byte @putb_utf8@, UTF-8-encoding every byte above 0x7F a +-- second time (mojibake). Binary handles have a real @writeb@ and +-- take raw bytes. The mode is detected with 'hIsTextMode' and each +-- side uses its exact writer: text handles get the UTF-8 decoding of +-- the bytes through 'hPutStr' (which re-encodes them identically), +-- binary handles get the bytes untouched. +copyBytes :: Handle -> BS.ByteString -> IO () +copyBytes h bs = do + text <- hIsTextMode h + if text + then hPutStr h (decodeUtf8Lossy bs) + else BS.hPut h bs + +-- | Read the raw bytes of a handle of either text or binary mode. +-- +-- 'BS.hGetContents' uses @c_readb@, which MicroHs' UTF-8 transducer +-- layer does not implement: on a text-mode handle it falls back to +-- per-character @getb_utf8@, truncating every decoded code point +-- above 0x7F to a single byte. Binary handles have a real @readb@ +-- and yield raw bytes. The mode is detected with 'hIsTextMode' and +-- each side uses its exact reader: text handles are read as +-- characters and the transducer decoding is inverted (see +-- 'charToRawBytes'), binary handles are read untouched. +readBytes :: Handle -> IO BS.ByteString +readBytes h = do + text <- hIsTextMode h + if text + then hGetRawBytes h + else BS.hGetContents h + +-- | Whether a handle carries MicroHs' UTF-8 transducer layer (that +-- is, it was opened with 'openFile', not 'openBinaryFile'). +-- MicroHs has no 'hSetBinaryMode' and exposes no mode query; the +-- outermost 'BFILE' of a text handle is the UTF-8 transducer (see +-- @c_add_utf8@), identified through the C helper +-- @mhs_handle_is_text@, which compares its @getb@ implementation. +-- Pinned to the MicroHs 0.16.12.0 runtime layout (the method table +-- starts the @BFILE@ struct); the @T4b@ capture tests cover both +-- handle kinds and fail if a runtime upgrade moves it. +hIsTextMode :: Handle -> IO Bool +hIsTextMode h = withHandleAny h $ \p -> (/= 0) <$> c_handleIsText p + +foreign import ccall "mhs_handle.h mhs_handle_is_text" c_handleIsText :: Ptr BFILE -> IO CInt + +-- | Decode bytes as UTF-8, mirroring MicroHs' @getb_utf8@: valid +-- sequences become the decoded characters, undecodable bytes become +-- the replacement character (never a surrogate: 'hPutChar' rejects +-- those, and the C layer only round-trips its own escapes). +decodeUtf8Lossy :: BS.ByteString -> String +decodeUtf8Lossy bs + | BS.null bs = "" + | otherwise = + let (ascii, rest) = BS.span (< 0x80) bs + in map (chr . fromIntegral) (BS.unpack ascii) + ++ decodeRest rest + where + decodeRest r + | BS.null r = "" + | otherwise = + case decodeOne r of + (c, n) -> c : decodeRest (BS.drop n r) + +-- | Decode one UTF-8 sequence (at least one byte consumed), returning +-- the character and the number of bytes consumed. +decodeOne :: BS.ByteString -> (Char, Int) +decodeOne r = + let b0 = fromIntegral (BS.head r) :: Int + len = BS.length r + get i = fromIntegral (BS.index r i) :: Int + cont i = i < len && 0x80 <= get i && get i < 0xC0 + replacement = ('\xFFFD', 1) + in if b0 < 0x80 + then (chr b0, 1) + else + if b0 < 0xC0 || b0 >= 0xF8 || not (cont 1) + then replacement + else + if b0 < 0xE0 + then + let c = (b0 - 0xC0) * 64 + (get 1 - 0x80) + in if c < 0x80 then replacement else (chr c, 2) + else + if b0 < 0xF0 + then + if not (cont 2) + then replacement + else + let c = (b0 - 0xE0) * 4096 + (get 1 - 0x80) * 64 + (get 2 - 0x80) + in if c < 0x800 || 0xD800 <= c && c <= 0xDFFF + then replacement + else (chr c, 3) + else + if not (cont 2 && cont 3) + then replacement + else + let c = (b0 - 0xF0) * 262144 + (get 1 - 0x80) * 4096 + (get 2 - 0x80) * 64 + (get 3 - 0x80) + in if c < 0x10000 || c >= 0x110000 + then replacement + else (chr c, 4) + +-- | Read the raw bytes of a text-mode handle, inverting MicroHs' +-- UTF-8 transducer decoding (see 'readBytes'): +-- +-- * characters below 0x80 are the bytes themselves; +-- * @0xDC80@..@0xDCFF@ are the transducer's own escapes for +-- undecodable bytes; +-- * anything else is UTF-8-encoded back to bytes. +hGetRawBytes :: Handle -> IO BS.ByteString +hGetRawBytes h = do + str <- hGetContents h + let bytes = concatMap charToRawBytes str + length bytes `seq` pure (BS.pack (map fromIntegral bytes)) + +-- | Map one decoded 'Char' back to the raw bytes it came from (see +-- 'hGetRawBytes'). +charToRawBytes :: Char -> [Int] +charToRawBytes c + | n < 0x80 = [n] + | 0xDC80 <= n && n <= 0xDCFF = [n - 0xDC00] + | otherwise = encodeCharUtf8 (if isSurrogate n then 0xFFFD else n) + where + n = ord c + isSurrogate x = 0xD800 <= x && x <= 0xDFFF + +-- | UTF-8-encode one 'Char', inverting @getb_utf8@ for every +-- character it can yield. +encodeCharUtf8 :: Int -> [Int] +encodeCharUtf8 n + | n < 0x800 = + [ 0xC0 + n `div` 64 + , 0x80 + n `mod` 64 + ] + | n < 0x10000 = + [ 0xE0 + n `div` 4096 + , 0x80 + (n `div` 64) `mod` 64 + , 0x80 + n `mod` 64 + ] + | otherwise = + [ 0xF0 + n `div` 262144 + , 0x80 + (n `div` 4096) `mod` 64 + , 0x80 + (n `div` 64) `mod` 64 + , 0x80 + n `mod` 64 + ] +#endif + +-- | Remove the temporary files of a reaped child. Pending +-- @(path, handle)@ copies (see 'MhsChild') are performed first, so +-- regular-file redirections land in the destination handle before +-- its temporary file disappears. A copy failure is reported (never +-- silently swallowed) after the temporary files are still removed. +mhsCleanupChild :: MhsChild -> IO () +mhsCleanupChild (MhsChild _ _ temps copies) = do + errs <- mapM (uncurry copyBack) copies + mapM_ removeQuietly temps + case [e | Just e <- errs] of + (e : _) -> ioError e + [] -> pure () + where + removeQuietly :: FilePath -> IO () + removeQuietly fp = catch (removeFile fp) handle + handle :: IOError -> IO () + handle _ = pure () + +-- | Polling reap shared by 'mhsWait', 'mhsTryWait' and 'mhsJoin': +-- wait for the child to exit (or, when @nonBlocking@, take a single +-- probe), caching the exit code. Never touches temporary files. +mhsPoll :: Bool -> MhsChild -> IO (Maybe ExitCode) +mhsPoll nonBlocking child@(MhsChild _ st _ _) = do + cached <- readIORef st + case cached of + Just ec -> pure (Just ec) + Nothing -> go + where + go = do + mex <- mhsProbe child + case mex of + Just ec -> writeIORef st (Just ec) >> pure (Just ec) + Nothing + | nonBlocking -> pure Nothing + | otherwise -> threadDelay mhsPollMicros >> go + +-- | Wait for the child to exit, polling @waitpid@ with @WNOHANG@. +-- The exit code is cached, so repeated calls are cheap. Temporary +-- files are removed once the child is reaped. +mhsWait :: MhsChild -> IO ExitCode +mhsWait child = do + Just ec <- mhsPoll False child + mhsCleanupChild child + pure ec + +-- | Non-blocking exit check. Caches and cleans up when the child has +-- exited, like 'mhsWait'. +mhsTryWait :: MhsChild -> IO (Maybe ExitCode) +mhsTryWait child = do + mex <- mhsPoll True child + case mex of + Just _ -> mhsCleanupChild child + Nothing -> pure () + pure mex + +-- | Wait for the child to exit without touching temporary files. +-- Private capture paths use this to read the child's outputs before +-- 'mhsRelease' removes them. +mhsJoin :: MhsChild -> IO ExitCode +mhsJoin child = do + Just ec <- mhsPoll False child + pure ec + +-- | Perform pending copies and remove temporary files, like +-- 'mhsCleanupChild'. A copy failure is reported (never silently +-- swallowed) after the temporary files are still removed; only +-- failures while removing the temporary files themselves are +-- ignored. +mhsRelease :: MhsChild -> IO () +mhsRelease = mhsCleanupChild + +-- | Ask the child to terminate with @SIGTERM@. Does not wait. +mhsTerminate :: MhsChild -> IO () +mhsTerminate (MhsChild pid _ _ _) = + throwErrnoIfMinus1_ "mhsTerminate" (c_mhs_terminate (fromIntegral pid)) + +-- | Create a fresh empty temporary file, returning its path. The +-- file exists (so the child can open it without @O_CREAT@ races) and +-- is removed by 'mhsWait' once the owning child is reaped. It goes +-- through "Distribution.Compat.Internal.TempFile" (atomic +-- @O_CREAT@|@O_EXCL@ creation instead of MicroHs' unhardened +-- check-then-open 'System.IO.openTempFile'), and is binary so piped +-- child output round-trips byte-for-byte. +mhsTempFile :: IO FilePath +mhsTempFile = do + tmp <- getTemporaryDirectory + (path, h) <- openBinaryTempFile tmp "cabal-mhs-pipe" + hClose h + pure path + +-- | Registry remembering which temporary file backs each pipe +-- 'Handle' handed out by 'mhsCreatePipe' or stream setup, so a later +-- @UseHandle@ of such a handle can be redirected to the same file. +-- Entries are never removed; the number of live entries is bounded by +-- the number of pipes created, which is small in practice. +{-# NOINLINE tempRegistry #-} +tempRegistry :: IORef [(Handle, FilePath)] +tempRegistry = unsafePerformIO (newIORef []) + +-- | Remember the temporary file backing a pipe 'Handle'. +mhsRegisterTemp :: Handle -> FilePath -> IO () +mhsRegisterTemp h path = modifyIORef tempRegistry ((h, path) :) + +-- | Look up the temporary file backing a 'Handle', if any. +mhsLookupTemp :: Handle -> IO (Maybe FilePath) +mhsLookupTemp h = lookup h <$> readIORef tempRegistry + +-- | A 'CreatePipe' replacement for builds without file-descriptor to +-- 'Handle' conversion: a single temporary file with a read 'Handle' +-- and a write 'Handle' opened on it. +-- +-- Note the semantic limits of this fallback. A regular file has no +-- blocking or end-of-stream signalling: a reader that reaches the +-- current end of the file observes end-of-file even when the writer +-- has more to come, so concurrent streaming protocols (writing input +-- while lazily reading output before the child has exited) may observe +-- truncated output. The reliable pattern is to write the input, +-- close it, wait for the child, and only then read the output, which +-- is exactly how MicroHs' own @System.Process.readProcess@ uses +-- temporary files. +mhsCreatePipe :: IO (Handle, Handle) +mhsCreatePipe = do + path <- mhsTempFile + rh <- openFile path ReadMode + wh <- openFile path WriteMode + hSetBuffering wh NoBuffering + mhsRegisterTemp rh path + mhsRegisterTemp wh path + pure (rh, wh) diff --git a/Cabal/src/Distribution/Compat/Internal/TempFile.hs b/Cabal/src/Distribution/Compat/Internal/TempFile.hs index f95568fc97d..15b3b3a96c0 100644 --- a/Cabal/src/Distribution/Compat/Internal/TempFile.hs +++ b/Cabal/src/Distribution/Compat/Internal/TempFile.hs @@ -10,25 +10,105 @@ module Distribution.Compat.Internal.TempFile import Distribution.Compat.Exception +#ifdef __MHS__ +import Data.IORef (IORef, atomicModifyIORef', newIORef) +#else import GHC.IORef (IORef, atomicModifyIORef'_, newIORef) +#endif import System.FilePath (()) +#ifdef __MHS__ +import System.IO (Handle, IOMode (..), openBinaryFile, openFile) +#else import System.IO (Handle, openBinaryTempFile, openBinaryTempFileWithDefaultPermissions, openTempFile) +#endif import System.IO.Error (isAlreadyExistsError) import System.IO.Unsafe (unsafePerformIO) -import System.Posix.Internals (c_getpid) +#ifdef __MHS__ +import System.IO.Error (IOError, alreadyExistsErrorType, mkIOError) +#endif + +#ifdef __MHS__ +-- MicroHs lacks 'GHC.IORef.atomicModifyIORef'_'; 'Data.IORef' only has +-- the pair-returning 'atomicModifyIORef''. The old and new values are +-- reconstructed from it. +atomicModifyIORef'_ :: IORef a -> (a -> a) -> IO (a, a) +atomicModifyIORef'_ ref f = + atomicModifyIORef' ref (\x -> let x' = f x in (x', (x, x'))) +#endif -#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS) -import System.Directory ( createDirectory ) +#ifdef __MHS__ +import Distribution.Compat.Directory + ( createFileExclusively + , createPrivateDirectory + , removeFile + ) #else +import System.Posix.Internals (c_getpid) import qualified System.Posix #endif openNewBinaryFile :: FilePath -> String -> IO (FilePath, Handle) +#ifdef __MHS__ +-- No permission bits under MicroHs; same as 'openBinaryTempFile'. +openNewBinaryFile = openBinaryTempFile +#else openNewBinaryFile = openBinaryTempFileWithDefaultPermissions +#endif + +#ifdef __MHS__ +-- MicroHs 'System.IO' has no temporary-file primitives; they are +-- implemented here on top of 'openFile'/'openBinaryFile' with +-- atomically-created files (see 'createFileExclusively') and +-- per-process counters (see 'tempDirectoryCounter'). +openTempFile :: FilePath -> String -> IO (FilePath, Handle) +openTempFile = openTempFileWith openFile + +openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle) +openBinaryTempFile = openTempFileWith openBinaryFile + +openTempFileWith + :: (FilePath -> IOMode -> IO Handle) + -> FilePath -> String -> IO (FilePath, Handle) +openTempFileWith open dir template = do + pid <- getTempPid + let findTemp = do + (counter, _) <- atomicModifyIORef'_ tempDirectoryCounter (+ 1) + let path = dir template ++ "-" ++ show pid ++ show counter + -- Atomically create the file: O_CREAT|O_EXCL fails if anything + -- (a regular file, a directory, or a live or dangling symlink) + -- already exists at the path, closing both the check-then-open + -- race between processes and the symlink plant. + created <- createFileExclusively path 0o600 + if not created + then findTemp + else do + rh <- tryIO (open path ReadWriteMode) + case rh of + Right h -> pure (path, h) + -- Practically unreachable (the file was just created by + -- us): remove the empty file and propagate the failure + -- rather than leaking it. + Left e -> do + _ <- tryIO (removeFile path) :: IO (Either IOError ()) + ioError e + findTemp +#endif + +-- | Process identifier seed for temporary names. Only the MHS build +-- lacks 'System.Posix.Internals.c_getpid' (which exists on all GHC +-- platforms, including Windows); there uniqueness comes from the +-- per-process counter plus atomic creation (which retries on +-- collision) rather than from a pid. +getTempPid :: IO Int +#ifdef __MHS__ +getTempPid = pure 0 +#else +getTempPid = fromIntegral <$> c_getpid +#endif createTempDirectory :: FilePath -> String -> IO FilePath createTempDirectory dir template = do - pid <- c_getpid + pid <- getTempPid let findTempName = do (counter, _) <- atomicModifyIORef'_ tempDirectoryCounter (+ 1) let relpath = template ++ "-" ++ show pid ++ show counter @@ -46,8 +126,13 @@ tempDirectoryCounter = unsafePerformIO $ newIORef 0 {-# NOINLINE tempDirectoryCounter #-} mkPrivateDir :: String -> IO () -#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS) -mkPrivateDir s = createDirectory s +#ifdef __MHS__ +-- Atomic with the requested mode (no chmod window). +mkPrivateDir s = do + created <- createPrivateDirectory s 0o700 + if created + then pure () + else ioError (mkIOError alreadyExistsErrorType "createDirectory" Nothing (Just s)) #else mkPrivateDir s = System.Posix.createDirectory s 0o700 #endif diff --git a/Cabal/src/Distribution/Compat/Process.hs b/Cabal/src/Distribution/Compat/Process.hs index f82fc601287..bff617aa94e 100644 --- a/Cabal/src/Distribution/Compat/Process.hs +++ b/Cabal/src/Distribution/Compat/Process.hs @@ -1,14 +1,392 @@ {-# LANGUAGE CPP #-} +#if defined(__MHS__) || defined(MHS) +-- | Portability seam for process operations. +-- +-- Under GHC this module re-exports "System.Process" (plus the 'proc' +-- wrapper below). Under MHS (MicroHs, which has neither the +-- @process@ nor the @unix@ package) processes are spawned with +-- @posix_spawnp@, reaped with @waitpid@/@WNOHANG@ polled with +-- 'threadDelay', and terminated with @kill@; see +-- "Distribution.Compat.Internal.MhsProcess". 'CreatePipe' streams +-- fall back to temporary files because MHS 'Handle's cannot be built +-- on top of file descriptors. +-- +-- MicroHs defines @__MHS__@ itself; a manual @-DMHS@ flag is accepted +-- as well. Either macro selects this branch. +-- +-- Limitations of the MHS branch, relative to @process@: +-- +-- * The @close_fds@, @create_group@, @detach_console@, +-- @create_new_console@, @new_session@, @child_group@, @child_user@ +-- and @use_process_jobs@ fields of 'CreateProcess' are accepted but +-- ignored. The @cwd@ and @env@ fields are honoured by temporarily +-- changing the current directory and environment around the spawn, +-- which is not safe against concurrent spawns from other threads. +-- * @UseHandle@ accepts the standard streams, 'Handle's created by +-- 'newStagedInput' (or registered by an internal pipe stream), and +-- ordinary file 'Handle's (redirected via a temporary file that is +-- staged or copied back on reap, so logging to files works). Any +-- other 'Handle' throws. +-- * 'CreatePipe' is rejected: temporary files cannot emulate blocking +-- pipes, so streaming through the public 'createProcess' API would +-- silently truncate. Use 'captureProcess', +-- 'readCreateProcessWithExitCode' or 'newStagedInput', which own the +-- stage\/spawn\/wait\/read order and are complete by construction. +module Distribution.Compat.Process + ( CreateProcess (..) + , CmdSpec (..) + , StdStream (..) + , ProcessHandle + , proc + , shell + , createProcess + , createProcess_ + , cleanupProcess + , readCreateProcessWithExitCode + , readProcessWithExitCode + , captureProcess + , StagedInput (..) + , CapturedOutputs (..) + , newStagedInput + , callProcess + , waitForProcess + , getProcessExitCode + , terminateProcess + , showCommandForUser + , createPipe + , enableProcessJobs + ) where + +import Data.Char (isAlphaNum) +import Data.Maybe (catMaybes) +import Distribution.Compat.Directory (getTemporaryDirectory, removeFile) +import Distribution.Compat.Internal.MhsProcess + ( MhsChild + , MhsRedirect (..) + , mhsJoin + , readBytes + , mhsLookupTemp + , mhsRegisterTemp + , mhsRelease + , mhsSpawn + , mhsTempFile + , mhsTerminate + , mhsTryWait + , mhsWait + ) +import qualified Data.ByteString as BS +import qualified Data.ByteString.Lazy as LBS +import Control.Exception (throwIO) +import System.Exit (ExitCode (..)) +import Distribution.Compat.Internal.TempFile (openTempFile) +import System.IO (Handle, IOMode (..), hClose, hPutStr, openFile, stderr, stdin, stdout) + +-- | How to start a process: a shell command line or a raw executable +-- with arguments. +data CmdSpec + = ShellCommand String + | RawCommand FilePath [String] + deriving (Eq, Show) + +-- | What to do with a standard stream of the child. +data StdStream + = Inherit + | UseHandle Handle + | CreatePipe + | NoStream + +-- | Process creation parameters. Only @cmdspec@, @cwd@, @env@, +-- @std_in@, @std_out@ and @std_err@ affect the MHS spawn; the +-- remaining fields are accepted and ignored. +data CreateProcess = CreateProcess + { cmdspec :: CmdSpec + , cwd :: Maybe FilePath + , env :: Maybe [(String, String)] + , std_in :: StdStream + , std_out :: StdStream + , std_err :: StdStream + , close_fds :: Bool + , create_group :: Bool + , delegate_ctlc :: Bool + , detach_console :: Bool + , create_new_console :: Bool + , new_session :: Bool + , child_group :: Maybe Int + , child_user :: Maybe Int + , use_process_jobs :: Bool + } + +-- | An opaque handle to a spawned child. +newtype ProcessHandle = ProcessHandle MhsChild + +-- | Build a raw process specification. Defaults to inheriting the +-- standard streams and, as in the GHC branch, enabling @delegate_ctlc@. +proc :: FilePath -> [String] -> CreateProcess +proc path args = + CreateProcess + { cmdspec = RawCommand path args + , cwd = Nothing + , env = Nothing + , std_in = Inherit + , std_out = Inherit + , std_err = Inherit + , close_fds = False + , create_group = False + , delegate_ctlc = True + , detach_console = False + , create_new_console = False + , new_session = False + , child_group = Nothing + , child_user = Nothing + , use_process_jobs = False + } + +-- | Build a shell process specification. +shell :: String -> CreateProcess +shell command = (proc "/bin/sh" ["-c", command]) {cmdspec = ShellCommand command} + +-- | Process jobs only exist on Windows; a no-op here. +enableProcessJobs :: CreateProcess -> CreateProcess +enableProcessJobs = id + +-- | Resolve one standard stream for the public 'createProcess' API. +-- Returns the spawn redirection, an optional parent 'Handle', any +-- temporary file the stream owns, and any @(path, handle)@ copy to +-- perform on reap. +-- +-- 'CreatePipe' is rejected outright: a temporary file cannot emulate +-- a blocking pipe, so handing one out would let callers silently +-- observe truncated output. Internal capture paths +-- ('captureProcessOutput', 'newStagedInput') own the +-- stage\/spawn\/wait\/read order instead and never go through here. +resolveStream :: StdStream -> Bool -> IO (MhsRedirect, Maybe Handle, Maybe FilePath, [(FilePath, Handle)]) +resolveStream Inherit _ = pure (MhsInherit, Nothing, Nothing, []) +resolveStream NoStream _ = pure (MhsNull, Nothing, Nothing, []) +resolveStream CreatePipe isStdin = + ioError + ( userError + ( "Distribution.Compat.Process: " + ++ (if isStdin then "std_in" else "std_out/std_err") + ++ " CreatePipe is not supported in the MHS build" + ++ " (temporary files cannot emulate blocking pipes); use" + ++ " captureProcessOutput, readCreateProcessWithExitCode or" + ++ " newStagedInput instead" + ) + ) +resolveStream (UseHandle h) isStdin = do + mtmp <- mhsLookupTemp h + case mtmp of + Just tmp -> pure (MhsFile tmp, Nothing, Nothing, []) + Nothing + | h == stdin -> pure (MhsFd 0, Nothing, Nothing, []) + | h == stdout -> pure (MhsFd 1, Nothing, Nothing, []) + | h == stderr -> pure (MhsFd 2, Nothing, Nothing, []) + | isStdin -> do + -- Assume a regular file: stage its full contents before + -- spawn so the child observes complete input however late + -- it starts reading. 'readBytes' (not 'BS.hGetContents'): + -- on a text-mode handle @c_readb@ falls back to + -- per-character @getb_utf8@, truncating every decoded code + -- point above 0x7F to a single byte. + content <- readBytes h + tmp <- mhsTempFile + BS.writeFile tmp content + pure (MhsFile tmp, Nothing, Just tmp, []) + | otherwise -> do + -- Assume a regular file (e.g. a build log): redirect the + -- child to a temporary file and append it to the handle on + -- reap, so logging keeps working. + tmp <- mhsTempFile + pure (MhsFile tmp, Nothing, Just tmp, [(tmp, h)]) + +-- | Start a child, returning the parent ends of any pipe streams plus +-- a handle to the child. 'CreatePipe' streams are rejected (see +-- 'resolveStream'); only 'Inherit', 'NoStream' and 'UseHandle' +-- streams are supported. +createProcess_ :: String -> CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) +createProcess_ _name cp = do + (redirIn, mIn, tmpIn, copyIn) <- resolveStream (std_in cp) True + (redirOut, mOut, tmpOut, copyOut) <- resolveStream (std_out cp) False + (redirErr, mErr, tmpErr, copyErr) <- resolveStream (std_err cp) False + let (prog, args) = case cmdspec cp of + RawCommand path as -> (path, as) + ShellCommand command -> ("/bin/sh", ["-c", command]) + temps = catMaybes [tmpIn, tmpOut, tmpErr] + copies = copyIn ++ copyOut ++ copyErr + child <- mhsSpawn prog args (cwd cp) (env cp) redirIn redirOut redirErr temps copies + pure (mIn, mOut, mErr, ProcessHandle child) + +-- | Stage @input@ in a temporary file (locale-encoded, like +-- 'System.IO.hPutStr') and hand back a readable 'Handle' suitable +-- for 'UseHandle', plus a cleanup action that closes the handle and +-- removes the file. The input is complete before any child spawned +-- with the handle starts reading, so there is no writer/reader race. +newStagedInput :: String -> IO (Handle, IO ()) +newStagedInput input = do + tmpDir <- getTemporaryDirectory + (tmp, wh) <- openTempFile tmpDir "cabal-staged-input" + hPutStr wh input + hClose wh + rh <- openFile tmp ReadMode + mhsRegisterTemp rh tmp + pure (rh, hClose rh >> removeFile tmp) + +-- | Standard input staging for 'captureProcess'. +-- +-- 'TextInput' is staged with a locale-encoded text write (matching +-- 'System.IO.hPutStr', never 'Data.ByteString.Lazy.Char8.pack', so +-- non-ASCII text round-trips); 'BinaryInput' is staged byte-for-byte. +data StagedInput + = NoInput + | TextInput String + | BinaryInput LBS.ByteString + +-- | Captured standard output of a finished child: the paths holding +-- the complete outputs plus the release action that copies +-- 'UseHandle' redirections back and removes the temporary files. +-- Read the files (with the decoding of your choice) before running +-- 'capturedRelease'; reading before the child has been reaped +-- observes partial data. +data CapturedOutputs = CapturedOutputs + { capturedOutPath :: FilePath + , capturedErrPath :: FilePath + , capturedRelease :: IO () + } + +-- | Run a command to completion, capturing its standard output and +-- error to temporary files. Capture discipline: the input (if any) +-- is staged before spawn, and this function only returns after the +-- child has been reaped, so reading the output paths afterwards is +-- complete by construction and can never silently truncate. +-- +-- The @std_in@, @std_out@ and @std_err@ fields of the 'CreateProcess' +-- are ignored (output always goes to the captured files); only the +-- command, arguments, working directory and environment are +-- honoured. Passing 'CreatePipe' there is pointless but harmless. +captureProcess :: CreateProcess -> StagedInput -> IO (ExitCode, CapturedOutputs) +captureProcess cp staged = do + (redirIn, inTmp) <- case staged of + NoInput -> pure (MhsNull, Nothing) + TextInput input -> do + tmp <- mhsTempFile + writeFile tmp input + pure (MhsFile tmp, Just tmp) + BinaryInput input -> do + tmp <- mhsTempFile + LBS.writeFile tmp input + pure (MhsFile tmp, Just tmp) + outTmp <- mhsTempFile + errTmp <- mhsTempFile + let (prog, args) = case cmdspec cp of + RawCommand path as -> (path, as) + ShellCommand command -> ("/bin/sh", ["-c", command]) + temps = catMaybes [inTmp, Just outTmp, Just errTmp] + child <- mhsSpawn prog args (cwd cp) (env cp) redirIn (MhsFile outTmp) (MhsFile errTmp) temps [] + exit <- mhsJoin child + pure (exit, CapturedOutputs outTmp errTmp (mhsRelease child)) + +-- | Start a child with the default failure context. +createProcess :: CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) +createProcess = createProcess_ "createProcess" + +-- | Release a child created by 'createProcess_': close the pipe +-- 'Handle's, reap the child (waiting if needed, so no zombies are +-- left behind) and delete its temporary files. +cleanupProcess :: (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle) -> IO () +cleanupProcess (mIn, mOut, mErr, ProcessHandle child) = do + mapM_ hClose (catMaybes [mIn, mOut, mErr]) + _ <- mhsWait child + pure () + +-- | Block until the child exits, returning its exit code. Polls +-- @waitpid@ with @WNOHANG@; the result is cached, so repeated calls +-- are cheap. +waitForProcess :: ProcessHandle -> IO ExitCode +waitForProcess (ProcessHandle child) = mhsWait child + +-- | 'System.Process.readCreateProcessWithExitCode' equivalent built +-- on 'captureProcess': the input is staged (locale-encoded, like +-- 'System.IO.hPutStr') before spawn and the outputs are read (locale +-- decoded, like 'System.IO.hGetContents') after reap, so +-- temporary-file redirection is complete by construction. +readCreateProcessWithExitCode :: CreateProcess -> String -> IO (ExitCode, String, String) +readCreateProcessWithExitCode cp input = do + (exit, captured) <- captureProcess (cp {std_in = NoStream, std_out = NoStream, std_err = NoStream}) (TextInput input) + out <- readFile (capturedOutPath captured) + err <- readFile (capturedErrPath captured) + length out `seq` length err `seq` return () + capturedRelease captured + return (exit, out, err) + +-- | 'System.Process.readProcessWithExitCode' equivalent built on +-- 'readCreateProcessWithExitCode'. +readProcessWithExitCode :: FilePath -> [String] -> String -> IO (ExitCode, String, String) +readProcessWithExitCode cmd args = readCreateProcessWithExitCode (proc cmd args) + +-- | 'System.Process.callProcess' equivalent: inherits the standard +-- streams, waits, and throws the exit code on failure. +callProcess :: FilePath -> [String] -> IO () +callProcess cmd args = do + (_, _, _, ph) <- createProcess (proc cmd args) + exit <- waitForProcess ph + cleanupProcess (Nothing, Nothing, Nothing, ph) + case exit of + ExitSuccess -> return () + failure -> throwIO failure + +-- | Non-blocking exit check. +getProcessExitCode :: ProcessHandle -> IO (Maybe ExitCode) +getProcessExitCode (ProcessHandle child) = mhsTryWait child + +-- | Ask the child to terminate with @SIGTERM@. Does not wait. +terminateProcess :: ProcessHandle -> IO () +terminateProcess (ProcessHandle child) = mhsTerminate child + +-- | Rejected in the MHS build: a temporary-file pair cannot emulate +-- a blocking pipe (see 'resolveStream'). Restructure callers to use +-- 'captureProcess', 'readCreateProcessWithExitCode' or +-- 'newStagedInput' instead. +createPipe :: IO (Handle, Handle) +createPipe = + ioError + ( userError + "Distribution.Compat.Process.createPipe is not supported in the MHS build" + ) + +-- | Quote a command line for display, matching "System.Process". +showCommandForUser :: FilePath -> [String] -> String +showCommandForUser cmd args = unwords (map translate (cmd : args)) + where + translate "" = "''" + translate str + | all goodChar str = str + | otherwise = '\'' : foldr escape "'" str + escape '\'' = showString "'\\''" + escape c = showChar c + goodChar c = isAlphaNum c || c `elem` "-_.,/" + +#else + module Distribution.Compat.Process - ( -- * Redefined functions - proc + ( -- * Re-exported module + module System.Process + + -- * Redefined functions + , proc -- * Additions , enableProcessJobs + , captureProcess + , StagedInput (..) + , CapturedOutputs (..) ) where -import System.Process (CreateProcess) +import qualified Data.ByteString.Lazy as LBS +import System.Directory (getTemporaryDirectory, removeFile) +import System.Exit (ExitCode (..)) +import System.IO (IOMode (..), hClose, hPutStr, openFile, openTempFile) +import System.Process hiding (proc) import qualified System.Process as Process #if defined(mingw32_HOST_OS) && MIN_VERSION_process(1,6,9) @@ -61,3 +439,65 @@ enableProcessJobs cp = cp -- and defaulting 'delegate_ctlc' to 'True'. proc :: FilePath -> [String] -> CreateProcess proc path args = enableProcessJobs (Process.proc path args){Process.delegate_ctlc = True} + +-- | How to provide standard input to 'captureProcess'. +data StagedInput + = NoInput + | TextInput String + | BinaryInput LBS.ByteString + +-- | Captured standard output of a finished child: the paths holding +-- the complete outputs plus a release action removing the temporary +-- files. Read the files before running 'capturedRelease'. +data CapturedOutputs = CapturedOutputs + { capturedOutPath :: FilePath + , capturedErrPath :: FilePath + , capturedRelease :: IO () + } + +-- | Run a command to completion, capturing standard output and error +-- to temporary files. The child is reaped before this returns, so +-- reading 'capturedOutPath' and 'capturedErrPath' is complete by +-- construction. Text is staged locale-encoded (like +-- 'System.IO.hPutStr'); binary input is staged byte-for-byte. +captureProcess :: CreateProcess -> StagedInput -> IO (ExitCode, CapturedOutputs) +captureProcess cp staged = do + tmpDir <- getTemporaryDirectory + let stage put = do + (p, h) <- openTempFile tmpDir "cabal-captured-in" + put h + hClose h + inH <- openFile p ReadMode + return (UseHandle inH, p) + mIn <- case staged of + NoInput -> pure Nothing + TextInput s -> Just <$> stage (`hPutStr` s) + BinaryInput b -> Just <$> stage (`LBS.hPutStr` b) + let inStd = case mIn of + Nothing -> NoStream + Just (h, _) -> h + (outTmp, outH) <- openTempFile tmpDir "cabal-captured-out" + (errTmp, errH) <- openTempFile tmpDir "cabal-captured-err" + hClose outH + hClose errH + outW <- openFile outTmp WriteMode + errW <- openFile errTmp WriteMode + (_, _, _, ph) <- + Process.createProcess + cp + { Process.std_in = inStd + , Process.std_out = UseHandle outW + , Process.std_err = UseHandle errW + } + case mIn of + Just (UseHandle h, _) -> hClose h + _ -> return () + hClose outW + hClose errW + exit <- Process.waitForProcess ph + Process.cleanupProcess (Nothing, Nothing, Nothing, ph) + case mIn of + Just (_, p) -> removeFile p + Nothing -> return () + return (exit, CapturedOutputs outTmp errTmp (removeFile outTmp >> removeFile errTmp)) +#endif diff --git a/Cabal/src/Distribution/Compat/ResponseFile.hs b/Cabal/src/Distribution/Compat/ResponseFile.hs index 31f172e0715..4dd04235761 100644 --- a/Cabal/src/Distribution/Compat/ResponseFile.hs +++ b/Cabal/src/Distribution/Compat/ResponseFile.hs @@ -1,8 +1,18 @@ +{-# LANGUAGE CPP #-} + module Distribution.Compat.ResponseFile (expandResponse, escapeArgs) where import Distribution.Compat.Prelude +#ifndef __MHS__ import GHC.ResponseFile (escapeArgs, unescapeArgs) +#else +-- MicroHS does not provide 'GHC.ResponseFile'. The pure argument escaping +-- functions ('escapeArgs', 'unescapeArgs') are inlined below instead, +-- adapted from 'GHC.Internal.ResponseFile' (GCC style response files); +-- 'isSpace' and 'foldl'' come from 'Distribution.Compat.Prelude'. The 'IO' +-- entry point ('expandResponse') is unchanged and shared. +#endif import Prelude () @@ -32,3 +42,78 @@ expandResponse = go recursionLimit "." readRecursively :: Int -> FilePath -> IO [String] readRecursively n f = go (n - 1) (takeDirectory f) . unescapeArgs =<< readFile f + +#ifdef __MHS__ +-- | Given a list of strings, concatenate them into a single string with +-- escaping of certain characters, and the addition of a newline between +-- each string. The escaping is done by adding a single backslash character +-- before any whitespace, single quote, double quote, or backslash +-- character. Unescaped whitespace (in this case, newline) is part of this +-- \"transport\" format to indicate the end of the previous string and the +-- start of a new string. +-- +-- While 'unescapeArgs' allows using quoting (i.e. convenient escaping of +-- many characters) by having matching sets of single- or double-quotes, +-- 'escapeArgs' does not use the quoting mechanism, and thus will always +-- escape any whitespace, quotes, and backslashes. +-- +-- > escapeArgs ["hello \"world\""] == "hello\\ \\\"world\\\"\n" +escapeArgs :: [String] -> String +escapeArgs = unlines . map escapeArg + +-- | Given a string of concatenated strings, separate each by removing a +-- layer of /quoting/ and\/or /escaping/ of certain characters. +-- +-- These characters are: any whitespace, single quote, double quote, and +-- the backslash character. The backslash character always escapes (i.e. +-- passes through without further consideration) the character which +-- follows. Characters can also be escaped in blocks by quoting (i.e. +-- surrounding the blocks with matching pairs of either single- or +-- double-quotes which are not themselves escaped). +-- +-- Any whitespace which appears outside of either of the quoting and +-- escaping mechanisms, is interpreted as having been added by this special +-- concatenation process to designate where the boundaries are between the +-- original, un-concatenated list of strings. These added whitespace +-- characters are removed from the output. +-- +-- > unescapeArgs "hello\\ \\\"world\\\"\n" == ["hello \"world\""] +unescapeArgs :: String -> [String] +unescapeArgs = filter (not . null) . unescape + +escapeArg :: String -> String +escapeArg = reverse . foldl' escape [] + +escape :: String -> Char -> String +escape cs c + | isSpace c || c == '\\' || c == '\'' || c == '"' = c : '\\' : cs -- n.b., our caller must reverse the result + | otherwise = c : cs + +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 [] _ _ 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 diff --git a/Cabal/src/Distribution/Compat/Stack.hs b/Cabal/src/Distribution/Compat/Stack.hs index 22b6015c96e..25b95d68e2c 100644 --- a/Cabal/src/Distribution/Compat/Stack.hs +++ b/Cabal/src/Distribution/Compat/Stack.hs @@ -1,8 +1,10 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE ImplicitParams #-} module Distribution.Compat.Stack ( WithCallStack , CallStack + , HasCallStack , withFrozenCallStack , withLexicalCallStack , callStack @@ -10,6 +12,43 @@ module Distribution.Compat.Stack , parentSrcLocPrefix ) where +#ifdef __MHS__ + +-- MicroHs has no call-stack support: there is no 'GHC.Stack' module +-- and it does not implement 'ImplicitParams'. This variant provides +-- the same API with neutral behaviour (empty call stacks, identity +-- wrappers) so that the rest of the tree typechecks. + +type WithCallStack a = a + +data CallStack = NoCallStack + deriving (Show) + +class HasCallStack + +instance HasCallStack + +withFrozenCallStack :: WithCallStack a -> WithCallStack a +withFrozenCallStack x = x + +withLexicalCallStack :: (a -> WithCallStack (IO b)) -> WithCallStack (a -> IO b) +withLexicalCallStack f = \x -> f x + +callStack :: CallStack +callStack = NoCallStack + +prettyCallStack :: CallStack -> String +prettyCallStack _ = "" + +-- | Give the *parent* of the person who invoked this; +-- so it's most suitable for being called from a utility function. +-- You probably want to call this using 'withFrozenCallStack'; otherwise +-- it's not very useful. +parentSrcLocPrefix :: WithCallStack String +parentSrcLocPrefix = "" + +#else + import GHC.Stack type WithCallStack a = HasCallStack => a @@ -33,3 +72,5 @@ withLexicalCallStack :: (a -> WithCallStack (IO b)) -> WithCallStack (a -> IO b) withLexicalCallStack f = let stk = ?callStack in \x -> let ?callStack = stk in f x + +#endif diff --git a/Cabal/src/Distribution/Compat/Time.hs b/Cabal/src/Distribution/Compat/Time.hs index 0e2e7e20e8b..dbdf723b5ce 100644 --- a/Cabal/src/Distribution/Compat/Time.hs +++ b/Cabal/src/Distribution/Compat/Time.hs @@ -9,7 +9,7 @@ where import Distribution.Compat.Prelude import Prelude () -import System.Directory (getModificationTime) +import Distribution.Compat.Directory (getModificationTime) import Data.Time (diffUTCTime, getCurrentTime) import Data.Time.Clock.POSIX (POSIXTime, getPOSIXTime, posixDayLength, utcTimeToPOSIXSeconds) diff --git a/Cabal/src/Distribution/PackageDescription/Check.hs b/Cabal/src/Distribution/PackageDescription/Check.hs index c3c00b6cf3d..9cb082a6bd2 100644 --- a/Cabal/src/Distribution/PackageDescription/Check.hs +++ b/Cabal/src/Distribution/PackageDescription/Check.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.PackageDescription.Check -- Copyright : Lennart Kolmodin 2008, Francesco Ariis 2022 @@ -51,6 +49,7 @@ import Data.Text (Text) import Distribution.CabalSpecVersion import Distribution.Compat.Lens import Distribution.Compiler +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.FieldGrammar.Parsec (freeTextIgnoreDotlineVers) import Distribution.License import Distribution.ModuleName (toFilePath) @@ -80,9 +79,9 @@ import System.FilePath (splitExtension, takeFileName) import qualified Data.ByteString.Lazy as BS import qualified Distribution.SPDX as SPDX -import qualified System.Directory as System +import qualified Distribution.Compat.Directory as System -import qualified System.Directory (listDirectory) +import qualified Distribution.Compat.Directory (listDirectory) import qualified System.FilePath.Windows as FilePath.Windows (isValid) import qualified Data.Set as Set @@ -94,7 +93,8 @@ import qualified Distribution.Compat.Lens as L import qualified Distribution.Types.BuildInfo.Lens as L import qualified Distribution.Types.GenericPackageDescription.Lens as L -import Control.Monad +import Control.Monad hiding (forM_, mapM, mapM_, sequence, sequence_) +import Data.Foldable (forM_, mapM_, sequence_) -- $setup -- >>> import Control.Arrow ((&&&)) @@ -178,14 +178,14 @@ checkPackageFilesGPD verbosity gpd root = CheckPackageContentOps { doesFileExist = System.doesFileExist . relative , doesDirectoryExist = System.doesDirectoryExist . relative - , listDirectory = System.Directory.listDirectory . relative - , getFileContents = BS.readFile . relative + , listDirectory = Distribution.Compat.Directory.listDirectory . relative + , getFileContents = readFileLBS . relative } checkPreIO = CheckPreDistributionOps { runDirFileGlobM = \fp g -> runDirFileGlob verbosity (Just . specVersion $ packageDescription gpd) (root fp) g - , listDirectoryM = System.Directory.listDirectory . relative + , listDirectoryM = Distribution.Compat.Directory.listDirectory . relative } relative :: FilePath -> FilePath diff --git a/Cabal/src/Distribution/PackageDescription/Check/Warning.hs b/Cabal/src/Distribution/PackageDescription/Check/Warning.hs index 88c838f2f7f..864c68fdd9a 100644 --- a/Cabal/src/Distribution/PackageDescription/Check/Warning.hs +++ b/Cabal/src/Distribution/PackageDescription/Check/Warning.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} -- | @@ -45,7 +44,7 @@ import Distribution.Types.PackageName (PackageName) import Distribution.Types.TestType (TestType, knownTestTypes) import Distribution.Types.UnqualComponentName import Distribution.Types.Version (Version) -import Distribution.Utils.Path (FileOrDir (..), Pkg, RelativePath, getSymbolicPath) +import Distribution.Utils.Path (File, Pkg, RelativePath, getSymbolicPath) import Language.Haskell.Extension (Extension) import qualified Data.Either as Either diff --git a/Cabal/src/Distribution/Simple.hs b/Cabal/src/Distribution/Simple.hs index f1dbf736419..9838aec80f5 100644 --- a/Cabal/src/Distribution/Simple.hs +++ b/Cabal/src/Distribution/Simple.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE OverloadedStrings #-} {- @@ -128,7 +128,7 @@ import Language.Haskell.Extension -- Base import Data.List (unionBy, (\\)) -import System.Directory (removePathForcibly) +import Distribution.Compat.Directory (removePathForcibly) import System.Environment (getArgs, getProgName) import System.IO (hPutStr, hPutStrLn) @@ -153,6 +153,10 @@ defaultMainWithSetupHooks setupHooks = getArgs >>= defaultMainWithSetupHooksArgs setupHooks defaultVerbosityHandles defaultMainWithSetupHooksArgs :: SetupHooks -> VerbosityHandles -> [String] -> IO () +#ifdef __MHS__ +defaultMainWithSetupHooksArgs _ _ _ = + error "build-type: Hooks is not supported in this MHS build of Cabal." +#else defaultMainWithSetupHooksArgs setupHooks verbHandles = defaultMainHelper $ simpleUserHooks @@ -274,6 +278,7 @@ defaultMainWithSetupHooksArgs setupHooks verbHandles = lbi (allSuffixHandlers hooks) flags +#endif -- | A customizable version of 'defaultMain'. defaultMainWithHooks :: UserHooks -> IO () @@ -603,7 +608,7 @@ cleanAction verbHandles globalFlags hooks flags args = do flags' = flags{cleanCommonFlags = common'} - mbWorkDirFlag = cleanWorkingDir flags' + mbWorkDirFlag = setupWorkingDir $ cleanCommonFlags flags' mbWorkDir = flagToMaybe mbWorkDirFlag pbi <- preClean hooks args flags' @@ -661,7 +666,7 @@ installAction verbHandles globalFlags hooks flags args = do -- Since Cabal-3.4 UserHooks are completely ignored sdistAction :: VerbosityHandles -> GlobalFlags -> UserHooks -> SDistFlags -> Args -> IO () sdistAction verbHandles _globalFlags _hooks flags _args = do - let mbWorkDir = flagToMaybe $ sDistWorkingDir flags + let mbWorkDir = flagToMaybe $ setupWorkingDir $ sDistCommonFlags flags (_, ppd) <- confPkgDescr emptyUserHooks verbosity mbWorkDir Nothing let pkg_descr = flattenPackageDescription ppd sdist verbHandles pkg_descr flags srcPref knownSuffixHandlers @@ -1082,9 +1087,9 @@ autoconfSetupHooks = , SetupHooks.component = component } ) = do - let verbosity = mkVerbosity defaultVerbosityHandles (fromFlag $ configVerbosity cfg) - mbWorkDir = flagToMaybe $ configWorkingDir cfg - distPref = configDistPref cfg + let verbosity = mkVerbosity defaultVerbosityHandles (fromFlag $ setupVerbosity $ configCommonFlags cfg) + mbWorkDir = flagToMaybe $ setupWorkingDir $ configCommonFlags cfg + distPref = setupDistPref $ configCommonFlags cfg dist_dir <- findDistPrefOrDefault distPref -- Read the ".buildinfo" file and use that to update -- the components (main library + executables only). diff --git a/Cabal/src/Distribution/Simple/Bench.hs b/Cabal/src/Distribution/Simple/Bench.hs index faa6f2c8058..84b42a78632 100644 --- a/Cabal/src/Distribution/Simple/Bench.hs +++ b/Cabal/src/Distribution/Simple/Bench.hs @@ -39,7 +39,7 @@ import Distribution.Types.UnqualComponentName import Distribution.Utils.Path import Distribution.Verbosity -import System.Directory (doesFileExist) +import Distribution.Compat.Directory (doesFileExist) -- | Perform the \"@.\/setup bench@\" action. bench @@ -55,11 +55,11 @@ bench -> IO () bench args verbHandles pkg_descr lbi flags = do curDir <- LBI.absoluteWorkingDirLBI lbi - let verbosity = mkVerbosity verbHandles (fromFlag $ benchmarkVerbosity flags) + let verbosity = mkVerbosity verbHandles (fromFlag $ setupVerbosity $ benchmarkCommonFlags flags) benchmarkNames = args pkgBenchmarks = PD.benchmarks pkg_descr enabledBenchmarks = LBI.enabledBenchLBIs pkg_descr lbi - mbWorkDir = flagToMaybe $ benchmarkWorkingDir flags + mbWorkDir = flagToMaybe $ setupWorkingDir $ benchmarkCommonFlags flags i = interpretSymbolicPath mbWorkDir -- See Note [Symbolic paths] in Distribution.Utils.Path -- Run the benchmark diff --git a/Cabal/src/Distribution/Simple/Build.hs b/Cabal/src/Distribution/Simple/Build.hs index 9f392325f0c..ac4121bb453 100644 --- a/Cabal/src/Distribution/Simple/Build.hs +++ b/Cabal/src/Distribution/Simple/Build.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE LambdaCase #-} @@ -121,13 +122,32 @@ import Distribution.Version (thisVersion) import Distribution.Compat.Graph (IsNode (..)) -import Control.Monad import qualified Data.ByteString.Lazy as LBS import qualified Data.Map as Map import qualified Data.Text as Text import System.FilePath (takeDirectory) +#ifdef __MHS__ +buildVerbosity :: BuildFlags -> Flag VerbosityFlags +buildVerbosity = setupVerbosity . buildCommonFlags + +buildDistPref :: BuildFlags -> Flag (SymbolicPath Pkg (Dir Dist)) +buildDistPref = setupDistPref . buildCommonFlags + +buildWorkingDir :: BuildFlags -> Flag (SymbolicPath CWD (Dir Pkg)) +buildWorkingDir = setupWorkingDir . buildCommonFlags + +buildTargets :: BuildFlags -> [String] +buildTargets = setupTargets . buildCommonFlags + +replVerbosity :: ReplFlags -> Flag VerbosityFlags +replVerbosity = setupVerbosity . replCommonFlags + +replDistPref :: ReplFlags -> Flag (SymbolicPath Pkg (Dir Dist)) +replDistPref = setupDistPref . replCommonFlags +#endif + -- ----------------------------------------------------------------------------- -- | Build the libraries and executables in this package. @@ -216,7 +236,7 @@ build_setupHooks par_strat <- toFlag <$> case buildUseSemaphore flags of Flag sem_name -> case numJobs of - Flag{} -> do + Flag _ -> do warn verbosity "Ignoring -j due to --semaphore" return $ UseSem sem_name NoFlag -> return $ UseSem sem_name diff --git a/Cabal/src/Distribution/Simple/Build/Macros/Z.hs b/Cabal/src/Distribution/Simple/Build/Macros/Z.hs index b43407f1b2a..c9e1d2da9df 100644 --- a/Cabal/src/Distribution/Simple/Build/Macros/Z.hs +++ b/Cabal/src/Distribution/Simple/Build/Macros/Z.hs @@ -1,4 +1,5 @@ {- FOURMOLU_DISABLE -} +{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} module Distribution.Simple.Build.Macros.Z (render, Z(..), ZPackage (..), ZTool (..)) where import Distribution.ZinzaPrelude @@ -11,21 +12,27 @@ data Z zNotNull :: (String -> Bool), zManglePkgName :: (PackageName -> String), zMangleStr :: (String -> String)} +#ifndef __MHS__ deriving Generic +#endif data ZPackage = ZPackage {zpkgName :: PackageName, zpkgVersion :: Version, zpkgX :: String, zpkgY :: String, zpkgZ :: String} +#ifndef __MHS__ deriving Generic +#endif data ZTool = ZTool {ztoolName :: String, ztoolVersion :: Version, ztoolX :: String, ztoolY :: String, ztoolZ :: String} +#ifndef __MHS__ deriving Generic +#endif render :: Z -> String render z_root = execWriter $ do tell "/* DO NOT EDIT: This file is automatically generated by Cabal */\n" diff --git a/Cabal/src/Distribution/Simple/Build/PackageInfoModule/Z.hs b/Cabal/src/Distribution/Simple/Build/PackageInfoModule/Z.hs index ad03f4ff7e3..f2a3a8cd3a4 100644 --- a/Cabal/src/Distribution/Simple/Build/PackageInfoModule/Z.hs +++ b/Cabal/src/Distribution/Simple/Build/PackageInfoModule/Z.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} module Distribution.Simple.Build.PackageInfoModule.Z (render, Z (..)) where import Distribution.ZinzaPrelude (Generic, execWriter, tell) @@ -9,7 +10,9 @@ data Z = Z , zCopyright :: String , zHomepage :: String } +#ifndef __MHS__ deriving (Generic) +#endif render :: Z -> String render z_root = execWriter $ do diff --git a/Cabal/src/Distribution/Simple/Build/PathsModule/Z.hs b/Cabal/src/Distribution/Simple/Build/PathsModule/Z.hs index e324c8ea11c..aaea7c242d9 100644 --- a/Cabal/src/Distribution/Simple/Build/PathsModule/Z.hs +++ b/Cabal/src/Distribution/Simple/Build/PathsModule/Z.hs @@ -1,4 +1,5 @@ {- FOURMOLU_DISABLE -} +{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} module Distribution.Simple.Build.PathsModule.Z (render, Z(..)) where import Distribution.ZinzaPrelude @@ -20,7 +21,9 @@ data Z zSysconfdir :: FilePath, zNot :: (Bool -> Bool), zManglePkgName :: (PackageName -> String)} +#ifndef __MHS__ deriving Generic +#endif render :: Z -> String render z_root = execWriter $ do tell "{-# LANGUAGE CPP #-}\n" diff --git a/Cabal/src/Distribution/Simple/BuildPaths.hs b/Cabal/src/Distribution/Simple/BuildPaths.hs index 8f77b954623..59ffc51c3ba 100644 --- a/Cabal/src/Distribution/Simple/BuildPaths.hs +++ b/Cabal/src/Distribution/Simple/BuildPaths.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.BuildPaths -- Copyright : Isaac Jones 2003-2004, @@ -246,7 +244,7 @@ getExeSourceFiles -> LocalBuildInfo -> Executable -> ComponentLocalBuildInfo - -> IO [(ModuleName.ModuleName, SymbolicPath Pkg 'File)] + -> IO [(ModuleName.ModuleName, SymbolicPath Pkg File)] getExeSourceFiles verbosity lbi exe clbi = do moduleFiles <- getSourceFiles verbosity mbWorkDir searchpaths modules srcMainPath <- findFileCwd verbosity mbWorkDir (hsSourceDirs bi) (modulePath exe) @@ -266,7 +264,7 @@ getTestSourceFiles -> LocalBuildInfo -> TestSuite -> ComponentLocalBuildInfo - -> IO [(ModuleName.ModuleName, SymbolicPath Pkg 'File)] + -> IO [(ModuleName.ModuleName, SymbolicPath Pkg File)] getTestSourceFiles verbosity lbi test@TestSuite{testInterface = TestSuiteExeV10 _ path} clbi = do moduleFiles <- getSourceFiles verbosity mbWorkDir searchpaths modules srcMainPath <- findFileCwd verbosity mbWorkDir (hsSourceDirs bi) path @@ -287,7 +285,7 @@ getBenchmarkSourceFiles -> LocalBuildInfo -> Benchmark -> ComponentLocalBuildInfo - -> IO [(ModuleName.ModuleName, SymbolicPath Pkg 'File)] + -> IO [(ModuleName.ModuleName, SymbolicPath Pkg File)] getBenchmarkSourceFiles verbosity lbi bench@Benchmark{benchmarkInterface = BenchmarkExeV10 _ path} clbi = do moduleFiles <- getSourceFiles verbosity mbWorkDir searchpaths modules srcMainPath <- findFileCwd verbosity mbWorkDir (hsSourceDirs bi) path @@ -323,7 +321,7 @@ getFLibSourceFiles verbosity lbi flib clbi = getSourceFiles :: Verbosity - -> Maybe (SymbolicPath CWD ('Dir Pkg)) + -> Maybe (SymbolicPath CWD (Dir Pkg)) -> [SymbolicPathX allowAbsolute Pkg (Dir Source)] -> [ModuleName.ModuleName] -> IO [(ModuleName.ModuleName, SymbolicPathX allowAbsolute Pkg File)] diff --git a/Cabal/src/Distribution/Simple/BuildTarget.hs b/Cabal/src/Distribution/Simple/BuildTarget.hs index c4219c88c8f..2456cafada6 100644 --- a/Cabal/src/Distribution/Simple/BuildTarget.hs +++ b/Cabal/src/Distribution/Simple/BuildTarget.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} -- | @@ -60,7 +59,7 @@ import Control.Monad (msum) import Data.List (groupBy, stripPrefix) import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map -import System.Directory (doesDirectoryExist, doesFileExist) +import Distribution.Compat.Directory (doesDirectoryExist, doesFileExist) import System.FilePath as FilePath ( dropExtension , hasTrailingPathSeparator diff --git a/Cabal/src/Distribution/Simple/Command.hs b/Cabal/src/Distribution/Simple/Command.hs index d3cff2db4e8..10f4bc8d377 100644 --- a/Cabal/src/Distribution/Simple/Command.hs +++ b/Cabal/src/Distribution/Simple/Command.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} -- | @@ -84,7 +85,9 @@ import Distribution.Compat.Prelude hiding (get) import Prelude () import qualified Data.Array as Array +#ifndef __MHS__ import Data.Either (rights) +#endif import qualified Data.List as List import Distribution.Compat.Lens (ALens', (#~), (^#)) import qualified Distribution.GetOpt as GetOpt diff --git a/Cabal/src/Distribution/Simple/Compiler.hs b/Cabal/src/Distribution/Simple/Compiler.hs index 507de08a172..da464cf89f0 100644 --- a/Cabal/src/Distribution/Simple/Compiler.hs +++ b/Cabal/src/Distribution/Simple/Compiler.hs @@ -1,5 +1,4 @@ -{-# LANGUAGE DataKinds #-} - +{-# LANGUAGE CPP #-} -- | -- Module : Distribution.Simple.Compiler -- Copyright : Isaac Jones 2003-2004 @@ -93,6 +92,7 @@ module Distribution.Simple.Compiler ) where import Distribution.Compat.CharParsing +import Data.Foldable (Foldable) import Distribution.Compat.Prelude import Distribution.Parsec import Distribution.Pretty @@ -101,6 +101,7 @@ import Prelude () import Distribution.Compiler import Distribution.Package (PackageName, mkPackageName, unPackageName) import Distribution.Simple.Utils +import Distribution.System (Platform) import Distribution.Types.UnitId (UnitId, mkUnitId, unUnitId) import Distribution.Utils.Path import Distribution.Version @@ -110,8 +111,9 @@ import qualified Text.Read as Read import Language.Haskell.Extension import Data.Bool (bool) -import qualified Data.Map as Map (lookup) -import System.Directory (canonicalizePath) +import Data.Char (isAscii) +import qualified Data.Map as Map +import Distribution.Compat.Directory (canonicalizePath) data Compiler = Compiler { compilerId :: CompilerId @@ -247,6 +249,85 @@ compilerFlavor = (\(CompilerId f _) -> f) . compilerId compilerVersion :: Compiler -> Version compilerVersion = (\(CompilerId _ v) -> v) . compilerId +-- | The compiler's intrinsic target ABI, independently of its architecture +-- and OS. Older compilers omit this property and retain their existing ABI. +compilerTargetAbi :: Compiler -> String +compilerTargetAbi = Map.findWithDefault "" "Target ABI" . compilerProperties + +-- | A validated, opaque logical target identity. The value is kept as a +-- string because the producer owns canonicalization; Cabal only validates +-- that it is safe to use as a single path component. +newtype TargetName = TargetName String + deriving (Eq, Ord, Show) + +renderTargetName :: TargetName -> String +renderTargetName (TargetName name) = name + +parseTargetName :: String -> Either String TargetName +parseTargetName name + | null name = Left "target name is empty" + | length name > 255 = Left "target name exceeds the 255-character filesystem component limit" + | not (all safeChar name) = Left "target name contains an unsafe character" + | not (hasAlphaNumEndpoints name) = Left "target name must begin and end with a letter or digit" +#ifdef __MHS__ + | any (\p -> p == "" || p == "." || p == "..") (splitOn "-" name) = Left "target name contains an empty or dot path component" +#else + | any (`elem` ["", ".", ".."]) (splitOn "-" name) = Left "target name contains an empty or dot path component" +#endif + | otherwise = Right (TargetName name) + where +#ifdef __MHS__ + -- MicroHs treats string literals as overloaded, so `elem` over literals + -- fails to resolve; spell out the comparisons (identical semantics). + safeChar c = isAscii c && (isAlphaNum c || c == '_' || c == '.' || c == '-') +#else + safeChar c = isAscii c && (isAlphaNum c || c `elem` "_.-") +#endif + hasAlphaNumEndpoints [] = False + hasAlphaNumEndpoints (firstChar:rest) = isAlphaNum firstChar && lastIsAlphaNum firstChar rest + lastIsAlphaNum lastChar [] = isAlphaNum lastChar + lastIsAlphaNum _ (nextChar:rest) = lastIsAlphaNum nextChar rest + splitOn sep = foldr step [""] + where + step c (x:xs) | [c] == sep = "" : x : xs + step c (x:xs) = (c:x) : xs + step _ [] = [] + +-- | Return the canonical target identity, validating new-protocol metadata. +-- Older compilers retain their full Target platform string where available, +-- with the historical Platform rendering as the final fallback. +compilerTargetName :: Platform -> Compiler -> Either String TargetName +compilerTargetName platform comp = + case (Map.lookup "Target name" props, Map.lookup "Target platform" props, compilerTargetAbi comp) of + (Just name, Just machine, abi) -> do + target <- parseTargetName name + _ <- parseTargetName machine + let expected = machine ++ if abi == "profiling" then "-prof" else "" + if abi `notElem` ["", "profiling"] + then Left ("unsupported Target ABI: " ++ abi) + else if name /= expected + then Left "Target name contradicts Target platform and Target ABI" + else if length name + 1 + length (prettyShow (compilerVersion comp)) > 255 + then Left "target name plus compiler version exceeds the 255-character filesystem component limit" + else Right target + (Just _, Nothing, _) -> Left "Target name requires Target platform" + (Nothing, Just machine, abi) -> do + _ <- parseTargetName machine + if abi `notElem` ["", "profiling"] + then Left ("unsupported Target ABI: " ++ abi) + else parseTargetName (machine ++ if abi == "profiling" then "-prof" else "") + (Nothing, Nothing, abi) + | abi `notElem` ["", "profiling"] -> Left ("unsupported Target ABI: " ++ abi) + | otherwise -> parseTargetName (prettyShow platform ++ if abi == "profiling" then "-prof" else "") + where + props = compilerProperties comp + +-- | Profiling is intrinsic to this target, rather than an additional library +-- way. Its ordinary objects and interfaces already use the profiling ABI. +compilerTargetsProfiling :: Compiler -> Bool +compilerTargetsProfiling comp = + compilerFlavor comp == GHC && compilerTargetAbi comp == "profiling" + -- | Is this compiler compatible with the compiler flavour we're interested in? -- -- For example this checks if the compiler is actually GHC or is another @@ -641,6 +722,22 @@ profilingDynamicSupportedOrUnknown :: Compiler -> Bool profilingDynamicSupportedOrUnknown comp = profilingDynamicSupported comp `elem` [Just True, Nothing] +-- | Whether the selected profiling target includes a debug RTS variant. +profilingDebugSupported :: Compiler -> Maybe Bool +profilingDebugSupported comp + | compilerTargetsProfiling comp + , GHC <- compilerFlavor comp + , compilerVersion comp >= mkVersion [9, 10, 1] = + case Map.lookup "RTS ways" (compilerProperties comp) of +#ifdef __MHS__ + Just ways -> Just (any (\w -> w == "debug" || w == "thr_debug") (words ways)) +#else + Just ways -> Just (any (`elem` words ways) ["debug", "thr_debug"]) +#endif + Nothing -> Just False + | compilerTargetsProfiling comp = Nothing + | otherwise = Just False + -- | Is the compiler distributed with dynamic libraries dynamicSupported :: Compiler -> Maybe Bool dynamicSupported comp = waySupported "dyn" comp diff --git a/Cabal/src/Distribution/Simple/Configure.hs b/Cabal/src/Distribution/Simple/Configure.hs index 53b99b349d0..9b10c4017a6 100644 --- a/Cabal/src/Distribution/Simple/Configure.hs +++ b/Cabal/src/Distribution/Simple/Configure.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} @@ -71,7 +71,8 @@ module Distribution.Simple.Configure , platformDefines ) where -import Control.Monad +import Control.Monad hiding (forM_, mapM, mapM_, sequence, sequence_) +import Data.Foldable (mapM_) import Distribution.Compat.Prelude import Prelude () @@ -160,7 +161,7 @@ import Distribution.Simple.Errors import Distribution.Types.AnnotatedId import Distribution.Utils.Path import Distribution.Utils.Structured (structuredDecodeOrFailIO, structuredEncode) -import System.Directory +import Distribution.Compat.Directory ( canonicalizePath , createDirectoryIfMissing , doesFileExist @@ -192,6 +193,20 @@ import qualified Data.Maybe as M import qualified Data.Set as Set import qualified Distribution.Compat.NonEmptySet as NES +#ifdef __MHS__ +configVerbosity :: ConfigFlags -> Flag VerbosityFlags +configVerbosity = setupVerbosity . configCommonFlags + +configDistPref :: ConfigFlags -> Flag (SymbolicPath Pkg (Dir Dist)) +configDistPref = setupDistPref . configCommonFlags + +configWorkingDir :: ConfigFlags -> Flag (SymbolicPath CWD (Dir Pkg)) +configWorkingDir = setupWorkingDir . configCommonFlags + +configTargets :: ConfigFlags -> [String] +configTargets = setupTargets . configCommonFlags +#endif + type UseExternalInternalDeps = Bool -- | The errors that can be thrown when reading the @setup-config@ file. @@ -1516,10 +1531,16 @@ configureComponents } lbi = +#ifdef __MHS__ + -- MicroHs cannot parse the record pattern synonym for + -- 'LocalBuildInfo', which is a real flat record there. + mkFlatLocalBuildInfo lbd lbc +#else NewLocalBuildInfo { localBuildDescr = lbd , localBuildConfig = lbc } +#endif when (LBC.relocatable $ LBC.withBuildOptions lbc) $ checkRelocatable verbosity pkg_descr lbi @@ -2304,7 +2325,7 @@ getPackageDBContents verbosity comp mbWorkDir packageDB progdb = do getInstalledPackagesMonitorFiles :: Verbosity -> Compiler - -> Maybe (SymbolicPath CWD ('Dir from)) + -> Maybe (SymbolicPath CWD (Dir from)) -> PackageDBStackS from -> ProgramDb -> Platform diff --git a/Cabal/src/Distribution/Simple/ConfigureScript.hs b/Cabal/src/Distribution/Simple/ConfigureScript.hs index cd9a01c4c54..8285bf02606 100644 --- a/Cabal/src/Distribution/Simple/ConfigureScript.hs +++ b/Cabal/src/Distribution/Simple/ConfigureScript.hs @@ -1,5 +1,4 @@ {-# LANGUAGE CPP #-} -{-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# OPTIONS_GHC -Wno-deprecations #-} @@ -35,7 +34,7 @@ import Distribution.Utils.Path import Distribution.Verbosity -- Base -import System.Directory (createDirectoryIfMissing, doesFileExist, makeAbsolute) +import Distribution.Compat.Directory (createDirectoryIfMissing, doesFileExist, makeAbsolute) import qualified System.FilePath as FilePath #ifdef mingw32_HOST_OS import System.FilePath (normalise, splitDrive) diff --git a/Cabal/src/Distribution/Simple/Errors.hs b/Cabal/src/Distribution/Simple/Errors.hs index 24b4891f0c3..be0df4512ba 100644 --- a/Cabal/src/Distribution/Simple/Errors.hs +++ b/Cabal/src/Distribution/Simple/Errors.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + ----------------------------------------------------------------------------- -- Module : Distribution.Simple.Errors @@ -638,11 +640,21 @@ exceptionMessage e = case e of ] _ -> [] where +#ifdef __MHS__ + plural = case libs of + _ : _ : _ -> True + _ -> False + missing = + case libs of + _ : _ -> True + [] -> case hdr of Just (Left _) -> True; _ -> False +#else plural = length libs >= 2 -- Is there something missing? (as opposed to broken) missing = not (null libs) || case hdr of Just (Left _) -> True; _ -> False +#endif messageSingular = "This problem can usually be solved by installing the system " ++ "package that provides this library (you may need the " diff --git a/Cabal/src/Distribution/Simple/GHC.hs b/Cabal/src/Distribution/Simple/GHC.hs index c3064ee3853..c0b96731084 100644 --- a/Cabal/src/Distribution/Simple/GHC.hs +++ b/Cabal/src/Distribution/Simple/GHC.hs @@ -1,5 +1,4 @@ {-# LANGUAGE CPP #-} -{-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} @@ -127,19 +126,22 @@ import System.FilePath , takeFileName ) import qualified System.Info -#ifndef mingw32_HOST_OS +#if !defined(mingw32_HOST_OS) && !defined(__MHS__) && !defined(MHS) +-- MicroHs has no @unix@ package, so there is no 'System.Posix' under +-- MHS: versioned foreign-library symlinks are skipped there, as on +-- Windows (see below). import System.Posix (createSymbolicLink) #endif /* mingw32_HOST_OS */ {- FOURMOLU_DISABLE -} -import System.Directory +import Distribution.Compat.Directory ( canonicalizePath , createDirectoryIfMissing , doesDirectoryExist , doesFileExist , getAppUserDataDirectory , listDirectory -#ifndef mingw32_HOST_OS +#if !defined(mingw32_HOST_OS) && !defined(__MHS__) && !defined(MHS) , renameFile #endif ) @@ -943,7 +945,7 @@ installFLib verbosity lbi targetDir builtDir _pkg flib = let (Platform _ os) = hostPlatform lbi unless (null (foreignLibVersion flib os)) $ do when (os /= Linux) $ dieWithException verbosity CantInstallForeignLib -#ifndef mingw32_HOST_OS +#if !defined(mingw32_HOST_OS) && !defined(__MHS__) && !defined(MHS) -- 'createSymbolicLink file1 file2' creates a symbolic link -- named 'file2' which points to the file 'file1'. -- Note that we do want a symlink to 'name' rather than diff --git a/Cabal/src/Distribution/Simple/GHC/Build.hs b/Cabal/src/Distribution/Simple/GHC/Build.hs index 3d3dc3de1e6..46ad8ca5705 100644 --- a/Cabal/src/Distribution/Simple/GHC/Build.hs +++ b/Cabal/src/Distribution/Simple/GHC/Build.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Simple.GHC.Build where import Distribution.Compat.Prelude @@ -86,9 +84,9 @@ build numJobs verbHandles pkg_descr pbci = do -- Create a few directories for building the component -- See Note [Build Target Dir vs Target Dir] - let targetDir0 :: SymbolicPath Pkg ('Dir Build) + let targetDir0 :: SymbolicPath Pkg (Dir Build) targetDir0 = componentBuildDir lbi clbi - buildTargetDir0 :: SymbolicPath Pkg ('Dir Artifacts) + buildTargetDir0 :: SymbolicPath Pkg (Dir Artifacts) buildTargetDir0 -- Libraries use the target dir for building (see above) | isLib = coerceSymbolicPath targetDir0 diff --git a/Cabal/src/Distribution/Simple/GHC/Build/ExtraSources.hs b/Cabal/src/Distribution/Simple/GHC/Build/ExtraSources.hs index 3fe16f28b73..6501aa926b9 100644 --- a/Cabal/src/Distribution/Simple/GHC/Build/ExtraSources.hs +++ b/Cabal/src/Distribution/Simple/GHC/Build/ExtraSources.hs @@ -1,11 +1,10 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DisambiguateRecordFields #-} {-# LANGUAGE LambdaCase #-} module Distribution.Simple.GHC.Build.ExtraSources where import Control.Monad -import Data.Foldable +import Data.Foldable (traverse_) import Distribution.Simple.Flag import qualified Distribution.Simple.GHC.Internal as Internal import Distribution.Simple.Program diff --git a/Cabal/src/Distribution/Simple/GHC/Build/Link.hs b/Cabal/src/Distribution/Simple/GHC/Build/Link.hs index 99f9135eb61..a0db903be07 100644 --- a/Cabal/src/Distribution/Simple/GHC/Build/Link.hs +++ b/Cabal/src/Distribution/Simple/GHC/Build/Link.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} module Distribution.Simple.GHC.Build.Link where @@ -6,7 +5,7 @@ module Distribution.Simple.GHC.Build.Link where import Distribution.Compat.Prelude import Prelude () -import Control.Monad +import Control.Monad hiding (mapM, sequence) import Control.Monad.IO.Class import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.Set as Set @@ -52,7 +51,7 @@ import Distribution.Utils.Path import Distribution.Verbosity import Distribution.Version -import System.Directory +import Distribution.Compat.Directory ( createDirectoryIfMissing , doesDirectoryExist , renameFile diff --git a/Cabal/src/Distribution/Simple/GHC/Build/Modules.hs b/Cabal/src/Distribution/Simple/GHC/Build/Modules.hs index 3113dbc7f9a..d7d96560802 100644 --- a/Cabal/src/Distribution/Simple/GHC/Build/Modules.hs +++ b/Cabal/src/Distribution/Simple/GHC/Build/Modules.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} module Distribution.Simple.GHC.Build.Modules @@ -10,6 +9,7 @@ module Distribution.Simple.GHC.Build.Modules import Control.Monad.IO.Class import Distribution.Compat.Prelude +import Prelude () import Data.List (sortOn, (\\)) import qualified Data.Set as Set @@ -107,7 +107,7 @@ buildHaskellModules -- ^ Optional path to a Haskell Main file to build -> [ModuleName] -- ^ The Haskell modules to build - -> SymbolicPath Pkg ('Dir Artifacts) + -> SymbolicPath Pkg (Dir Artifacts) -- ^ The path to the build directory for this target, which -- has already been created. -> [BuildWay] diff --git a/Cabal/src/Distribution/Simple/GHC/Build/Utils.hs b/Cabal/src/Distribution/Simple/GHC/Build/Utils.hs index 7fbb97ec64f..21876f584a4 100644 --- a/Cabal/src/Distribution/Simple/GHC/Build/Utils.hs +++ b/Cabal/src/Distribution/Simple/GHC/Build/Utils.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - module Distribution.Simple.GHC.Build.Utils where import Distribution.Compat.Prelude diff --git a/Cabal/src/Distribution/Simple/GHC/EnvironmentParser.hs b/Cabal/src/Distribution/Simple/GHC/EnvironmentParser.hs index fee034827ce..41f21b968a6 100644 --- a/Cabal/src/Distribution/Simple/GHC/EnvironmentParser.hs +++ b/Cabal/src/Distribution/Simple/GHC/EnvironmentParser.hs @@ -30,7 +30,7 @@ parseEnvironmentFileLine = P.try $ P.string "package-id" *> P.spaces - *> (mkUnitId <$> P.many1 (P.satisfy $ \c -> isAlphaNum c || c `elem` "-_.+")) + *> (mkUnitId <$> P.many1 (P.satisfy $ \c -> isAlphaNum c || c `elem` ("-_.+" :: String))) packageDb = (P.string "global-package-db" $> GlobalPackageDB) <|> (P.string "user-package-db" $> UserPackageDB) diff --git a/Cabal/src/Distribution/Simple/GHC/Internal.hs b/Cabal/src/Distribution/Simple/GHC/Internal.hs index a018b8da9c1..fce34799b26 100644 --- a/Cabal/src/Distribution/Simple/GHC/Internal.hs +++ b/Cabal/src/Distribution/Simple/GHC/Internal.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.GHC.Internal -- Copyright : Isaac Jones 2003-2007 @@ -86,7 +84,7 @@ import Distribution.Utils.NubList (NubListR, toNubListR) import Distribution.Utils.Path import Distribution.Verbosity import Language.Haskell.Extension -import System.Directory (listDirectory) +import Distribution.Compat.Directory (listDirectory) import System.Environment (getEnv) import System.FilePath ( takeDirectory diff --git a/Cabal/src/Distribution/Simple/Glob.hs b/Cabal/src/Distribution/Simple/Glob.hs index fedfffa800e..b58ea384150 100644 --- a/Cabal/src/Distribution/Simple/Glob.hs +++ b/Cabal/src/Distribution/Simple/Glob.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} -- | @@ -60,9 +59,8 @@ import Distribution.Verbosity , silent ) -import Control.Monad (mapM) import Data.List (stripPrefix) -import System.Directory +import Distribution.Compat.Directory import System.FilePath hiding ((<.>), ()) ------------------------------------------------------------------------------- diff --git a/Cabal/src/Distribution/Simple/Haddock.hs b/Cabal/src/Distribution/Simple/Haddock.hs index 4446aac0faa..106aa53273e 100644 --- a/Cabal/src/Distribution/Simple/Haddock.hs +++ b/Cabal/src/Distribution/Simple/Haddock.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE LambdaCase #-} @@ -82,9 +82,11 @@ import Distribution.Verbosity import Distribution.Version import Data.Bool (bool) +#ifndef __MHS__ import Data.Either (lefts, rights) +#endif import qualified Data.Text as T -import System.Directory (doesDirectoryExist, doesFileExist) +import Distribution.Compat.Directory (doesDirectoryExist, doesFileExist) import System.FilePath (isAbsolute, joinPath, normalise, splitDirectories) import System.IO (hClose, hPutStrLn, hSetEncoding, utf8) @@ -259,7 +261,7 @@ haddock_setupHooks ++ " --benchmarks or --foreign-libraries flags." return [] where - verb = mkVerbosity verbHandles $ fromFlag $ haddockVerbosity haddockFlags + verb = mkVerbosity verbHandles $ fromFlag $ setupVerbosity $ haddockCommonFlags haddockFlags haddock_setupHooks preBuildHook verbHandles @@ -267,8 +269,8 @@ haddock_setupHooks lbi suffixes flags' = do - let verbosity = mkVerbosity verbHandles (fromFlag $ haddockVerbosity flags) - mbWorkDir = flagToMaybe $ haddockWorkingDir flags + let verbosity = mkVerbosity verbHandles (fromFlag $ setupVerbosity $ haddockCommonFlags flags) + mbWorkDir = flagToMaybe $ setupWorkingDir $ haddockCommonFlags flags comp = compiler lbi platform = hostPlatform lbi config = configFlags lbi @@ -331,7 +333,7 @@ haddock_setupHooks suffixes (defaultHscolourFlags <> haddockToHscolour flags) - targets <- readTargetInfos verbosity pkg_descr lbi (haddockTargets flags) + targets <- readTargetInfos verbosity pkg_descr lbi (setupTargets $ haddockCommonFlags flags) let targets' = diff --git a/Cabal/src/Distribution/Simple/Hpc.hs b/Cabal/src/Distribution/Simple/Hpc.hs index c46b0f1fb0e..aed43aeb01e 100644 --- a/Cabal/src/Distribution/Simple/Hpc.hs +++ b/Cabal/src/Distribution/Simple/Hpc.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.Hpc -- Copyright : Thomas Tuegel 2011 @@ -48,7 +46,7 @@ import Distribution.Utils.Path import Distribution.Verbosity (Verbosity ()) import Distribution.Version (anyVersion) -import System.Directory (createDirectoryIfMissing, doesFileExist) +import Distribution.Compat.Directory (createDirectoryIfMissing, doesFileExist) -- ------------------------------------------------------------------------- -- Haskell Program Coverage diff --git a/Cabal/src/Distribution/Simple/Install.hs b/Cabal/src/Distribution/Simple/Install.hs index ffcaad97556..81ab8ba2f8e 100644 --- a/Cabal/src/Distribution/Simple/Install.hs +++ b/Cabal/src/Distribution/Simple/Install.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} -- | @@ -71,7 +70,7 @@ import qualified Distribution.Simple.GHC as GHC import Distribution.Simple.Setup.Common import qualified Distribution.Simple.UHC as UHC -import System.Directory +import Distribution.Compat.Directory ( doesDirectoryExist , doesFileExist ) @@ -117,7 +116,7 @@ install_setupHooks lbi flags = do checkHasLibsOrExes - targets <- readTargetInfos verbosity pkg_descr lbi (copyTargets flags) + targets <- readTargetInfos verbosity pkg_descr lbi (setupTargets $ copyCommonFlags flags) copyPackage verbosity pkg_descr lbi distPref copydest diff --git a/Cabal/src/Distribution/Simple/InstallDirs.hs b/Cabal/src/Distribution/Simple/InstallDirs.hs index 1e929db9f0c..9a066edd43a 100644 --- a/Cabal/src/Distribution/Simple/InstallDirs.hs +++ b/Cabal/src/Distribution/Simple/InstallDirs.hs @@ -61,7 +61,7 @@ import Distribution.Simple.Flag import Distribution.Simple.InstallDirs.Internal import Distribution.System -import System.Directory (getAppUserDataDirectory) +import Distribution.Compat.Directory (getAppUserDataDirectory) import System.FilePath ( dropDrive , isPathSeparator @@ -105,7 +105,36 @@ data InstallDirs dir = InstallDirs , sysconfdir :: dir } deriving (Eq, Read, Show, Functor, Generic) +#ifndef __MHS__ deriving (Semigroup, Monoid) via Generically (InstallDirs dir) +#endif + +#ifdef __MHS__ +instance Semigroup dir => Semigroup (InstallDirs dir) where + (<>) = combineInstallDirs (<>) + +instance Monoid dir => Monoid (InstallDirs dir) where + mempty = + InstallDirs + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mempty + mappend = (<>) +#endif instance Binary dir => Binary (InstallDirs dir) instance NFData dir => NFData (InstallDirs dir) @@ -561,25 +590,25 @@ foreign import capi unsafe "shlobj.h SHGetFolderPathW" -- FieldGrammar installDirsGrammar :: ParsecFieldGrammar' (InstallDirs (Flag PathTemplate)) -installDirsGrammar = do - prefix <- optionalFieldDef "prefix" installDirsPrefixLens mempty - bindir <- optionalFieldDef "bindir" installDirsBindirLens mempty - libdir <- optionalFieldDef "libdir" installDirsLibdirLens mempty - libsubdir <- optionalFieldDef "libsubdir" installDirsLibsubdirLens mempty - dynlibdir <- optionalFieldDef "dynlibdir" installDirsDynlibdirLens mempty - bytecodelibdir <- optionalFieldDef "bytecodelibdir" installDirsBytecodelibdirLens mempty - let flibdir = NoFlag - libexecdir <- optionalFieldDef "libexecdir" installDirsLibexecdirLens mempty - libexecsubdir <- optionalFieldDef "libexecsubdir" installDirsLibexecsubdirLens mempty - let includedir = NoFlag - datadir <- optionalFieldDef "datadir" installDirsDatadirLens mempty - datasubdir <- optionalFieldDef "datasubdir" installDirsDatasubdirLens mempty - docdir <- optionalFieldDef "docdir" installDirsDocdirLens mempty - let mandir = NoFlag - htmldir <- optionalFieldDef "htmldir" installDirsHtmldirLens mempty - haddockdir <- optionalFieldDef "haddockdir" installDirsHaddockdirLens mempty - sysconfdir <- optionalFieldDef "sysconfdir" installDirsSysconfdirLens mempty - pure InstallDirs{..} +installDirsGrammar = + mkInstallDirs + <$> optionalFieldDef "prefix" installDirsPrefixLens mempty + <*> optionalFieldDef "bindir" installDirsBindirLens mempty + <*> optionalFieldDef "libdir" installDirsLibdirLens mempty + <*> optionalFieldDef "libsubdir" installDirsLibsubdirLens mempty + <*> optionalFieldDef "dynlibdir" installDirsDynlibdirLens mempty + <*> optionalFieldDef "bytecodelibdir" installDirsBytecodelibdirLens mempty + <*> optionalFieldDef "libexecdir" installDirsLibexecdirLens mempty + <*> optionalFieldDef "libexecsubdir" installDirsLibexecsubdirLens mempty + <*> optionalFieldDef "datadir" installDirsDatadirLens mempty + <*> optionalFieldDef "datasubdir" installDirsDatasubdirLens mempty + <*> optionalFieldDef "docdir" installDirsDocdirLens mempty + <*> optionalFieldDef "htmldir" installDirsHtmldirLens mempty + <*> optionalFieldDef "haddockdir" installDirsHaddockdirLens mempty + <*> optionalFieldDef "sysconfdir" installDirsSysconfdirLens mempty + where + mkInstallDirs prefix bindir libdir libsubdir dynlibdir bytecodelibdir libexecdir libexecsubdir datadir datasubdir docdir htmldir haddockdir sysconfdir = + InstallDirs{flibdir = NoFlag, includedir = NoFlag, mandir = NoFlag, ..} -- --------------------------------------------------------------------------- -- Lenses diff --git a/Cabal/src/Distribution/Simple/LocalBuildInfo.hs b/Cabal/src/Distribution/Simple/LocalBuildInfo.hs index 923e279f5ec..76c9636b73e 100644 --- a/Cabal/src/Distribution/Simple/LocalBuildInfo.hs +++ b/Cabal/src/Distribution/Simple/LocalBuildInfo.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} -- | @@ -104,7 +103,7 @@ import Distribution.Simple.Utils import Distribution.Utils.Path import Data.List (stripPrefix) -import qualified System.Directory as Directory +import qualified Distribution.Compat.Directory as Directory ( canonicalizePath , doesDirectoryExist ) diff --git a/Cabal/src/Distribution/Simple/PackageDescription.hs b/Cabal/src/Distribution/Simple/PackageDescription.hs index 3ca2756d0cd..532b333a9d1 100644 --- a/Cabal/src/Distribution/Simple/PackageDescription.hs +++ b/Cabal/src/Distribution/Simple/PackageDescription.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - ----------------------------------------------------------------------------- -- | @@ -45,7 +43,7 @@ import Distribution.Simple.Errors import Distribution.Simple.Utils (dieWithException, equating, warn) import Distribution.Utils.Path import Distribution.Verbosity (Verbosity, VerbosityLevel (..), verbosityLevel) -import System.Directory (doesFileExist) +import Distribution.Compat.Directory (doesFileExist) import Text.Printf (printf) readGenericPackageDescription diff --git a/Cabal/src/Distribution/Simple/PreProcess.hs b/Cabal/src/Distribution/Simple/PreProcess.hs index 431b3544e10..c8306d9b2e7 100644 --- a/Cabal/src/Distribution/Simple/PreProcess.hs +++ b/Cabal/src/Distribution/Simple/PreProcess.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.PreProcess -- Copyright : (c) 2003-2005, Isaac Jones, Malcolm Wallace @@ -69,7 +67,7 @@ import Distribution.Verbosity import Distribution.Version import qualified Data.Text as T -import System.Directory (doesDirectoryExist, doesFileExist) +import Distribution.Compat.Directory (doesDirectoryExist, doesFileExist) import System.FilePath ( normalise , replaceExtension @@ -684,7 +682,7 @@ ppC2hs bi lbi clbi = -- -- -- DO NOT add Installed.cxxOptions unless this changes! - c `elem` "DIU" + c `elem` ("DIU" :: String) ] ] -- TODO: install .chi files for packages, so we can --include @@ -720,7 +718,7 @@ getCppOptions bi lbi = platformDefines lbi ++ map T.unpack (cppOptions bi) ++ ["-I" ++ getSymbolicPath dir | dir <- PD.includeDirs bi] - ++ [opt | opt@('-' : c : _) <- map T.unpack (PD.ccOptions bi ++ PD.cxxOptions bi), c `elem` "DIU"] + ++ [opt | opt@('-' : c : _) <- map T.unpack (PD.ccOptions bi ++ PD.cxxOptions bi), c `elem` ("DIU" :: String)] platformDefines :: LocalBuildInfo -> [String] platformDefines lbi = diff --git a/Cabal/src/Distribution/Simple/PreProcess/Types.hs b/Cabal/src/Distribution/Simple/PreProcess/Types.hs index e5a2a64260c..2edc8f2dbd8 100644 --- a/Cabal/src/Distribution/Simple/PreProcess/Types.hs +++ b/Cabal/src/Distribution/Simple/PreProcess/Types.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.PreProcess.Types -- Copyright : (c) 2003-2005, Isaac Jones, Malcolm Wallace diff --git a/Cabal/src/Distribution/Simple/Program.hs b/Cabal/src/Distribution/Simple/Program.hs index 87e2e97827a..4fe2d4eb79c 100644 --- a/Cabal/src/Distribution/Simple/Program.hs +++ b/Cabal/src/Distribution/Simple/Program.hs @@ -5,8 +5,6 @@ - Ideally, a set of unit tests that check whether certain - flags trigger recompilation should be added. - -} -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.Program -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 diff --git a/Cabal/src/Distribution/Simple/Program/Ar.hs b/Cabal/src/Distribution/Simple/Program/Ar.hs index 9c2744a8f60..231edf339b6 100644 --- a/Cabal/src/Distribution/Simple/Program/Ar.hs +++ b/Cabal/src/Distribution/Simple/Program/Ar.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE NondecreasingIndentation #-} {-# LANGUAGE OverloadedStrings #-} @@ -59,16 +59,34 @@ import Distribution.Verbosity , verbosityLevel ) -import System.Directory (doesFileExist, renameFile) +import Distribution.Compat.Directory (doesFileExist, renameFile) import System.FilePath (splitFileName) import System.IO ( Handle , IOMode (ReadWriteMode) , SeekMode (AbsoluteSeek) , hFileSize +#ifndef __MHS__ , hSeek +#endif , withBinaryFile ) +#ifdef __MHS__ +import Data.Int (Int64) +import Foreign.C.Error (throwErrnoIfMinus1_) +import Foreign.C.Types (CInt (..)) +import Foreign.Ptr (Ptr) +import System.IO.Internal (BFILE, withHandleAny) + +foreign import ccall "mhs_handle.h mhs_handle_seek" + c_handleSeek :: Ptr BFILE -> CInt -> Int64 -> IO CInt + +hSeek :: Handle -> SeekMode -> Integer -> IO () +hSeek h mode off = + withHandleAny h $ \p -> + throwErrnoIfMinus1_ "hSeek" $ + c_handleSeek p (fromIntegral (fromEnum mode)) (fromIntegral off) +#endif -- | Call @ar@ to create a library archive from a bunch of object files. createArLibArchive diff --git a/Cabal/src/Distribution/Simple/Program/Db.hs b/Cabal/src/Distribution/Simple/Program/Db.hs index 4143e32c66a..8d238e79bc0 100644 --- a/Cabal/src/Distribution/Simple/Program/Db.hs +++ b/Cabal/src/Distribution/Simple/Program/Db.hs @@ -75,7 +75,7 @@ import Distribution.Simple.Program.Builtin import Distribution.Simple.Program.Find import Distribution.Simple.Program.Types import Distribution.Simple.Utils -import Distribution.Utils.Structured (Structure (..), Structured (..)) +import Distribution.Utils.Structured (Structure (..)) import Distribution.Verbosity import Distribution.Version diff --git a/Cabal/src/Distribution/Simple/Program/Find.hs b/Cabal/src/Distribution/Simple/Program/Find.hs index 2560f4f81cc..a318dec2cb2 100644 --- a/Cabal/src/Distribution/Simple/Program/Find.hs +++ b/Cabal/src/Distribution/Simple/Program/Find.hs @@ -42,7 +42,7 @@ import Distribution.Simple.Utils import Distribution.System import Distribution.Verbosity -import System.Directory +import Distribution.Compat.Directory ( findExecutable ) import System.FilePath as FilePath diff --git a/Cabal/src/Distribution/Simple/Program/GHC.hs b/Cabal/src/Distribution/Simple/Program/GHC.hs index 26cb7619796..4bee995589a 100644 --- a/Cabal/src/Distribution/Simple/Program/GHC.hs +++ b/Cabal/src/Distribution/Simple/Program/GHC.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} @@ -48,7 +47,7 @@ import Distribution.Utils.Path import Distribution.Verbosity import Distribution.Version -import GHC.IO.Encoding (TextEncoding) +import System.IO (TextEncoding) import Language.Haskell.Extension import Data.List (stripPrefix) @@ -57,7 +56,7 @@ import Data.Monoid (All (..), Any (..), Endo (..)) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text -import qualified System.Process as Process +import qualified Distribution.Compat.Process as Process normaliseGhcArgs :: Maybe Version -> PackageDescription -> [String] -> [String] normaliseGhcArgs (Just ghcVersion) PackageDescription{..} ghcArgs diff --git a/Cabal/src/Distribution/Simple/Program/HcPkg.hs b/Cabal/src/Distribution/Simple/Program/HcPkg.hs index 0f4234bd883..9dc3e23db25 100644 --- a/Cabal/src/Distribution/Simple/Program/HcPkg.hs +++ b/Cabal/src/Distribution/Simple/Program/HcPkg.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} -- | @@ -72,7 +71,7 @@ import Distribution.Types.UnitId (mkLegacyUnitId, unUnitId) import Distribution.Utils.Path ( CWD , FileLike ((<.>)) - , FileOrDir (Dir) + , Dir , PathLike (()) , Pkg , PkgDB diff --git a/Cabal/src/Distribution/Simple/Program/Hpc.hs b/Cabal/src/Distribution/Simple/Program/Hpc.hs index 8704cffa996..0154bcb8af4 100644 --- a/Cabal/src/Distribution/Simple/Program/Hpc.hs +++ b/Cabal/src/Distribution/Simple/Program/Hpc.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.Program.Hpc -- Copyright : Thomas Tuegel 2011 diff --git a/Cabal/src/Distribution/Simple/Program/Ld.hs b/Cabal/src/Distribution/Simple/Program/Ld.hs index f7c07ac0b64..9b90fce1f4b 100644 --- a/Cabal/src/Distribution/Simple/Program/Ld.hs +++ b/Cabal/src/Distribution/Simple/Program/Ld.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.Program.Ld -- Copyright : Duncan Coutts 2009 @@ -43,7 +41,7 @@ import Distribution.Verbosity ( Verbosity ) -import System.Directory +import Distribution.Compat.Directory ( renameFile ) diff --git a/Cabal/src/Distribution/Simple/Program/ResponseFile.hs b/Cabal/src/Distribution/Simple/Program/ResponseFile.hs index 7a963b3d1c6..ba2aee73ec6 100644 --- a/Cabal/src/Distribution/Simple/Program/ResponseFile.hs +++ b/Cabal/src/Distribution/Simple/Program/ResponseFile.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.Program.ResponseFile -- Copyright : (c) Sergey Vinokurov 2017 diff --git a/Cabal/src/Distribution/Simple/Program/Run.hs b/Cabal/src/Distribution/Simple/Program/Run.hs index 79579764171..dcf451aaf31 100644 --- a/Cabal/src/Distribution/Simple/Program/Run.hs +++ b/Cabal/src/Distribution/Simple/Program/Run.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} -- | diff --git a/Cabal/src/Distribution/Simple/Register.hs b/Cabal/src/Distribution/Simple/Register.hs index 746643f05ea..3661d062124 100644 --- a/Cabal/src/Distribution/Simple/Register.hs +++ b/Cabal/src/Distribution/Simple/Register.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Simple.Register -- Copyright : Isaac Jones 2003-2004 @@ -81,7 +79,7 @@ import Distribution.System import Distribution.Utils.Path import Distribution.Verbosity as Verbosity import Distribution.Version -import System.Directory +import Distribution.Compat.Directory import System.FilePath (isAbsolute) import System.IO (hPutStrLn) @@ -112,8 +110,8 @@ registerWithHandles verbHandles pkg_descr lbi0 flags = do -- when there was no public library. But with per-component -- configure, we legitimately need to install internal libraries -- so that we can get them. So just unconditionally install. - let verbosity = mkVerbosity verbHandles (fromFlag $ registerVerbosity flags) - targets <- readTargetInfos verbosity pkg_descr lbi0 $ registerTargets flags + let verbosity = mkVerbosity verbHandles (fromFlag $ setupVerbosity $ registerCommonFlags flags) + targets <- readTargetInfos verbosity pkg_descr lbi0 $ setupTargets $ registerCommonFlags flags -- It's important to register in build order, because ghc-pkg -- will complain if a dependency is not registered. @@ -693,7 +691,7 @@ relocatableInstalledPackageInfo -> Library -> LocalBuildInfo -> ComponentLocalBuildInfo - -> SymbolicPath CWD ('Dir Pkg) + -> SymbolicPath CWD (Dir Pkg) -> InstalledPackageInfo relocatableInstalledPackageInfo pkg abi_hash lib lbi clbi pkgroot = generalInstalledPackageInfo diff --git a/Cabal/src/Distribution/Simple/Setup.hs b/Cabal/src/Distribution/Simple/Setup.hs index b7d1ee5b4fc..aa05a056014 100644 --- a/Cabal/src/Distribution/Simple/Setup.hs +++ b/Cabal/src/Distribution/Simple/Setup.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} diff --git a/Cabal/src/Distribution/Simple/Setup/Benchmark.hs b/Cabal/src/Distribution/Simple/Setup/Benchmark.hs index 30b6477fdaf..8237b11bb81 100644 --- a/Cabal/src/Distribution/Simple/Setup/Benchmark.hs +++ b/Cabal/src/Distribution/Simple/Setup/Benchmark.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -15,6 +15,9 @@ -- Definition of the benchmarking command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Benchmark +#ifdef __MHS__ + ( BenchmarkFlags (..) +#else ( BenchmarkFlags ( BenchmarkCommonFlags , benchmarkVerbosity @@ -24,6 +27,7 @@ module Distribution.Simple.Setup.Benchmark , benchmarkTargets , .. ) +#endif , emptyBenchmarkFlags , defaultBenchmarkFlags , benchmarkCommand @@ -53,6 +57,7 @@ data BenchmarkFlags = BenchmarkFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically BenchmarkFlags +#ifndef __MHS__ pattern BenchmarkCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -76,6 +81,7 @@ pattern BenchmarkCommonFlags , setupTargets = benchmarkTargets } ) +#endif instance Binary BenchmarkFlags instance Structured BenchmarkFlags diff --git a/Cabal/src/Distribution/Simple/Setup/Build.hs b/Cabal/src/Distribution/Simple/Setup/Build.hs index 658f2060c70..5cc5a58ec15 100644 --- a/Cabal/src/Distribution/Simple/Setup/Build.hs +++ b/Cabal/src/Distribution/Simple/Setup/Build.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -15,6 +15,9 @@ -- Definition of the build command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Build +#ifdef __MHS__ + ( BuildFlags (..) +#else ( BuildFlags ( BuildCommonFlags , buildVerbosity @@ -24,6 +27,7 @@ module Distribution.Simple.Setup.Build , buildTargets , .. ) +#endif , emptyBuildFlags , defaultBuildFlags , buildCommand @@ -59,6 +63,7 @@ data BuildFlags = BuildFlags deriving (Read, Show, Generic) deriving (Semigroup, Monoid) via Generically BuildFlags +#ifndef __MHS__ pattern BuildCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -82,6 +87,7 @@ pattern BuildCommonFlags , setupTargets = buildTargets } ) +#endif instance Binary BuildFlags instance Structured BuildFlags diff --git a/Cabal/src/Distribution/Simple/Setup/Clean.hs b/Cabal/src/Distribution/Simple/Setup/Clean.hs index 6801cc4d6ad..d93933c38a7 100644 --- a/Cabal/src/Distribution/Simple/Setup/Clean.hs +++ b/Cabal/src/Distribution/Simple/Setup/Clean.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -15,6 +15,9 @@ -- Definition of the clean command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Clean +#ifdef __MHS__ + ( CleanFlags (..) +#else ( CleanFlags ( CleanCommonFlags , cleanVerbosity @@ -24,6 +27,7 @@ module Distribution.Simple.Setup.Clean , cleanTargets , .. ) +#endif , emptyCleanFlags , defaultCleanFlags , cleanCommand @@ -51,6 +55,7 @@ data CleanFlags = CleanFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically CleanFlags +#ifndef __MHS__ pattern CleanCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -74,6 +79,7 @@ pattern CleanCommonFlags , setupTargets = cleanTargets } ) +#endif instance Binary CleanFlags instance Structured CleanFlags diff --git a/Cabal/src/Distribution/Simple/Setup/Common.hs b/Cabal/src/Distribution/Simple/Setup/Common.hs index 4fd043da1e3..67bd41ceba5 100644 --- a/Cabal/src/Distribution/Simple/Setup/Common.hs +++ b/Cabal/src/Distribution/Simple/Setup/Common.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} diff --git a/Cabal/src/Distribution/Simple/Setup/Config.hs b/Cabal/src/Distribution/Simple/Setup/Config.hs index aa8222e5ce9..2b9967aaad0 100644 --- a/Cabal/src/Distribution/Simple/Setup/Config.hs +++ b/Cabal/src/Distribution/Simple/Setup/Config.hs @@ -1,5 +1,4 @@ {-# LANGUAGE CPP #-} -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} @@ -17,6 +16,9 @@ -- Definition of the configure command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Config +#ifdef __MHS__ + ( ConfigFlags (..) +#else ( ConfigFlags ( ConfigCommonFlags , configVerbosity @@ -26,6 +28,7 @@ module Distribution.Simple.Setup.Config , configTargets , .. ) +#endif , emptyConfigFlags , defaultConfigFlags , configureCommand @@ -236,6 +239,7 @@ data ConfigFlags = ConfigFlags deriving (Generic, Read, Show) deriving (Semigroup, Monoid) via Generically ConfigFlags +#ifndef __MHS__ pattern ConfigCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -259,6 +263,7 @@ pattern ConfigCommonFlags , setupTargets = configTargets } ) +#endif instance Binary ConfigFlags instance Structured ConfigFlags diff --git a/Cabal/src/Distribution/Simple/Setup/Copy.hs b/Cabal/src/Distribution/Simple/Setup/Copy.hs index a25e195641c..68169208fea 100644 --- a/Cabal/src/Distribution/Simple/Setup/Copy.hs +++ b/Cabal/src/Distribution/Simple/Setup/Copy.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} @@ -16,6 +16,9 @@ -- Definition of the copy command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Copy +#ifdef __MHS__ + ( CopyFlags (..) +#else ( CopyFlags ( CopyCommonFlags , copyVerbosity @@ -25,6 +28,7 @@ module Distribution.Simple.Setup.Copy , copyTargets , .. ) +#endif , emptyCopyFlags , defaultCopyFlags , copyCommand @@ -56,6 +60,7 @@ data CopyFlags = CopyFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically CopyFlags +#ifndef __MHS__ pattern CopyCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -79,6 +84,7 @@ pattern CopyCommonFlags , setupTargets = copyTargets } ) +#endif instance Binary CopyFlags instance Structured CopyFlags diff --git a/Cabal/src/Distribution/Simple/Setup/Global.hs b/Cabal/src/Distribution/Simple/Setup/Global.hs index 06964f88430..ae43b6a0dac 100644 --- a/Cabal/src/Distribution/Simple/Setup/Global.hs +++ b/Cabal/src/Distribution/Simple/Setup/Global.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingVia #-} -- | diff --git a/Cabal/src/Distribution/Simple/Setup/Haddock.hs b/Cabal/src/Distribution/Simple/Setup/Haddock.hs index 93cf866702e..df992dcdad3 100644 --- a/Cabal/src/Distribution/Simple/Setup/Haddock.hs +++ b/Cabal/src/Distribution/Simple/Setup/Haddock.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -16,6 +16,9 @@ -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Haddock ( HaddockTarget (..) +#ifdef __MHS__ + , HaddockFlags (..) +#else , HaddockFlags ( HaddockCommonFlags , haddockVerbosity @@ -25,6 +28,7 @@ module Distribution.Simple.Setup.Haddock , haddockTargets , .. ) +#endif , emptyHaddockFlags , defaultHaddockFlags , haddockCommand @@ -114,6 +118,7 @@ data HaddockFlags = HaddockFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically HaddockFlags +#ifndef __MHS__ pattern HaddockCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -137,6 +142,7 @@ pattern HaddockCommonFlags , setupTargets = haddockTargets } ) +#endif instance Binary HaddockFlags instance Structured HaddockFlags diff --git a/Cabal/src/Distribution/Simple/Setup/Hscolour.hs b/Cabal/src/Distribution/Simple/Setup/Hscolour.hs index 4aeae882241..8c889628929 100644 --- a/Cabal/src/Distribution/Simple/Setup/Hscolour.hs +++ b/Cabal/src/Distribution/Simple/Setup/Hscolour.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -15,6 +15,9 @@ -- Definition of the hscolour command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Hscolour +#ifdef __MHS__ + ( HscolourFlags (..) +#else ( HscolourFlags ( HscolourCommonFlags , hscolourVerbosity @@ -24,6 +27,7 @@ module Distribution.Simple.Setup.Hscolour , hscolourTargets , .. ) +#endif , emptyHscolourFlags , defaultHscolourFlags , hscolourCommand @@ -55,6 +59,7 @@ data HscolourFlags = HscolourFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically HscolourFlags +#ifndef __MHS__ pattern HscolourCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -78,6 +83,7 @@ pattern HscolourCommonFlags , setupTargets = hscolourTargets } ) +#endif instance Binary HscolourFlags instance Structured HscolourFlags diff --git a/Cabal/src/Distribution/Simple/Setup/Install.hs b/Cabal/src/Distribution/Simple/Setup/Install.hs index ff02008fc95..3533d4008b6 100644 --- a/Cabal/src/Distribution/Simple/Setup/Install.hs +++ b/Cabal/src/Distribution/Simple/Setup/Install.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} @@ -16,6 +16,9 @@ -- Definition of the install command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Install +#ifdef __MHS__ + ( InstallFlags (..) +#else ( InstallFlags ( InstallCommonFlags , installVerbosity @@ -25,6 +28,7 @@ module Distribution.Simple.Setup.Install , installTargets , .. ) +#endif , emptyInstallFlags , defaultInstallFlags , installCommand @@ -60,6 +64,7 @@ data InstallFlags = InstallFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically InstallFlags +#ifndef __MHS__ pattern InstallCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -83,6 +88,7 @@ pattern InstallCommonFlags , setupTargets = installTargets } ) +#endif defaultInstallFlags :: InstallFlags defaultInstallFlags = diff --git a/Cabal/src/Distribution/Simple/Setup/Register.hs b/Cabal/src/Distribution/Simple/Setup/Register.hs index ba6886bc1ed..a90d3b23054 100644 --- a/Cabal/src/Distribution/Simple/Setup/Register.hs +++ b/Cabal/src/Distribution/Simple/Setup/Register.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -15,6 +15,9 @@ -- Definition of the register command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Register +#ifdef __MHS__ + ( RegisterFlags (..) +#else ( RegisterFlags ( RegisterCommonFlags , registerVerbosity @@ -24,6 +27,7 @@ module Distribution.Simple.Setup.Register , registerTargets , .. ) +#endif , emptyRegisterFlags , defaultRegisterFlags , registerCommand @@ -59,6 +63,7 @@ data RegisterFlags = RegisterFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically RegisterFlags +#ifndef __MHS__ pattern RegisterCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -82,6 +87,7 @@ pattern RegisterCommonFlags , setupTargets = registerTargets } ) +#endif defaultRegisterFlags :: RegisterFlags defaultRegisterFlags = diff --git a/Cabal/src/Distribution/Simple/Setup/Repl.hs b/Cabal/src/Distribution/Simple/Setup/Repl.hs index ca6b61811c0..a30dbd26af2 100644 --- a/Cabal/src/Distribution/Simple/Setup/Repl.hs +++ b/Cabal/src/Distribution/Simple/Setup/Repl.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -15,6 +15,9 @@ -- Definition of the repl command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Repl +#ifdef __MHS__ + ( ReplFlags (..) +#else ( ReplFlags ( ReplCommonFlags , replVerbosity @@ -24,6 +27,7 @@ module Distribution.Simple.Setup.Repl , replTargets , .. ) +#endif , defaultReplFlags , replCommand , ReplOptions (..) @@ -57,6 +61,7 @@ data ReplOptions = ReplOptions deriving (Show, Generic) deriving (Semigroup) via Generically ReplOptions +#ifndef __MHS__ pattern ReplCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -80,6 +85,7 @@ pattern ReplCommonFlags , setupTargets = replTargets } ) +#endif instance Binary ReplOptions instance Structured ReplOptions diff --git a/Cabal/src/Distribution/Simple/Setup/SDist.hs b/Cabal/src/Distribution/Simple/Setup/SDist.hs index 7901953f89f..ec3c456a298 100644 --- a/Cabal/src/Distribution/Simple/Setup/SDist.hs +++ b/Cabal/src/Distribution/Simple/Setup/SDist.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -15,6 +15,9 @@ -- Definition of the sdist command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.SDist +#ifdef __MHS__ + ( SDistFlags (..) +#else ( SDistFlags ( SDistCommonFlags , sDistVerbosity @@ -24,6 +27,7 @@ module Distribution.Simple.Setup.SDist , sDistTargets , .. ) +#endif , emptySDistFlags , defaultSDistFlags , sdistCommand @@ -54,6 +58,7 @@ data SDistFlags = SDistFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically SDistFlags +#ifndef __MHS__ pattern SDistCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -77,6 +82,7 @@ pattern SDistCommonFlags , setupTargets = sDistTargets } ) +#endif defaultSDistFlags :: SDistFlags defaultSDistFlags = diff --git a/Cabal/src/Distribution/Simple/Setup/Test.hs b/Cabal/src/Distribution/Simple/Setup/Test.hs index 5a1563f2b70..eaa736e0017 100644 --- a/Cabal/src/Distribution/Simple/Setup/Test.hs +++ b/Cabal/src/Distribution/Simple/Setup/Test.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ViewPatterns #-} @@ -15,6 +15,9 @@ -- Definition of the testing command-line options. -- See: @Distribution.Simple.Setup@ module Distribution.Simple.Setup.Test +#ifdef __MHS__ + ( TestFlags (..) +#else ( TestFlags ( TestCommonFlags , testVerbosity @@ -24,6 +27,7 @@ module Distribution.Simple.Setup.Test , testTargets , .. ) +#endif , emptyTestFlags , defaultTestFlags , testCommand @@ -99,6 +103,7 @@ data TestFlags = TestFlags deriving (Show, Generic) deriving (Semigroup, Monoid) via Generically TestFlags +#ifndef __MHS__ pattern TestCommonFlags :: Flag VerbosityFlags -> Flag (SymbolicPath Pkg (Dir Dist)) @@ -122,6 +127,7 @@ pattern TestCommonFlags , setupTargets = testTargets } ) +#endif instance Binary TestFlags instance Structured TestFlags diff --git a/Cabal/src/Distribution/Simple/SetupHooks/Errors.hs b/Cabal/src/Distribution/Simple/SetupHooks/Errors.hs index 2e4e5736353..20e1a554a85 100644 --- a/Cabal/src/Distribution/Simple/SetupHooks/Errors.hs +++ b/Cabal/src/Distribution/Simple/SetupHooks/Errors.hs @@ -188,7 +188,7 @@ cannotApplyComponentDiffMessage = \case CTest{} -> "a testsuite" CBench{} -> "a benchmark" to = case componentName comp of - nm@(CExeName{}) -> "an " ++ showComponentName nm + nm@(CExeName _) -> "an " ++ showComponentName nm nm -> "a " ++ showComponentName nm IllegalComponentDiff comp reasons -> unlines $ diff --git a/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs b/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs index 76c0a872236..193fcfb8228 100644 --- a/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs +++ b/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE DuplicateRecordFields #-} @@ -33,7 +34,9 @@ import Control.Monad import Control.Monad.IO.Class ( liftIO ) -import GHC.Exception +import Control.Exception + ( Exception (..) + ) import System.Environment ( getArgs ) @@ -46,7 +49,6 @@ import System.IO -- bytestring import Data.ByteString.Lazy as LBS ( ByteString - , hGetContents , hPutStr , null ) @@ -54,11 +56,13 @@ import Data.ByteString.Lazy as LBS -- containers import qualified Data.Map as Map +#ifndef __MHS__ -- process import System.Process.CommunicationHandle ( openCommunicationHandleRead , openCommunicationHandleWrite ) +#endif -- transformers import Control.Monad.Trans.Except @@ -79,9 +83,17 @@ import Distribution.Utils.Structured ( MD5 , structureHash ) +#ifdef __MHS__ +import Distribution.Utils.MD5 (showMD5) + +instance Show MD5 where + show = showMD5 +#endif -- Cabal +import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS) import Distribution.Compat.Prelude +import Prelude () import Distribution.Simple.SetupHooks.Internal import Distribution.Simple.SetupHooks.Rule import Distribution.Simple.Utils @@ -128,8 +140,12 @@ hooksVersion :: HooksVersion hooksVersion = HooksVersion { hooksAPIVersion = cabalVersion - , cabalABIHash = structureHash $ Proxy @CabalABI - , hooksABIHash = structureHash $ Proxy @HooksABI + , cabalABIHash = structureHash (Proxy :: Proxy CabalABI) +#ifndef __MHS__ + , hooksABIHash = structureHash (Proxy :: Proxy HooksABI) +#else + , hooksABIHash = structureHash (Proxy :: Proxy CabalABI) +#endif } -- | Tracks the parts of the Cabal API relevant to its binary interface. @@ -156,7 +172,9 @@ data HooksABI = HooksABI } deriving stock (Generic) +#ifndef __MHS__ deriving anyclass instance Structured HooksABI +#endif -------------------------------------------------------------------------------- -- Error types (internal) @@ -199,11 +217,11 @@ setupHooksExeExceptionCode = \case setupHooksExeExceptionMessage :: SetupHooksExeException -> String setupHooksExeExceptionMessage = \case NoHookType -> - "Missing argument to Hooks executable.\n\ - \Expected two arguments: communication handle and hook type." + "Missing argument to Hooks executable.\n" + ++ "Expected two arguments: communication handle and hook type." NoHandle Nothing -> - "Missing argument to Hooks executable.\n\ - \Expected two arguments: communication handle and hook type." + "Missing argument to Hooks executable.\n" + ++ "Expected two arguments: communication handle and hook type." NoHandle (Just h) -> "Invalid handle reference passed to Hooks executable: '" ++ h ++ "'." BadHooksExeArgs hookName reason -> @@ -220,21 +238,21 @@ badHooksExeArgsMessage hookName = \case UnknownHookType knownHookNames -> "Unknown hook type " ++ hookName - ++ ".\n\ - \Known hook types are: " + ++ ".\n" + ++ "Known hook types are: " ++ show knownHookNames ++ "." CouldNotDecodeInput _bytes offset err -> "Failed to decode the input to the " ++ hookName - ++ " hook.\n\ - \Decoding failed at position " + ++ " hook.\n" + ++ "Decoding failed at position " ++ show offset ++ " with error: " ++ err - ++ ".\n\ - \This could be due to a mismatch between the Cabal version of cabal-install\ - \ and of the hooks executable." + ++ ".\n" + ++ "This could be due to a mismatch between the Cabal version of cabal-install" + ++ " and of the hooks executable." NoDynDepsCmd rId -> unlines [ "Unexpected rule " <> show rId <> " in the " <> hookName <> " hook." @@ -242,7 +260,6 @@ badHooksExeArgsMessage hookName = \case ] instance Exception (VerboseException SetupHooksExeException) where - displayException :: VerboseException SetupHooksExeException -> String displayException (VerboseException stack timestamp verb err) = withOutputMarker verb @@ -292,6 +309,10 @@ hooksMain setupHooks = runHooksM $ do -- Get the communication handles and the name of the hook to run getHooksMainArgs :: HooksM ((Handle, Handle), String) +#ifdef __MHS__ + getHooksMainArgs = + error "Distribution.Simple.SetupHooks.HooksMain: build-type 'Hooks' is not supported in this MHS build of Cabal." +#else getHooksMainArgs = liftIO getArgs >>= \case inputFdRef : outputFdRef : hookNm : _ -> @@ -305,6 +326,7 @@ hooksMain setupHooks = runHooksM $ do (_, Nothing) -> throwE $ NoHandle (Just $ "hook output communication handle '" ++ outputFdRef ++ "'") _ -> throwE $ NoHandle Nothing +#endif type HooksM = ExceptT SetupHooksExeException IO @@ -324,7 +346,7 @@ runHookHandle -- ^ The hook to run -> HooksM () runHookHandle (hRead, hWrite) hookName hook = do - inputsData <- liftIO $ LBS.hGetContents hRead + inputsData <- liftIO $ hGetContentsLBS hRead let mb_inputs = Binary.decodeOrFail inputsData case mb_inputs of Left (_, offset, err) -> diff --git a/Cabal/src/Distribution/Simple/SetupHooks/Internal.hs b/Cabal/src/Distribution/Simple/SetupHooks/Internal.hs index dd8b0d3c919..d2c4be599da 100644 --- a/Cabal/src/Distribution/Simple/SetupHooks/Internal.hs +++ b/Cabal/src/Distribution/Simple/SetupHooks/Internal.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE DuplicateRecordFields #-} @@ -121,7 +122,9 @@ import Distribution.Verbosity import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import Data.Coerce (coerce) +#ifndef __MHS__ import Data.Either (fromRight) +#endif import qualified Data.Graph as Graph import Data.IORef (IORef, modifyIORef', newIORef, readIORef) import qualified Data.List.NonEmpty as NE @@ -130,9 +133,15 @@ import Data.Monoid (Ap (..)) import qualified Data.Set as Set import qualified Data.Text as Text -import System.Directory (doesFileExist, getModificationTime) +import Distribution.Compat.Directory (doesFileExist, getModificationTime) import qualified System.FilePath as FilePath +#ifdef __MHS__ +fromRight :: b -> Either a b -> b +fromRight _ (Right x) = x +fromRight d (Left _) = d +#endif + -------------------------------------------------------------------------------- -- SetupHooks @@ -534,20 +543,20 @@ emptyComponentDiff :: ComponentName -> ComponentDiff emptyComponentDiff name = ComponentDiff $ case name of CLibName{} -> CLib emptyLibrary - CFLibName{} -> CFLib emptyForeignLib - CExeName{} -> CExe emptyExecutable - CTestName{} -> CTest emptyTestSuite - CBenchName{} -> CBench emptyBenchmark + CFLibName _ -> CFLib emptyForeignLib + CExeName _ -> CExe emptyExecutable + CTestName _ -> CTest emptyTestSuite + CBenchName _ -> CBench emptyBenchmark buildInfoComponentDiff :: ComponentName -> BuildInfo -> ComponentDiff buildInfoComponentDiff name bi = ComponentDiff $ BI.buildInfo .~ bi $ case name of CLibName{} -> CLib emptyLibrary - CFLibName{} -> CFLib emptyForeignLib - CExeName{} -> CExe emptyExecutable - CTestName{} -> CTest emptyTestSuite - CBenchName{} -> CBench emptyBenchmark + CFLibName _ -> CFLib emptyForeignLib + CExeName _ -> CExe emptyExecutable + CTestName _ -> CTest emptyTestSuite + CBenchName _ -> CBench emptyBenchmark applyLibraryDiff :: Verbosity -> Library -> LibraryDiff -> IO Library applyLibraryDiff verbosity lib diff = @@ -859,7 +868,9 @@ executeRules = executeRulesUserOrSystem :: forall userOrSystem . ( Binary (RuleData userOrSystem) +#ifndef __MHS__ , Structured (RuleData userOrSystem) +#endif , Eq (RuleData userOrSystem) ) => SScope userOrSystem @@ -870,6 +881,7 @@ executeRulesUserOrSystem -> TargetInfo -> Map RuleId (RuleData userOrSystem) -> IO () +#ifndef __MHS__ executeRulesUserOrSystem scope runDepsCmdData runCmdData verbosity lbi tgtInfo allRules = do -- Load the rule cache from the previous build. -- Used to detect when rule definitions have changed. @@ -1126,6 +1138,11 @@ pprNotDemandedRuleReasons case miss_files of [_] -> ("", "is", "It") _ -> ("s", "are", "They") +#else +-- MicroHs stub: Hooks execution is unsupported in the MHS build (no +-- DataKinds promotion: the scope index is erased). +executeRulesUserOrSystem _ _ _ _ _ _ _ = error "Distribution.Simple.SetupHooks.Internal: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif directRuleDependencyMaybe :: Rule.Dependency -> Maybe RuleId directRuleDependencyMaybe (RuleDependency dep) = Just $ outputOfRule dep @@ -1250,9 +1267,9 @@ hookedBuildInfoComponentDiff_maybe (mb_mainlib, exes) comp_nm = CExeName exe_nm -> let mb_exe = lookup exe_nm exes in return . ComponentDiff . CExe . buildInfoExecutableDiff <$> mb_exe - CFLibName{} -> Nothing - CTestName{} -> Nothing - CBenchName{} -> Nothing + CFLibName _ -> Nothing + CTestName _ -> Nothing + CBenchName _ -> Nothing buildInfoLibraryDiff :: BuildInfo -> LibraryDiff buildInfoLibraryDiff bi = emptyLibrary{libBuildInfo = bi} diff --git a/Cabal/src/Distribution/Simple/SetupHooks/Rule.hs b/Cabal/src/Distribution/Simple/SetupHooks/Rule.hs index 8c7ef7e836f..ab1cb8376fc 100644 --- a/Cabal/src/Distribution/Simple/SetupHooks/Rule.hs +++ b/Cabal/src/Distribution/Simple/SetupHooks/Rule.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} @@ -83,7 +84,8 @@ import Distribution.ModuleName import Distribution.Simple.FileMonitor.Types import Distribution.Types.UnitId import Distribution.Utils.Path - ( FileOrDir (..) + ( Dir + , File , Pkg , RelativePath , SymbolicPath @@ -95,7 +97,6 @@ import Distribution.Utils.ShortText ) import Distribution.Utils.Structured ( Structure (..) - , Structured (..) , nominalStructure ) import Distribution.Verbosity @@ -119,6 +120,7 @@ import qualified Data.Map.Strict as Map ) import qualified Data.Kind as Hs +#ifndef __MHS__ import Data.Type.Bool ( If ) @@ -145,6 +147,7 @@ import qualified Type.Reflection as Typeable , withTypeable , pattern App ) +#endif import System.FilePath ( normalise @@ -197,6 +200,7 @@ data RulesNameSpace = RulesNameSpace deriving anyclass (Binary, Structured) -- | Internal function: create a 'RulesNameSpace' from a 'StaticPtrInfo'. +#ifndef __MHS__ staticPtrNameSpace :: StaticPtrInfo -> RulesNameSpace staticPtrNameSpace StaticPtrInfo @@ -209,6 +213,11 @@ staticPtrNameSpace , rulesModuleName = fromString modName , rulesSrcLoc = srcLoc } +#else +staticPtrNameSpace :: StaticPtrInfo -> RulesNameSpace +staticPtrNameSpace _ = + error "staticPtrNameSpace: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif -- | 'Rule's are defined with rich types by the package. -- @@ -222,12 +231,27 @@ data Scope | -- | Build-system space (manipulation of raw data). System +#ifndef __MHS__ data SScope (scope :: Scope) where SUser :: SScope User SSystem :: SScope System +#else +-- MicroHs has no DataKinds promotion: the scope index is erased. +data SScope scope = SUser | SSystem + deriving stock (Show, Eq) +#endif +#ifndef __MHS__ type Rule = RuleData User type RuleBinary = RuleData System +#else +-- MicroHs has no DataKinds promotion, so the scope index is erased: +-- 'Rule' and 'RuleBinary' coincide. Hooks execution is unsupported in +-- the MHS build (all Hooks entry points fail loudly); only the 'Eq' +-- instance below is exercised, never at runtime in the probe. +type Rule = RuleData () +type RuleBinary = RuleData () +#endif -- | A rule consists of: -- @@ -236,7 +260,11 @@ type RuleBinary = RuleData System -- -- Use 'staticRule' or 'dynamicRule' to construct a rule, overriding specific -- fields, rather than directly using the 'Rule' constructor. +#ifndef __MHS__ data RuleData (scope :: Scope) +#else +data RuleData scope +#endif = -- | Please use the 'staticRule' or 'dynamicRule' smart constructors -- instead of this constructor, in order to avoid relying on internal -- implementation details. @@ -248,6 +276,7 @@ data RuleData (scope :: Scope) , results :: !(NE.NonEmpty Location) -- ^ Results of this rule. } +#ifndef __MHS__ deriving stock (Generic) deriving stock instance Show (RuleData User) @@ -257,6 +286,22 @@ deriving anyclass instance Binary (RuleData User) deriving anyclass instance Binary (RuleData System) deriving anyclass instance Structured (RuleData User) deriving anyclass instance Structured (RuleData System) +#else +-- MicroHs stub: 'Show' is needed for error messages and 'Eq' for the +-- (retained) rule-cache comparison in 'Internal.ruleUpToDate'. 'Binary' +-- is never executed in the MHS build (Hooks execution, including rule-cache +-- serialisation, is unsupported) but 'ruleBinary' needs the instance to +-- exist. There is no 'Structured' instance: 'Structured' would demand a +-- 'Typeable' instance for a bare variable, and nothing retained in the +-- MHS build needs it. +instance Show (RuleData scope) where + showsPrec _ _ = showString "" +instance Eq (RuleData scope) where + _ == _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +instance Binary (RuleData scope) where + put _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + get = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif -- | Trimmed down 'Show' instance, mostly for error messages. instance Show RuleBinary where @@ -279,6 +324,7 @@ instance Show RuleBinary where -- Prefer using this smart constructor instead of v'Rule' whenever possible. -- -- See also 'dynamicRule' which adds support for dynamic dependencies. +#ifndef __MHS__ staticRule :: forall arg . Typeable arg @@ -299,6 +345,20 @@ staticRule cmd dep res = , staticDependencies = dep , results = res } +#else +staticRule + :: forall arg + . Typeable arg + => Command arg (IO ()) + -- ^ command to execute the rule + -> [Dependency] + -- ^ static dependencies of the rule + -> NE.NonEmpty Location + -- ^ rule results + -> Rule +staticRule _ _ _ = + error "staticRule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif -- | A rule with dynamic dependencies, which consists of two parts: -- @@ -310,6 +370,7 @@ staticRule cmd dep res = -- Prefer using this smart constructor instead of v'Rule' whenever possible. -- -- Use 'staticRule' if you do not have any dynamic dependencies. +#ifndef __MHS__ dynamicRule :: forall depsArg depsRes arg . (Typeable depsArg, Typeable depsRes, Typeable arg) @@ -339,6 +400,27 @@ dynamicRule dict depsCmd action dep res = , staticDependencies = dep , results = res } +#else +dynamicRule + :: forall depsArg depsRes arg + . (Typeable depsArg, Typeable depsRes, Typeable arg) + => StaticPtr (Dict (Binary depsRes, Show depsRes, Eq depsRes)) + -- ^ evidence that the result of the dynamic dependency command + -- is serialisable + -> Command depsArg (IO ([Dependency], depsRes)) + -- ^ dynamic dependency computation, returning dynamic dependencies + -- and an additional piece of data to be consumed by the main rule command + -> Command arg (depsRes -> IO ()) + -- ^ main rule command; takes in the piece of data returned by the dyn-deps + -- command + -> [Dependency] + -- ^ static dependencies of the rule + -> NE.NonEmpty Location + -- ^ rule results + -> Rule +dynamicRule _ _ _ _ _ = + error "dynamicRule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif ----------------------- -- Rule inputs/outputs @@ -353,6 +435,15 @@ dynamicRule dict depsCmd action dep res = -- - for a file dependency, @dir@ is one of the Cabal search directories, -- - for an output, @dir@ is a directory such as @autogenComponentModulesDir@ -- or @componentBuildDir@. +#ifdef __MHS__ +-- MicroHs cannot parse record syntax in GADT constructors, so this is +-- the positional equivalent (the field names are unused elsewhere). +data Location where + Location + :: !(SymbolicPath Pkg (Dir baseDir)) + -> !(RelativePath baseDir File) + -> Location +#else data Location where Location :: { locationBaseDir :: !(SymbolicPath Pkg (Dir baseDir)) @@ -361,6 +452,7 @@ data Location where -- ^ File path relative to base directory (including file extension). } -> Location +#endif instance Eq Location where Location b1 l1 == Location b2 l2 = @@ -374,6 +466,7 @@ instance Ord Location where instance Binary Location where put (Location base loc) = put (base, loc) get = Location <$> get <*> get +#ifndef __MHS__ instance Structured Location where structure _ = Structure @@ -390,6 +483,10 @@ instance Structured Location where ] where tr = Typeable.SomeTypeRep $ Typeable.typeRep @Location +#else +instance Structured Location where + structure _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif -- | Get a (relative or absolute) un-interpreted path to a 'Location'. location :: Location -> SymbolicPath Pkg File @@ -558,6 +655,7 @@ computeRules verbosity inputs (Rules rs) = do ------------ -- Commands +#ifndef __MHS__ -- | A static pointer (in user scope) or its key (in system scope). data family Static (scope :: Scope) :: Hs.Type -> Hs.Type @@ -586,6 +684,49 @@ instance Binary (Static User fnTy) where [ "Failed to look up static pointer key for action." , "NB: Binary instances for 'User' types cannot be used in external executables." ] +#else +-- MicroHs has no DataKinds promotion, data families, StaticPtr or +-- Type.Reflection. Static pointers are represented opaquely; any use +-- fails loudly. The MHS build does not support build-type 'Hooks'. +data Static scope a = MhsStatic + deriving stock (Show, Eq, Ord) + +instance Binary (Static scope a) where + put _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + get = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +-- NOTE: no 'Structured' instance for 'Static': 'Structured' demands a +-- 'Typeable' instance, which cannot be conjured for the erased scope +-- variable, and nothing retained in the MHS build needs it. + +-- | Opaque stand-in for 'GHC.StaticPtr.StaticPtr'. +data StaticPtr a = MhsStaticPtr + deriving stock (Show, Eq, Ord) + +instance Binary (StaticPtr a) where + put _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + get = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +-- | Opaque stand-in for 'GHC.StaticPtr.StaticKey'. +type StaticKey = String + +staticKey :: StaticPtr a -> StaticKey +staticKey _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +deRefStaticPtr :: StaticPtr a -> a +deRefStaticPtr _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +data StaticPtrInfo = MhsStaticPtrInfo + +staticPtrInfo :: StaticPtr a -> StaticPtrInfo +staticPtrInfo _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +unsafeLookupStaticPtr :: StaticKey -> IO (Maybe (StaticPtr a)) +unsafeLookupStaticPtr _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +systemStatic :: Static scope a -> Static scope' a +systemStatic _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif -- | A command consists of a statically-known action together with a -- (possibly dynamic) argument to that action. @@ -593,11 +734,19 @@ instance Binary (Static User fnTy) where -- For example, the action can consist of running an executable -- (such as @happy@ or @c2hs@), while the argument consists of the variable -- component of the command, e.g. the specific file to run @happy@ on. +#ifndef __MHS__ type Command = CommandData User +#else +type Command arg res = CommandData () arg res +#endif -- | Internal datatype used for commands, both for the Hooks API ('Command') -- and for the build system. +#ifndef __MHS__ data CommandData (scope :: Scope) (arg :: Hs.Type) (res :: Hs.Type) = Command +#else +data CommandData scope arg res = Command +#endif { actionPtr :: !(Static scope (arg -> res)) -- ^ The (statically-known) action to execute. , actionArg :: !(ScopedArgument scope arg) @@ -615,6 +764,7 @@ mkCommand -> StaticPtr (arg -> res) -> arg -> Command arg res +#ifndef __MHS__ mkCommand dict action arg = Command { actionPtr = UserStatic action @@ -626,6 +776,13 @@ mkCommand dict action arg = runCommand :: Command args res -> res runCommand (Command{actionPtr = UserStatic ptr, actionArg = ScopedArgument arg}) = deRefStaticPtr ptr arg +#else +mkCommand _ _ _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +-- | Run a 'Command'. +runCommand :: Command args res -> res +runCommand _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif -- | Commands to execute a rule: -- @@ -635,6 +792,7 @@ runCommand (Command{actionPtr = UserStatic ptr, actionArg = ScopedArgument arg}) -- -- Prefer using 'staticRule' and 'dynamicRule' instead of the (internal) -- constructors of 'RuleCommands'. +#ifndef __MHS__ data RuleCommands (scope :: Scope) @@ -685,6 +843,28 @@ data -- ^ A 'TypeRep' for the triple @(depsArg,depsRes,arg)@. } -> RuleCommands scope deps ruleCmd +#else +-- MicroHs has no DataKinds promotion: the scope index is a plain type +-- variable, and the 'TypeRep' witnesses (which need Type.Reflection) +-- are erased to '()'. MicroHs GADTs have no record syntax, so the +-- constructors are positional. Hooks execution is unsupported in the +-- MHS build. +data RuleCommands scope deps ruleCmd where + -- | A rule with statically-known dependencies. + -- Fields: the command to execute the rule; erased 'TypeRep' witness. + StaticRuleCommand + :: forall arg deps ruleCmd scope + . ruleCmd scope arg (IO ()) + -> () + -> RuleCommands scope deps ruleCmd + DynamicRuleCommands + :: forall depsArg depsRes arg deps ruleCmd scope + . Static scope (Dict (Binary depsRes, Show depsRes, Eq depsRes)) + -> deps scope depsArg depsRes + -> ruleCmd scope arg (depsRes -> IO ()) + -> () + -> RuleCommands scope deps ruleCmd +#endif -- NB: whenever you change this datatype, you **must** also update its -- 'Structured' instance. The structure hash is used as a handshake when @@ -739,9 +919,14 @@ includes the length. We use this newtype: - in the definition of 'DepsRes', for the result of dynamic dependency computations. -} +#ifndef __MHS__ newtype ScopedArgument (scope :: Scope) arg = ScopedArgument {getArg :: arg} +#else +newtype ScopedArgument scope arg = ScopedArgument {getArg :: arg} +#endif deriving newtype (Eq, Ord, Show) +#ifndef __MHS__ -- | Serialise/deserialise, always including the length of the payload. instance Binary arg => Binary (ScopedArgument User arg) where put (ScopedArgument arg) = put @LBS.ByteString (Binary.encode arg) @@ -755,10 +940,24 @@ instance Binary arg => Binary (ScopedArgument User arg) where instance arg ~ LBS.ByteString => Binary (ScopedArgument System arg) where put (ScopedArgument arg) = put arg get = ScopedArgument <$> get +#else +-- MicroHs erases the scope index (no DataKinds promotion). +instance Binary arg => Binary (ScopedArgument scope arg) where + put (ScopedArgument arg) = put @LBS.ByteString (Binary.encode arg) + get = do + dat <- get @LBS.ByteString + case Binary.decodeOrFail dat of + Left (_, _, err) -> fail err + Right (_, _, res) -> return $ ScopedArgument res +#endif -- | A placeholder for a command that has been omitted, e.g. when we don't -- care about serialising/deserialising one particular command in a datatype. +#ifndef __MHS__ data NoCmd (scope :: Scope) arg res = CmdOmitted +#else +data NoCmd scope arg res = CmdOmitted +#endif deriving stock (Generic, Eq, Ord, Show) deriving anyclass (Binary) @@ -768,6 +967,7 @@ newtype DynDepsCmd scope depsArg depsRes = DynDepsCmd :: CommandData scope depsArg (IO ([Dependency], depsRes)) } +#ifndef __MHS__ deriving newtype instance Show (DynDepsCmd User depsArg depsRes) deriving newtype instance Eq (DynDepsCmd User depsArg depsRes) deriving newtype instance Binary (DynDepsCmd User depsArg depsRes) @@ -777,9 +977,19 @@ deriving newtype instance deriving newtype instance (arg ~ LBS.ByteString, depsRes ~ LBS.ByteString) => Binary (DynDepsCmd System arg depsRes) +#else +-- MicroHs erases the scope index (no DataKinds promotion). +deriving newtype instance Show (DynDepsCmd scope depsArg depsRes) +deriving newtype instance Eq (DynDepsCmd scope depsArg depsRes) +deriving newtype instance Binary (DynDepsCmd scope depsArg depsRes) +#endif -- | The result of a dynamic dependency computation. +#ifndef __MHS__ newtype DepsRes (scope :: Scope) depsArg depsRes = DepsRes +#else +newtype DepsRes scope depsArg depsRes = DepsRes +#endif { depsRes :: ScopedArgument scope depsRes -- See Note [Hooks Binary instances] } @@ -799,6 +1009,7 @@ type RuleDynDepsCmd scope = RuleCommands scope DynDepsCmd NoCmd -- dependency computation. type RuleExecCmd scope = RuleCommands scope DepsRes CommandData +#ifndef __MHS__ -- | Project out the (optional) dependency computation command, so that -- it can be serialised without serialising anything else. ruleDepsCmd :: RuleCmds scope -> RuleDynDepsCmd scope @@ -823,7 +1034,14 @@ ruleDepsCmd = \case , dynamicRuleCommand = CmdOmitted :: NoCmd scope args (depsRes -> IO ()) , dynamicRuleTypeRep = tr } +#else +-- MicroHs stub for 'ruleDepsCmd': Hooks execution is unsupported in the +-- MHS build. +ruleDepsCmd :: RuleCmds scope -> RuleDynDepsCmd scope +ruleDepsCmd _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif +#ifndef __MHS__ -- | Obtain the (optional) 'IO' action that computes dynamic dependencies. runRuleDynDepsCmd :: RuleDynDepsCmd User -> Maybe (IO ([Dependency], LBS.ByteString)) runRuleDynDepsCmd = \case @@ -889,6 +1107,18 @@ runRuleExecCmd = \case , dynamicRuleCommand = cmd } -> runCommand cmd res +#else +-- MicroHs stubs: Hooks execution is unsupported in the MHS build (no +-- DataKinds promotion: the scope index is erased). +runRuleDynDepsCmd :: RuleDynDepsCmd scope -> Maybe (IO ([Dependency], LBS.ByteString)) +runRuleDynDepsCmd _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +ruleExecCmd :: SScope scope -> RuleCmds scope -> Maybe LBS.ByteString -> RuleExecCmd scope +ruleExecCmd _ _ _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +runRuleExecCmd :: RuleExecCmd scope -> IO () +runRuleExecCmd _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif -------------------------------------------------------------------------------- -- Instances @@ -897,6 +1127,7 @@ runRuleExecCmd = \case data Dict c where Dict :: c => Dict c +#ifndef __MHS__ instance Show (CommandData User arg res) where showsPrec prec (Command{actionPtr = cmdPtr, actionArg = arg, cmdInstances = insts}) | Dict <- deRefStaticPtr (userStaticPtr insts) = @@ -952,7 +1183,20 @@ instance arg ~ LBS.ByteString => Binary (CommandData System arg res) where instsKey <- get arg <- get return $ Command{actionPtr = cmdKey, actionArg = arg, cmdInstances = instsKey} - +#else +-- MicroHs erases the scope index (no DataKinds promotion): a single set of +-- instances covers both scopes. Hooks execution is unsupported in the MHS +-- build, so these fail loudly if ever used. +instance Show (CommandData scope arg res) where + showsPrec _ _ = showString "" +instance Eq (CommandData scope arg res) where + _ == _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +instance Binary (CommandData scope arg res) where + put _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + get = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif + +#ifndef __MHS__ instance ( forall arg res. Show (ruleCmd User arg res) , forall depsArg depsRes. Show depsRes => Show (deps User depsArg depsRes) @@ -982,7 +1226,14 @@ instance . showString "dynamicRuleCommand = " . shows cmd . showString "}" - +#else +-- MicroHs erases the scope index (no DataKinds promotion) and has no +-- Type.Reflection: a single set of instances covers both scopes. +instance Show (RuleCommands scope deps ruleCmd) where + showsPrec _ _ = showString "" +#endif + +#ifndef __MHS__ instance ( forall arg res. Eq (ruleCmd User arg res) , forall depsArg depsRes. Eq depsRes => Eq (deps User depsArg depsRes) @@ -1022,7 +1273,12 @@ instance DynamicRuleCommands a1 b1 c1 d1 == DynamicRuleCommands a2 b2 c2 d2 = a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2 _ == _ = False +#else +instance Eq (RuleCommands scope deps ruleCmd) where + _ == _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." +#endif +#ifndef __MHS__ instance ( forall arg res. Binary (ruleCmd User arg res) , forall depsArg depsRes. Binary depsRes => Binary (deps User depsArg depsRes) @@ -1173,6 +1429,18 @@ instance , dynamicRuleInstances = instsKey , dynamicRuleTypeRep = sTr } +#else +-- MicroHs erases the scope index (no DataKinds promotion) and has no +-- Type.Reflection: a single set of instances covers both scopes. +-- Hooks execution is unsupported in the MHS build. +instance Binary (RuleCommands scope deps ruleCmd) where + put _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + get = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." + +-- NOTE: no 'Structured' instance for 'RuleCommands': 'Structured' demands +-- a 'Typeable' instance, which cannot be conjured for the erased scope +-- variable, and nothing retained in the MHS build needs it. +#endif -------------------------------------------------------------------------------- -- Showing rules diff --git a/Cabal/src/Distribution/Simple/ShowBuildInfo.hs b/Cabal/src/Distribution/Simple/ShowBuildInfo.hs index e10f2b69e3a..e13ea69be9c 100644 --- a/Cabal/src/Distribution/Simple/ShowBuildInfo.hs +++ b/Cabal/src/Distribution/Simple/ShowBuildInfo.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} -- | diff --git a/Cabal/src/Distribution/Simple/SrcDist.hs b/Cabal/src/Distribution/Simple/SrcDist.hs index 883b4994c78..73ca1188676 100644 --- a/Cabal/src/Distribution/Simple/SrcDist.hs +++ b/Cabal/src/Distribution/Simple/SrcDist.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- NOTE: FIX: we don't have a great way of testing this module, since -- we can't easily look inside a tarball once its created. @@ -64,7 +62,7 @@ import Distribution.Version import qualified Data.Map as Map import Data.Time (UTCTime, getCurrentTime, toGregorian, utctDay) -import System.Directory (doesFileExist) +import Distribution.Compat.Directory (doesFileExist) import System.IO (IOMode (WriteMode), hPutStrLn, withFile) -- | Create a source distribution. diff --git a/Cabal/src/Distribution/Simple/Test.hs b/Cabal/src/Distribution/Simple/Test.hs index 42fcd3346ff..752f0f2aee2 100644 --- a/Cabal/src/Distribution/Simple/Test.hs +++ b/Cabal/src/Distribution/Simple/Test.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE ViewPatterns #-} @@ -47,7 +46,7 @@ import Distribution.Simple.Setup.Config import Distribution.Types.ExposedModule import Distribution.Types.InstalledPackageInfo (InstalledPackageInfo (libraryDirs), exposedModules) import Distribution.Types.LocalBuildInfo (LocalBuildInfo (..)) -import System.Directory +import Distribution.Compat.Directory ( createDirectoryIfMissing , listDirectory ) diff --git a/Cabal/src/Distribution/Simple/Test/ExeV10.hs b/Cabal/src/Distribution/Simple/Test/ExeV10.hs index 28cbc9062bc..26553f2bb86 100644 --- a/Cabal/src/Distribution/Simple/Test/ExeV10.hs +++ b/Cabal/src/Distribution/Simple/Test/ExeV10.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} module Distribution.Simple.Test.ExeV10 ( runTest ) where @@ -39,12 +40,19 @@ import Distribution.Utils.Path import qualified Data.ByteString.Lazy as LBS import Distribution.Simple.LocalBuildInfo (interpretSymbolicPathLBI, packageRoot) -import System.Directory +import Distribution.Compat.Directory ( createDirectoryIfMissing , doesFileExist , removePathForcibly ) -import System.Process (createPipe) +#ifdef __MHS__ +import Distribution.Compat.Internal.LazyByteString (readFileLBS) +#endif +#ifndef __MHS__ +import Distribution.Compat.Process (createPipe) +#else +import qualified Distribution.Compat.Process as Process +#endif runTest :: VerbosityHandles @@ -107,6 +115,27 @@ runTest verbHandles pkg_descr lbi clbi hpcMarkupInfo flags suite = do return (addLibraryPath os paths shellEnv) else return shellEnv +#ifdef __MHS__ + -- MHS: capture sequentially (stage, spawn, wait, read) instead of + -- streaming through a pipe; complete by construction. Standard + -- output and error are concatenated (in that order) rather than + -- interleaved as with a real pipe. + let runExe exe exeArgs workDir = do + (exitcode, captured) <- + Process.captureProcess + ((Process.proc exe exeArgs) {Process.env = Just shellEnv', Process.cwd = workDir}) + Process.NoInput + outLog <- readFileLBS (Process.capturedOutPath captured) + errLog <- readFileLBS (Process.capturedErrPath captured) + let logText = outLog <> errLog + _ <- evaluate (force logText) + Process.capturedRelease captured + -- '--show-details=streaming': the log is only shown once it is + -- complete, not while the test is running. + when (details == Streaming) $ + LBS.hPutStr (verbosityChosenOutputHandle verbosity) logText + return (exitcode, logText) +#else -- Output logger (wOut, wErr, getLogText) <- case details of Direct -> return (Nothing, Nothing, return LBS.empty) @@ -123,12 +152,17 @@ runTest verbHandles pkg_descr lbi clbi hpcMarkupInfo flags suite = do -- drain the output. evaluate (force logText) +#endif let mbWorkDir = interpretSymbolicPathCWD <$> flagToMaybe (setupWorkingDir (testCommonFlags flags)) (exit, logText) <- case testWrapper flags of +#ifdef __MHS__ + Flag path -> runExe path (cmd : opts) mbWorkDir + NoFlag -> runExe cmd opts mbWorkDir +#else Flag path -> rawSystemIOWithEnvAndAction verbosity @@ -151,6 +185,7 @@ runTest verbHandles pkg_descr lbi clbi hpcMarkupInfo flags suite = do Nothing wOut wErr +#endif -- Generate TestSuiteLog from executable exit code and a machine- -- readable test log. diff --git a/Cabal/src/Distribution/Simple/Test/LibV09.hs b/Cabal/src/Distribution/Simple/Test/LibV09.hs index 96ca8e14cac..a4d9455513d 100644 --- a/Cabal/src/Distribution/Simple/Test/LibV09.hs +++ b/Cabal/src/Distribution/Simple/Test/LibV09.hs @@ -1,5 +1,4 @@ -{-# LANGUAGE DataKinds #-} - +{-# LANGUAGE CPP #-} module Distribution.Simple.Test.LibV09 ( runTest -- Test stub @@ -41,7 +40,7 @@ import Distribution.Verbosity import qualified Control.Exception as CE import qualified Data.ByteString.Lazy as LBS -import System.Directory +import Distribution.Compat.Directory ( canonicalizePath , createDirectoryIfMissing , doesFileExist @@ -49,8 +48,11 @@ import System.Directory , removePathForcibly , setCurrentDirectory ) +#ifdef __MHS__ +import Distribution.Compat.Internal.LazyByteString (readFileLBS) +#endif import System.IO (hClose, hPutStr) -import qualified System.Process as Process +import qualified Distribution.Compat.Process as Process runTest :: VerbosityHandles @@ -118,6 +120,21 @@ runTest verbHandles pkg_descr lbi clbi hpcMarkupInfo flags suite = do Flag path -> (path, cmd : opts) NoFlag -> (cmd, opts) +#ifdef __MHS__ + -- MHS: capture sequentially (stage input, spawn, wait, read) + -- instead of streaming through a pipe; complete by construction. + -- Standard output and error are concatenated (in that order) + -- rather than interleaved as with a real pipe. + (exitcode, captured) <- + Process.captureProcess + ((proc cmd' opts') {Process.env = Just shellEnv'}) + (Process.TextInput (show (tempLog, PD.testName suite))) + outLog <- readFileLBS (Process.capturedOutPath captured) + errLog <- readFileLBS (Process.capturedErrPath captured) + let logText = outLog <> errLog + _ <- evaluate (force logText) + Process.capturedRelease captured +#else -- TODO: this setup is broken, -- if the test output is too big, we will deadlock. (rOut, wOut) <- Process.createPipe @@ -140,6 +157,7 @@ runTest verbHandles pkg_descr lbi clbi hpcMarkupInfo flags suite = do -- Force the IO manager to drain the test output pipe _ <- evaluate (force logText) return logText +#endif unless (exitcode == ExitSuccess) $ debug verbosity $ cmd ++ " returned " ++ show exitcode diff --git a/Cabal/src/Distribution/Simple/UHC.hs b/Cabal/src/Distribution/Simple/UHC.hs index 612f9faed28..876b2a66b2c 100644 --- a/Cabal/src/Distribution/Simple/UHC.hs +++ b/Cabal/src/Distribution/Simple/UHC.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE MultiWayIf #-} -- | @@ -48,7 +47,7 @@ import Language.Haskell.Extension import qualified Data.Map as Map (empty) import qualified Data.Text as Text -import System.Directory +import Distribution.Compat.Directory import System.FilePath (pathSeparator) -- ----------------------------------------------------------------------------- diff --git a/Cabal/src/Distribution/Simple/Utils.hs b/Cabal/src/Distribution/Simple/Utils.hs index 1bfb58cb847..75437b0028d 100644 --- a/Cabal/src/Distribution/Simple/Utils.hs +++ b/Cabal/src/Distribution/Simple/Utils.hs @@ -1,5 +1,4 @@ {-# LANGUAGE CPP #-} -{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} #if MIN_VERSION_base(4,21,0) {-# LANGUAGE ImplicitParams #-} @@ -214,6 +213,7 @@ module Distribution.Simple.Utils import Distribution.Compat.Async (waitCatch, withAsyncNF) import Distribution.Compat.CopyFile +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.Compat.Internal.TempFile import Distribution.Compat.Lens (Lens', over) import Distribution.Compat.Prelude @@ -255,10 +255,20 @@ import qualified Data.Version as DV import Distribution.Compat.Process (proc) import Foreign.C.Error (Errno (..), ePIPE) import qualified GHC.IO.Exception as GHC +#ifndef __MHS__ import GHC.IO.Handle.Lock (LockMode (..), hLock, hTryLock, hUnlock) -import GHC.Stack (HasCallStack) +#else +-- MicroHs ships no GHC.IO.Handle.Lock; file locking is best-effort there. +data LockMode = ExclusiveLock deriving (Eq, Show) +hLock :: Handle -> LockMode -> IO () +hLock _ _ = pure () +hTryLock :: Handle -> LockMode -> IO Bool +hTryLock _ _ = pure True +hUnlock :: Handle -> IO () +hUnlock _ = pure () +#endif import Numeric (showFFloat) -import System.Directory +import Distribution.Compat.Directory ( Permissions (executable) , createDirectory , doesDirectoryExist @@ -294,19 +304,26 @@ import System.IO , hGetContents , hPutStr , hPutStrLn +#ifndef __MHS__ , hSetBinaryMode +#endif , hSetBuffering , openFile , stderr , stdin , stdout ) +#ifdef __MHS__ +-- MicroHs System.IO has no binary/text mode distinction. +hSetBinaryMode :: Handle -> Bool -> IO () +hSetBinaryMode _ _ = pure () +#endif import System.IO.Error import System.IO.Unsafe ( unsafeInterleaveIO ) import qualified System.Info as SI -import qualified System.Process as Process +import qualified Distribution.Compat.Process as Process import qualified Text.PrettyPrint as Disp #ifdef GIT_REV @@ -1212,6 +1229,56 @@ rawSystemStdInOut -- ^ iodata mode, acts as proxy -> IO (mode, String, ExitCode) -- ^ output, errors, exit +#ifdef __MHS__ +rawSystemStdInOut verbosity path args mcwd menv input iomode = withFrozenCallStack $ do + -- MHS: temporary files cannot emulate blocking pipes, so capture + -- sequentially (stage input, spawn, wait, read outputs) instead of + -- streaming. Complete by construction; never silently truncates. + -- Text is locale-encoded like 'System.IO.hPutStr'/'hGetContents', + -- never truncated to Latin-1. + let cp = + (proc path args) + { Process.cwd = mcwd + , Process.env = menv + } + staged = case input of + Nothing -> Process.NoInput + Just (IODataText s) -> Process.TextInput s + Just (IODataBinary b) -> Process.BinaryInput b + (exitcode, captured) <- Process.captureProcess cp staged + -- The output mode determines the decoding; each branch reads, + -- forces, releases, reports and returns on its own so the types + -- line up. + case iomode of + IODataModeText -> do + out <- readFile (Process.capturedOutPath captured) + errors <- readFile (Process.capturedErrPath captured) + length out `seq` length errors `seq` return () + Process.capturedRelease captured + unless (exitcode == ExitSuccess) $ + debug verbosity $ + path + ++ " returned " + ++ show exitcode + ++ if null errors + then "" + else " with error message:\n" ++ errors + return (out, errors, exitcode) + IODataModeBinary -> do + out <- readFileLBS (Process.capturedOutPath captured) + errors <- readFile (Process.capturedErrPath captured) + BS.length out `seq` length errors `seq` return () + Process.capturedRelease captured + unless (exitcode == ExitSuccess) $ + debug verbosity $ + path + ++ " returned " + ++ show exitcode + ++ if null errors + then "" + else " with error message:\n" ++ errors + return (out, errors, exitcode) +#else rawSystemStdInOut verbosity path args mcwd menv input _ = withFrozenCallStack $ do let cp = (proc path args) @@ -1273,6 +1340,7 @@ rawSystemStdInOut verbosity path args mcwd menv input _ = withFrozenCallStack $ reportOutputIOError (Left exc) = case fromException exc of Just ioe -> throwIO (ioeSetFileName ioe ("output of " ++ path)) Nothing -> throwIO exc +#endif -- | Ignore SIGPIPE in a subcomputation. ignoreSigPipe :: IO () -> IO () @@ -2053,7 +2121,7 @@ rewriteFileEx verbosity path = rewriteFileLBS :: Verbosity -> FilePath -> BS.ByteString -> IO () rewriteFileLBS verbosity path newContent = flip catchIO mightNotExist $ do - existingContent <- annotateIO verbosity $ BS.readFile path + existingContent <- annotateIO verbosity $ readFileLBS path _ <- evaluate (BS.length existingContent) unless (existingContent == newContent) $ annotateIO verbosity $ diff --git a/Cabal/src/Distribution/Types/ComponentLocalBuildInfo.hs b/Cabal/src/Distribution/Types/ComponentLocalBuildInfo.hs index acab8d4c705..c815f0690f5 100644 --- a/Cabal/src/Distribution/Types/ComponentLocalBuildInfo.hs +++ b/Cabal/src/Distribution/Types/ComponentLocalBuildInfo.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} - module Distribution.Types.ComponentLocalBuildInfo ( ComponentLocalBuildInfo (..) , componentIsIndefinite @@ -113,8 +111,7 @@ data ComponentLocalBuildInfo instance Binary ComponentLocalBuildInfo instance Structured ComponentLocalBuildInfo -instance IsNode ComponentLocalBuildInfo where - type Key ComponentLocalBuildInfo = UnitId +instance IsNode UnitId ComponentLocalBuildInfo where nodeKey = componentUnitId nodeNeighbors = componentInternalDeps diff --git a/Cabal/src/Distribution/Types/LocalBuildConfig.hs b/Cabal/src/Distribution/Types/LocalBuildConfig.hs index 984cbc18161..d4113b8ed65 100644 --- a/Cabal/src/Distribution/Types/LocalBuildConfig.hs +++ b/Cabal/src/Distribution/Types/LocalBuildConfig.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE DataKinds #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE RecordWildCards #-} @@ -86,7 +85,7 @@ data PackageBuildDescr = PackageBuildDescr -- | Information about individual components in a package, -- determined after the configure step. data ComponentBuildDescr = ComponentBuildDescr - { componentGraph :: Graph ComponentLocalBuildInfo + { componentGraph :: Graph UnitId ComponentLocalBuildInfo -- ^ All the components to build, ordered by topological -- sort, and with their INTERNAL dependencies over the -- intrapackage dependency graph. diff --git a/Cabal/src/Distribution/Types/LocalBuildInfo.hs b/Cabal/src/Distribution/Types/LocalBuildInfo.hs index 7e91a5ebeb2..7a06a4486c5 100644 --- a/Cabal/src/Distribution/Types/LocalBuildInfo.hs +++ b/Cabal/src/Distribution/Types/LocalBuildInfo.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE PatternSynonyms #-} @@ -49,6 +49,11 @@ module Distribution.Types.LocalBuildInfo ) -- * Convenience accessors +#ifdef __MHS__ + , mkFlatLocalBuildInfo + , localBuildDescr + , localBuildConfig +#endif , localComponentId , localUnitId , localCompatPackageKey @@ -134,6 +139,160 @@ import qualified System.FilePath as FilePath (takeDirectory) -- | Data cached after configuration step. See also -- 'Distribution.Simple.Setup.ConfigFlags'. +#ifdef __MHS__ +-- MicroHs cannot parse record pattern synonyms, so the backwards-compatible +-- flat view is a real datatype here instead of a pattern synonym. All use +-- sites mention only 'LocalBuildInfo' and its field names, so they keep working +-- unchanged; use 'mkFlatLocalBuildInfo' to build one from the nested representation. +data LocalBuildInfo = LocalBuildInfo + { configFlags :: ConfigFlags + , flagAssignment :: FlagAssignment + , componentEnabledSpec :: ComponentRequestedSpec + , extraConfigArgs :: [String] + , installDirTemplates :: InstallDirTemplates + , compiler :: Compiler + , hostPlatform :: Platform + , pkgDescrFile :: Maybe (SymbolicPath Pkg File) + , componentGraph :: Graph UnitId ComponentLocalBuildInfo + , componentNameMap :: Map ComponentName [ComponentLocalBuildInfo] + , promisedPkgs :: Map (PackageName, ComponentName) PromisedComponent + , installedPkgs :: InstalledPackageIndex + , localPkgDescr :: PackageDescription + , withPrograms :: ProgramDb + , withPackageDB :: PackageDBStack + , withVanillaLib :: Bool + , withProfLib :: Bool + , withProfLibShared :: Bool + , withSharedLib :: Bool + , withStaticLib :: Bool + , withBytecodeLib :: Bool + , withDynExe :: Bool + , withFullyStaticExe :: Bool + , withProfExe :: Bool + , withProfLibDetail :: ProfDetailLevel + , withProfExeDetail :: ProfDetailLevel + , withOptimization :: OptimisationLevel + , withDebugInfo :: DebugInfoLevel + , withGHCiLib :: Bool + , splitSections :: Bool + , splitObjs :: Bool + , stripExes :: Bool + , stripLibs :: Bool + , exeCoverage :: Bool + , libCoverage :: Bool + , extraCoverageFor :: [UnitId] + , relocatable :: Bool + , programPrefix :: Maybe PathTemplate + , programSuffix :: Maybe PathTemplate + } + deriving (Generic, Read, Show) + +-- | Build the flat 'LocalBuildInfo' view from the nested representation. +mkFlatLocalBuildInfo :: LBC.LocalBuildDescr -> LBC.LocalBuildConfig -> LocalBuildInfo +mkFlatLocalBuildInfo lbd lbc = LocalBuildInfo + { configFlags = LBC.configFlags pbd + , flagAssignment = LBC.flagAssignment pbd + , componentEnabledSpec = LBC.componentEnabledSpec pbd + , extraConfigArgs = LBC.extraConfigArgs lbc + , installDirTemplates = LBC.installDirTemplates pbd + , compiler = LBC.compiler pbd + , hostPlatform = LBC.hostPlatform pbd + , pkgDescrFile = LBC.pkgDescrFile pbd + , componentGraph = LBC.componentGraph cbd + , componentNameMap = LBC.componentNameMap cbd + , promisedPkgs = LBC.promisedPkgs cbd + , installedPkgs = LBC.installedPkgs cbd + , localPkgDescr = LBC.localPkgDescr pbd + , withPrograms = LBC.withPrograms lbc + , withPackageDB = LBC.withPackageDB pbd + , withVanillaLib = LBC.withVanillaLib bopts + , withProfLib = LBC.withProfLib bopts + , withProfLibShared = LBC.withProfLibShared bopts + , withSharedLib = LBC.withSharedLib bopts + , withStaticLib = LBC.withStaticLib bopts + , withBytecodeLib = LBC.withBytecodeLib bopts + , withDynExe = LBC.withDynExe bopts + , withFullyStaticExe = LBC.withFullyStaticExe bopts + , withProfExe = LBC.withProfExe bopts + , withProfLibDetail = LBC.withProfLibDetail bopts + , withProfExeDetail = LBC.withProfExeDetail bopts + , withOptimization = LBC.withOptimization bopts + , withDebugInfo = LBC.withDebugInfo bopts + , withGHCiLib = LBC.withGHCiLib bopts + , splitSections = LBC.splitSections bopts + , splitObjs = LBC.splitObjs bopts + , stripExes = LBC.stripExes bopts + , stripLibs = LBC.stripLibs bopts + , exeCoverage = LBC.exeCoverage bopts + , libCoverage = LBC.libCoverage bopts + , extraCoverageFor = LBC.extraCoverageFor pbd + , relocatable = LBC.relocatable bopts + , programPrefix = LBC.programPrefix bopts + , programSuffix = LBC.programSuffix bopts + } + where + pbd = LBC.packageBuildDescr lbd + cbd = LBC.componentBuildDescr lbd + bopts = LBC.withBuildOptions lbc + +localBuildDescr :: LocalBuildInfo -> LBC.LocalBuildDescr +localBuildDescr lbi = + LBC.LocalBuildDescr + { LBC.packageBuildDescr = + LBC.PackageBuildDescr + { LBC.configFlags = configFlags lbi + , LBC.flagAssignment = flagAssignment lbi + , LBC.componentEnabledSpec = componentEnabledSpec lbi + , LBC.compiler = compiler lbi + , LBC.hostPlatform = hostPlatform lbi + , LBC.localPkgDescr = localPkgDescr lbi + , LBC.installDirTemplates = installDirTemplates lbi + , LBC.withPackageDB = withPackageDB lbi + , LBC.pkgDescrFile = pkgDescrFile lbi + , LBC.extraCoverageFor = extraCoverageFor lbi + } + , LBC.componentBuildDescr = + LBC.ComponentBuildDescr + { LBC.componentGraph = componentGraph lbi + , LBC.componentNameMap = componentNameMap lbi + , LBC.promisedPkgs = promisedPkgs lbi + , LBC.installedPkgs = installedPkgs lbi + } + } + +localBuildConfig :: LocalBuildInfo -> LBC.LocalBuildConfig +localBuildConfig lbi = + LBC.LocalBuildConfig + { LBC.extraConfigArgs = extraConfigArgs lbi + , LBC.withPrograms = withPrograms lbi + , LBC.withBuildOptions = + LBC.BuildOptions + { LBC.withVanillaLib = withVanillaLib lbi + , LBC.withProfLib = withProfLib lbi + , LBC.withProfLibShared = withProfLibShared lbi + , LBC.withSharedLib = withSharedLib lbi + , LBC.withStaticLib = withStaticLib lbi + , LBC.withBytecodeLib = withBytecodeLib lbi + , LBC.withDynExe = withDynExe lbi + , LBC.withFullyStaticExe = withFullyStaticExe lbi + , LBC.withProfExe = withProfExe lbi + , LBC.withProfLibDetail = withProfLibDetail lbi + , LBC.withProfExeDetail = withProfExeDetail lbi + , LBC.withOptimization = withOptimization lbi + , LBC.withDebugInfo = withDebugInfo lbi + , LBC.withGHCiLib = withGHCiLib lbi + , LBC.splitSections = splitSections lbi + , LBC.splitObjs = splitObjs lbi + , LBC.stripExes = stripExes lbi + , LBC.stripLibs = stripLibs lbi + , LBC.exeCoverage = exeCoverage lbi + , LBC.libCoverage = libCoverage lbi + , LBC.relocatable = relocatable lbi + , LBC.programPrefix = programPrefix lbi + , LBC.programSuffix = programSuffix lbi + } + } +#else data LocalBuildInfo = NewLocalBuildInfo { localBuildDescr :: LBC.LocalBuildDescr -- ^ Information about a package determined by Cabal @@ -157,7 +316,7 @@ pattern LocalBuildInfo -> Compiler -> Platform -> Maybe (SymbolicPath Pkg File) - -> Graph ComponentLocalBuildInfo + -> Graph UnitId ComponentLocalBuildInfo -> Map ComponentName [ComponentLocalBuildInfo] -> Map (PackageName, ComponentName) PromisedComponent -> InstalledPackageIndex @@ -286,6 +445,7 @@ pattern LocalBuildInfo } } } +#endif instance Binary LocalBuildInfo instance Structured LocalBuildInfo diff --git a/Cabal/src/Distribution/Types/TargetInfo.hs b/Cabal/src/Distribution/Types/TargetInfo.hs index e5eb8cc2e68..487dd5bf4c6 100644 --- a/Cabal/src/Distribution/Types/TargetInfo.hs +++ b/Cabal/src/Distribution/Types/TargetInfo.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} - module Distribution.Types.TargetInfo ( TargetInfo (..) ) where @@ -32,7 +30,6 @@ data TargetInfo = TargetInfo instance Binary TargetInfo instance Structured TargetInfo -instance IsNode TargetInfo where - type Key TargetInfo = UnitId +instance IsNode UnitId TargetInfo where nodeKey = nodeKey . targetCLBI nodeNeighbors = nodeNeighbors . targetCLBI diff --git a/Cabal/src/Distribution/Utils/IOData.hs b/Cabal/src/Distribution/Utils/IOData.hs index 78dc854df1c..67727245277 100644 --- a/Cabal/src/Distribution/Utils/IOData.hs +++ b/Cabal/src/Distribution/Utils/IOData.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} -- | @since 2.2.0 @@ -12,6 +13,7 @@ module Distribution.Utils.IOData ) where import qualified Data.ByteString.Lazy as LBS +import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS) import Distribution.Compat.Prelude hiding (null) import qualified System.IO import qualified Prelude @@ -62,16 +64,26 @@ data IODataMode mode where instance a ~ Char => KnownIODataMode [a] where hGetIODataContents h = do +#ifdef __MHS__ + -- MicroHs handles have no text/binary mode switch. + System.IO.hGetContents h +#else System.IO.hSetBinaryMode h False System.IO.hGetContents h +#endif toIOData = IODataText iodataMode = IODataModeText instance KnownIODataMode LBS.ByteString where hGetIODataContents h = do +#ifndef __MHS__ System.IO.hSetBinaryMode h True - LBS.hGetContents h +#endif + -- 'hGetContentsLBS' is 'LBS.hGetContents' on GHC; under MHS it + -- avoids 'hGetSome', which MicroHs does not implement (and + -- MicroHs handles have no text/binary mode switch to set). + hGetContentsLBS h toIOData = IODataBinary iodataMode = IODataModeBinary @@ -86,10 +98,20 @@ instance KnownIODataMode LBS.ByteString where -- @since 2.2 hPutContents :: System.IO.Handle -> IOData -> Prelude.IO () hPutContents h (IODataText c) = do +#ifdef __MHS__ + -- MicroHs handles have no text/binary mode switch. + System.IO.hPutStr h c +#else System.IO.hSetBinaryMode h False System.IO.hPutStr h c +#endif System.IO.hClose h hPutContents h (IODataBinary c) = do +#ifdef __MHS__ + -- MicroHs handles have no text/binary mode switch. + LBS.hPutStr h c +#else System.IO.hSetBinaryMode h True LBS.hPutStr h c +#endif System.IO.hClose h diff --git a/Cabal/src/Distribution/Utils/LogProgress.hs b/Cabal/src/Distribution/Utils/LogProgress.hs index 2d0380a3bcd..c2c70b48f49 100644 --- a/Cabal/src/Distribution/Utils/LogProgress.hs +++ b/Cabal/src/Distribution/Utils/LogProgress.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + module Distribution.Utils.LogProgress ( LogProgress , runLogProgress @@ -5,6 +7,9 @@ module Distribution.Utils.LogProgress , infoProgress , dieProgress , addProgressCtx +#ifdef __MHS__ + , hang +#endif ) where import Distribution.Compat.Prelude @@ -13,7 +18,7 @@ import Prelude () import Distribution.Simple.Utils import Distribution.Utils.Progress import Distribution.Verbosity -import GHC.Stack (HasCallStack, callStack, prettyCallStack) +import Distribution.Compat.Stack (HasCallStack, callStack, prettyCallStack) import System.IO (hFlush, hPutStr, hPutStrLn) import Text.PrettyPrint @@ -21,6 +26,11 @@ type CtxMsg = Doc data LogMsg = WarnMsg Doc | InfoMsg Doc type ErrMsg = Doc +#ifdef __MHS__ +hang :: Doc -> Int -> Doc -> Doc +hang d1 n d2 = sep [d1, nest n d2] +#endif + data LogEnv = LogEnv { le_verbosity :: Verbosity , le_context :: [CtxMsg] diff --git a/Cabal/src/Distribution/Utils/UnionFind.hs b/Cabal/src/Distribution/Utils/UnionFind.hs index 29443710ae7..0af3c99a317 100644 --- a/Cabal/src/Distribution/Utils/UnionFind.hs +++ b/Cabal/src/Distribution/Utils/UnionFind.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NondecreasingIndentation #-} @@ -18,11 +19,24 @@ module Distribution.Utils.UnionFind import Control.Monad import Control.Monad.ST import Data.STRef +#ifdef __MHS__ +import Data.IORef (IORef) +import Unsafe.Coerce (unsafeCoerce) +#endif -- | A variable which can be unified; alternately, this can be thought -- of as an equivalence class with a distinguished representative. newtype Point s a = Point (STRef s (Link s a)) +#ifndef __MHS__ deriving (Eq) +#endif + +#ifdef __MHS__ +-- MicroHs 'STRef' is @newtype STRef s a = R (IORef a)@ with no 'Eq' +-- instance, whereas 'IORef' has pointer-identity 'Eq' via @primArrEQ@. +instance Eq (Point s a) where + Point r1 == Point r2 = (unsafeCoerce r1 :: IORef ()) == unsafeCoerce r2 +#endif -- | Mutable write to a 'Point' writePoint :: Point s a -> Link s a -> ST s () diff --git a/Cabal/src/Distribution/Verbosity.hs b/Cabal/src/Distribution/Verbosity.hs index a3c3422402e..a2bb275c06c 100644 --- a/Cabal/src/Distribution/Verbosity.hs +++ b/Cabal/src/Distribution/Verbosity.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- Verbosity for Cabal functions. -- | @@ -96,7 +97,11 @@ import qualified Distribution.Compat.CharParsing as P import Distribution.Utils.Structured import System.IO (Handle, stderr, stdout) import qualified Text.PrettyPrint as PP +#ifdef __MHS__ +import qualified Data.Typeable as Typeable +#else import qualified Type.Reflection as Typeable +#endif -- | Rich verbosity, used for the Cabal library interface. data Verbosity = Verbosity @@ -178,13 +183,17 @@ instance Structured VerbosityHandles where [ ( "VerbosityHandles" , - [ nominalStructure $ Proxy @Handle - , nominalStructure $ Proxy @Handle + [ nominalStructure (Proxy :: Proxy Handle) + , nominalStructure (Proxy :: Proxy Handle) ] ) ] where +#ifdef __MHS__ + tr = Typeable.typeRep (Proxy :: Proxy VerbosityHandles) +#else tr = Typeable.SomeTypeRep $ Typeable.typeRep @VerbosityHandles +#endif instance NFData Verbosity instance Structured Verbosity diff --git a/Cabal/tests/ProcessCaptureTests.hs b/Cabal/tests/ProcessCaptureTests.hs new file mode 100644 index 00000000000..e421586b477 --- /dev/null +++ b/Cabal/tests/ProcessCaptureTests.hs @@ -0,0 +1,370 @@ +{-# LANGUAGE CPP #-} +{-# LANGUAGE ScopedTypeVariables #-} + +-- | Focused subprocess regression suite for the MHS process backend. +-- +-- Compiles and runs under both GHC (reference semantics, via +-- 'System.Process') and MicroHs (via the MHS branch of +-- "Distribution.Compat.Process"), asserting identical observable +-- behaviour: +-- +-- * T0 compiler identity (which backend under test) +-- * T1 delayed writer child, read after reap: complete output +-- * T2 non-ASCII stdin/stdout round-trip preserves locale encoding +-- * T3 @env = Just ...@ replaces the environment (removal, restore) +-- * T3b parent environment unchanged after replaced spawn +-- * T3c empty env + parent-PATH lookup +-- * T3d malformed entries pass through +-- * T4 regular-file 'UseHandle' for stdin and stdout +-- * T4b UTF-8 multibyte round-trip through text- and binary-mode +-- regular-file 'UseHandle's (no double-encoding, no truncation) +-- * T5 exit codes and stdout/stderr separation +-- * T6 public 'CreatePipe' is rejected under MHS, works under GHC +-- * T7 failing output handle surfaces an error (no silent success) +module Main where + +import qualified Distribution.Compat.Process as Process +import Distribution.Compat.Directory (getTemporaryDirectory, removeFile) + +import qualified Data.ByteString as BS +import Control.Exception (SomeException, evaluate, try) +import Control.Monad (when) +import Data.List (isInfixOf) +import System.Environment (getEnvironment, lookupEnv, setEnv, unsetEnv) +import System.Exit (ExitCode (..), exitFailure, exitSuccess) +import System.IO (IOMode (..), hClose, hFlush, hGetContents, hPutStr, openBinaryFile, openFile, openTempFile, stdout) + + +backend :: String +#ifdef __MHS__ +backend = "mhs" +#else +backend = "ghc" +#endif + +type Failure = String + +mark :: String -> IO () +mark s = putStrLn s >> hFlush stdout + +check :: String -> Bool -> IO (Maybe Failure) +check name True = mark ("ok " ++ name) >> return Nothing +check name False = mark ("FAIL " ++ name) >> return (Just name) + +-- T1: child writes after a delay; parent reads only after reap. +tDelayedWriter :: IO (Maybe Failure) +tDelayedWriter = do + (exit, captured) <- + Process.captureProcess + (Process.proc "sh" ["-c", "sleep 1; echo out; echo err >&2"]) + Process.NoInput + out <- readFile (Process.capturedOutPath captured) + err <- readFile (Process.capturedErrPath captured) + _ <- evaluate (length out + length err) + Process.capturedRelease captured + check "T1 delayed writer captured completely" (exit == ExitSuccess && out == "out\n" && err == "err\n") + +-- T2: non-ASCII round-trip through a cat child. +tNonAscii :: IO (Maybe Failure) +tNonAscii = do + locale <- lookupEnv "LC_ALL" + mark ("info locale LC_ALL=" ++ show locale) + let input = "h\xe9llo w\xf6rld \x2713\n" + (exit, captured) <- + Process.captureProcess + (Process.proc "cat" []) + (Process.TextInput input) + out <- readFile (Process.capturedOutPath captured) + _ <- evaluate (length out) + Process.capturedRelease captured + check "T2 non-ASCII round-trip" (exit == ExitSuccess && out == input) + +-- T3: env replacement removes unmentioned variables, then restores. +tEnvRemoval :: IO (Maybe Failure) +tEnvRemoval = do + setEnv "MHS_TEST_PARENT_SENTINEL" "1" + before <- getEnvironment + (exit, captured) <- + Process.captureProcess + (Process.proc "env" []) + { Process.env = Just [("MHS_TEST_ONLY", "present")] + } + Process.NoInput + out <- readFile (Process.capturedOutPath captured) + _ <- evaluate (length out) + Process.capturedRelease captured + after <- getEnvironment + unsetEnv "MHS_TEST_PARENT_SENTINEL" + check + "T3 env replacement and restore" + ( exit == ExitSuccess + && "MHS_TEST_ONLY=present\n" `isInfixOf` out + && not ("MHS_TEST_PARENT_SENTINEL=1" `isInfixOf` out) + && lookup "MHS_TEST_PARENT_SENTINEL" after == Just "1" + && length before == length after + ) + +-- T3b: the parent environment is unchanged by a replaced-env spawn. +tAcquireRollback :: IO (Maybe Failure) +tAcquireRollback = do + before <- getEnvironment + _ <- evaluate (length before) + (exit, captured) <- + Process.captureProcess + (Process.proc "env" []) + { Process.env = Just [] + } + Process.NoInput + out <- readFile (Process.capturedOutPath captured) + _ <- evaluate (length out) + Process.capturedRelease captured + after <- getEnvironment + check "T3b parent env unchanged by replaced spawn" (exit == ExitSuccess && before == after) + +-- T3c: empty env with a relative program name: lookup still uses the +-- parent PATH while the child sees an empty environment. +tEmptyEnvLookup :: IO (Maybe Failure) +tEmptyEnvLookup = do + (exit1, cap1) <- + Process.captureProcess + (Process.proc "echo" ["hi"]) + { Process.env = Just [] + } + Process.NoInput + out1 <- readFile (Process.capturedOutPath cap1) + _ <- evaluate (length out1) + Process.capturedRelease cap1 + (exit2, cap2) <- + Process.captureProcess + (Process.proc "env" []) + { Process.env = Just [] + } + Process.NoInput + out2 <- readFile (Process.capturedOutPath cap2) + _ <- evaluate (length out2) + Process.capturedRelease cap2 + check "T3c empty env + parent-PATH lookup" (exit1 == ExitSuccess && out1 == "hi\n" && exit2 == ExitSuccess && out2 == "") + +-- T3d: malformed entries pass through to the child unchanged (matching +-- System.Process.createProcess, which does not validate), rather +-- than being rejected or silently rewritten. +tMalformedEnv :: IO (Maybe Failure) +tMalformedEnv = do + (exit, captured) <- Process.captureProcess + (Process.proc "env" []) + { Process.env = Just [("BAD=KEY", "v"), ("", "w")] + } + Process.NoInput + out <- readFile (Process.capturedOutPath captured) + _ <- evaluate (length out) + Process.capturedRelease captured + check "T3d malformed entries pass through" (exit == ExitSuccess && "BAD=KEY=v\n" `isInfixOf` out && "=w\n" `isInfixOf` out) + +-- T4: regular files as UseHandle stdin and stdout. +tFileHandles :: IO (Maybe Failure) +tFileHandles = do + tmpDir <- getTemporaryDirectory + (inTmp, inH) <- openTempFile tmpDir "t4-in" + hPutStr inH "via-file\n" + hClose inH + outRes <- try $ do + inH2 <- openFile inTmp ReadMode + (logTmp, logH) <- openTempFile tmpDir "t4-log" + (_, _, _, ph) <- + Process.createProcess + (Process.proc "cat" []) + { Process.std_in = Process.UseHandle inH2 + , Process.std_out = Process.UseHandle logH + , Process.std_err = Process.Inherit + } + hClose inH2 + exit <- Process.waitForProcess ph + Process.cleanupProcess (Nothing, Nothing, Nothing, ph) + hClose logH + content <- readFile logTmp + _ <- evaluate (length content) + removeFile logTmp + return (exit, content) + removeFile inTmp + case outRes of + Left (e :: SomeException) -> do + putStrLn ("info T4 raised: " ++ show e) + check "T4 file handles (no exception)" False + Right (exit, content) -> + check "T4 file handles round-trip" (exit == ExitSuccess && content == "via-file\n") + +-- T4b: UTF-8 multibyte content round-trips byte-identically through +-- text-mode and binary-mode regular-file 'UseHandle's, for both the +-- output copy-back and the stdin staging paths. The bytes are +-- spelled out explicitly so the test does not depend on the locale. +-- ("caf\xc3\xa9 \xe2\x80\x9cquote\xe2\x80\x9d \xe2\x82\xac\n", +-- i.e. @"caf\xe9 \x201cquote\x201d \x20ac\n"@.) +tUtf8FileHandles :: IO (Maybe Failure) +tUtf8FileHandles = do + tmpDir <- getTemporaryDirectory + let want = + BS.pack + [ 0x63, 0x61, 0x66, 0xC3, 0xA9, 0x20 + , 0xE2, 0x80, 0x9C, 0x71, 0x75, 0x6F, 0x74, 0x65, 0xE2, 0x80, 0x9D + , 0x20, 0xE2, 0x82, 0xAC, 0x0A + ] :: BS.ByteString + (inTmp, inH0) <- openTempFile tmpDir "t4b-in" + hClose inH0 + BS.writeFile inTmp want + outRes <- try $ do + -- Text-mode destination log (the build-log case). + (textTmp, textH0) <- openTempFile tmpDir "t4b-log-text" + hClose textH0 + logH <- openFile textTmp WriteMode + (_, _, _, ph) <- + Process.createProcess + (Process.proc "cat" [inTmp]) + { Process.std_out = Process.UseHandle logH + , Process.std_err = Process.Inherit + } + exit1 <- Process.waitForProcess ph + Process.cleanupProcess (Nothing, Nothing, Nothing, ph) + hClose logH + gotText <- BS.readFile textTmp + -- Binary-mode destination log. + (binTmp, binH0) <- openTempFile tmpDir "t4b-log-bin" + hClose binH0 + logB <- openBinaryFile binTmp WriteMode + (_, _, _, ph2) <- + Process.createProcess + (Process.proc "cat" [inTmp]) + { Process.std_out = Process.UseHandle logB + , Process.std_err = Process.Inherit + } + exit2 <- Process.waitForProcess ph2 + Process.cleanupProcess (Nothing, Nothing, Nothing, ph2) + hClose logB + gotBin <- BS.readFile binTmp + -- Text-mode stdin staging: the child echoes staged input. + (echoTmp, echoH0) <- openTempFile tmpDir "t4b-echo" + hClose echoH0 + inH <- openFile inTmp ReadMode + outH <- openBinaryFile echoTmp WriteMode + (_, _, _, ph3) <- + Process.createProcess + (Process.proc "cat" []) + { Process.std_in = Process.UseHandle inH + , Process.std_out = Process.UseHandle outH + , Process.std_err = Process.Inherit + } + hClose inH + exit3 <- Process.waitForProcess ph3 + Process.cleanupProcess (Nothing, Nothing, Nothing, ph3) + hClose outH + gotEcho <- BS.readFile echoTmp + removeFile textTmp + removeFile binTmp + removeFile echoTmp + return (exit1, gotText, exit2, gotBin, exit3, gotEcho) + removeFile inTmp + case outRes of + Left (e :: SomeException) -> do + putStrLn ("info T4b raised: " ++ show e) + check "T4b UTF-8 file handles (no exception)" False + Right (exit1, gotText, exit2, gotBin, exit3, gotEcho) -> + check + "T4b UTF-8 file handles round-trip" + ( exit1 == ExitSuccess && gotText == want + && exit2 == ExitSuccess && gotBin == want + && exit3 == ExitSuccess && gotEcho == want + ) + +-- T5: exit codes and stream separation. +tExitStreams :: IO (Maybe Failure) +tExitStreams = do + (exit, out, err) <- + Process.readCreateProcessWithExitCode + (Process.proc "sh" ["-c", "echo out; echo err >&2; exit 3"]) + "" + check "T5 exit code and streams" (exit == ExitFailure 3 && out == "out\n" && err == "err\n") + +-- T6: public CreatePipe is rejected under MHS, fine under GHC. +tCreatePipe :: IO (Maybe Failure) +#ifdef __MHS__ +tCreatePipe = do + res <- + try + ( Process.createProcess + (Process.proc "true" []) + { Process.std_out = Process.CreatePipe + } + >> return () + ) + :: IO (Either SomeException ()) + case res of + Left (_ :: SomeException) -> check "T6 CreatePipe explicitly rejected" True + Right _ -> check "T6 CreatePipe explicitly rejected" False +#else +tCreatePipe = do + res <- + try + ( do + (_, Just hOut, _, ph) <- + Process.createProcess + (Process.proc "echo" ["hi"]) + { Process.std_out = Process.CreatePipe + } + out <- hGetContents hOut + _ <- evaluate (length out) + exit <- Process.waitForProcess ph + Process.cleanupProcess (Nothing, Just hOut, Nothing, ph) + return (exit, out) + ) + :: IO (Either SomeException (ExitCode, String)) + case res of + Right (ExitSuccess, "hi\n") -> check "T6 CreatePipe works (GHC)" True + _ -> check "T6 CreatePipe works (GHC)" False +#endif + +-- T7: a failing output handle must surface, never silently succeed. +tFailingHandle :: IO (Maybe Failure) +tFailingHandle = do + tmpDir <- getTemporaryDirectory + (tmp, h) <- openTempFile tmpDir "t7-closed" + hClose h + res <- + try + ( do + (_, _, _, ph) <- + Process.createProcess + (Process.proc "echo" ["hi"]) + { Process.std_out = Process.UseHandle h + } + exit <- Process.waitForProcess ph + Process.cleanupProcess (Nothing, Nothing, Nothing, ph) + return exit + ) + :: IO (Either SomeException ExitCode) + removeFile tmp + case res of + Left (_ :: SomeException) -> check "T7 failing handle raises" True + Right _ -> check "T7 failing handle raises" False + +main :: IO () +main = do + mark ("backend=" ++ backend) + results <- + sequence + [ tDelayedWriter + , tNonAscii + , tEnvRemoval + , tAcquireRollback + , tEmptyEnvLookup + , tMalformedEnv + , tFileHandles + , tUtf8FileHandles + , tExitStreams + , tCreatePipe + , tFailingHandle + ] + let failures = [f | Just f <- results] + when (not (null failures)) $ do + mark ("failures: " ++ show failures) + exitFailure + mark "all green" + exitSuccess diff --git a/Makefile b/Makefile index 2137d35399e..e2d1b78b8b0 100644 --- a/Makefile +++ b/Makefile @@ -20,6 +20,12 @@ lib: ## Builds the Cabal libraries. exe: ## Builds the cabal-install executables. $(CABALBUILD) cabal-install:exes +# minimal-toolchain (mhs) build, see cabal.mhs.project. Requires the +# pregenerated Distribution.Fields.Lexer (alex is needed to regenerate it). +.PHONY: mhs-build +mhs-build: ## Build with the minimal (mhs/stable-haskell) toolchain profile. + $(CABALBUILD) --project-file=cabal.mhs.project all + .PHONY: init init: ## Set up git hooks and ignored revisions. @git config core.hooksPath .githooks diff --git a/cabal-dev-scripts/src/GenSPDX.hs b/cabal-dev-scripts/src/GenSPDX.hs index e72dc508562..7147940a65d 100644 --- a/cabal-dev-scripts/src/GenSPDX.hs +++ b/cabal-dev-scripts/src/GenSPDX.hs @@ -71,6 +71,7 @@ generate' -> IO String generate' lss template = template $ Input { inputLicenseIds = licenseIds + , inputLicenseIdNames = licenseIdNames , inputLicenses = licenseValues , inputLicenseList_all = mkLicenseList (== allVers) , inputLicenseList_perv = tabulate $ \ver -> mkLicenseList @@ -101,6 +102,21 @@ generate' lss template = template $ Input | otherwise = foldMap (\v -> ", " <> prettyVer v) vers in pfx <> c <> " -- ^ @" <> licenseId l <> "@, " <> licenseName l <> versInfo + -- Constructor names for the hand-written Data 'toConstr' table, + -- in declaration order (8 per line, matching the checked-in files). + licenseIdNames :: Text + licenseIdNames = + let grps = groupsOf 8 [ c | (c, _, _) <- constructorNames ] + render i grp = + (if i == 0 then " [ " else " , ") + <> T.intercalate ", " (map (\c -> "\"" <> c <> "\"") grp) + <> (if i == length grps - 1 then " ]" else "") + in T.intercalate "\n" $ zipWith render [0 :: Int ..] grps + where + groupsOf :: Int -> [a] -> [[a]] + groupsOf _ [] = [] + groupsOf n xs = take n xs : groupsOf n (drop n xs) + mkLicenseList :: (Set.Set SPDXLicenseListVersion -> Bool) -> Text mkLicenseList p = mkList [ n | (n, _, vers) <- constructorNames, p vers ] diff --git a/cabal-dev-scripts/src/GenSPDXExc.hs b/cabal-dev-scripts/src/GenSPDXExc.hs index f74abb043b2..1e68a078b73 100644 --- a/cabal-dev-scripts/src/GenSPDXExc.hs +++ b/cabal-dev-scripts/src/GenSPDXExc.hs @@ -69,6 +69,7 @@ generate' -> IO String generate' lss template = template $ Input { inputLicenseIds = licenseIds + , inputLicenseIdNames = licenseIdNames , inputLicenses = licenseValues , inputLicenseList_all = mkLicenseList (== allVers) , inputLicenseList_perv = tabulate $ \ver -> mkLicenseList @@ -99,6 +100,21 @@ generate' lss template = template $ Input | otherwise = foldMap (\v -> ", " <> prettyVer v) vers in pfx <> c <> " -- ^ @" <> licenseId l <> "@, " <> licenseName l <> versInfo + -- Constructor names for the hand-written Data 'toConstr' table, + -- in declaration order (8 per line, matching the checked-in files). + licenseIdNames :: Text + licenseIdNames = + let grps = groupsOf 8 [ c | (c, _, _) <- constructorNames ] + render i grp = + (if i == 0 then " [ " else " , ") + <> T.intercalate ", " (map (\c -> "\"" <> c <> "\"") grp) + <> (if i == length grps - 1 then " ]" else "") + in T.intercalate "\n" $ zipWith render [0 :: Int ..] grps + where + groupsOf :: Int -> [a] -> [[a]] + groupsOf _ [] = [] + groupsOf n xs = take n xs : groupsOf n (drop n xs) + mkLicenseList :: (Set.Set SPDXLicenseListVersion -> Bool) -> Text mkLicenseList p = mkList [ n | (n, _, vers) <- constructorNames, p vers ] diff --git a/cabal-dev-scripts/src/GenUtils.hs b/cabal-dev-scripts/src/GenUtils.hs index 68667b8059b..cf32e47e7ad 100644 --- a/cabal-dev-scripts/src/GenUtils.hs +++ b/cabal-dev-scripts/src/GenUtils.hs @@ -188,6 +188,7 @@ mkList (x:xs) = data Input = Input { inputLicenseIds :: Text + , inputLicenseIdNames :: Text , inputLicenses :: [InputLicense] , inputLicenseList_all :: Text , inputLicenseList_perv :: PerV Text diff --git a/cabal-install-solver/cabal-install-solver.cabal b/cabal-install-solver/cabal-install-solver.cabal index 188224a998e..97caf91a28f 100644 --- a/cabal-install-solver/cabal-install-solver.cabal +++ b/cabal-install-solver/cabal-install-solver.cabal @@ -32,6 +32,11 @@ flag debug-tracetree default: False manual: True +flag mhs + description: MicroHs build (uses -mhs package variants for array/binary/pretty/uri) + default: False + manual: True + library default-language: GHC2021 hs-source-dirs: src @@ -100,21 +105,33 @@ library Distribution.Solver.Types.Variable build-depends: - , array >=0.4 && <0.6 , base >=4.18 && <4.24 , bytestring >=0.10.6.0 && <0.13 , Cabal ^>=3.19 , Cabal-syntax ^>=3.19 , containers >=0.5.6.2 && <0.9 - , edit-distance ^>= 0.2.2 , directory >= 1.3.8.5 && < 1.4 , filepath >= 1.4.301 && < 1.6 , mtl >=2.0 && <2.4 - , network-uri >= 2.6.0.2 && < 2.7 - , pretty ^>=1.1 , transformers >=0.4.2.0 && <0.7 , text (>= 1.2.3.0 && < 1.3) || (>= 2.0 && < 2.2) + if flag(mhs) + -- MicroHs build: use -mhs package variants. Binary instances come via + -- Distribution.Compat.Binary in Cabal-syntax (which already swaps to + -- binary-mhs); list binary-mhs here for completeness. + build-depends: + , array-mhs >=0.5.8 && <0.6 + , binary-mhs >=0.8.1 && <0.9 + , pretty-mhs >=1.1.3.6 && <1.2 + , uri-mhs >=0.1 && <0.2 + else + build-depends: + , array >=0.4 && <0.6 + , edit-distance ^>= 0.2.2 + , network-uri >= 2.6.0.2 && < 2.7 + , pretty ^>=1.1 + if flag(debug-expensive-assertions) cpp-options: -DDEBUG_EXPENSIVE_ASSERTIONS diff --git a/cabal-install-solver/src/Distribution/Solver/Modular/Cycles.hs b/cabal-install-solver/src/Distribution/Solver/Modular/Cycles.hs index 11d5f8447f0..362fd3a9f8b 100644 --- a/cabal-install-solver/src/Distribution/Solver/Modular/Cycles.hs +++ b/cabal-install-solver/src/Distribution/Solver/Modular/Cycles.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} module Distribution.Solver.Modular.Cycles ( detectCyclesPhase ) where @@ -71,7 +70,7 @@ findCycles pkg rdm = -- strongly connected component. -- if hasCycle - then let scc :: G.Graph RevDepMapNode + then let scc :: G.Graph QPN RevDepMapNode scc = case G.cycles $ revDepMapToGraph rdm of [] -> findCyclesError "cannot find a strongly connected component" c : _ -> G.fromDistinctList c @@ -110,11 +109,10 @@ findCycles pkg rdm = data RevDepMapNode = RevDepMapNode QPN [(Component, QPN)] -instance G.IsNode RevDepMapNode where - type Key RevDepMapNode = QPN +instance G.IsNode QPN RevDepMapNode where nodeKey (RevDepMapNode qpn _) = qpn nodeNeighbors (RevDepMapNode _ ns) = ordNub $ map snd ns -revDepMapToGraph :: RevDepMap -> G.Graph RevDepMapNode +revDepMapToGraph :: RevDepMap -> G.Graph QPN RevDepMapNode revDepMapToGraph rdm = G.fromDistinctList [RevDepMapNode qpn ns | (qpn, ns) <- M.toList rdm] diff --git a/cabal-install-solver/src/Distribution/Solver/Modular/Dependency.hs b/cabal-install-solver/src/Distribution/Solver/Modular/Dependency.hs index 5765b177e51..292be054ab0 100644 --- a/cabal-install-solver/src/Distribution/Solver/Modular/Dependency.hs +++ b/cabal-install-solver/src/Distribution/Solver/Modular/Dependency.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} module Distribution.Solver.Modular.Dependency ( -- * Variables @@ -142,7 +143,18 @@ data ExposedComponent = -- everything needed for creating ConflictSets or describing conflicts in solver -- log messages. data DependencyReason qpn = DependencyReason qpn (Map Flag FlagValue) (S.Set Stanza) +#ifndef __MHS__ deriving (Functor, Eq, Show) +#else + deriving (Eq, Show) +#endif + +#ifdef __MHS__ +-- MicroHs's derived Functor requires Functor for concrete Map/Set fields; +-- spell out the instance (map over the package name only). +instance Functor DependencyReason where + fmap f (DependencyReason qpn flags stanzas) = DependencyReason (f qpn) flags stanzas +#endif -- | Print the reason that a dependency was introduced. showDependencyReason :: DependencyReason QPN -> String diff --git a/cabal-install-solver/src/Distribution/Solver/Modular/MessageUtils.hs b/cabal-install-solver/src/Distribution/Solver/Modular/MessageUtils.hs index 684216579e8..62e3c489fe9 100644 --- a/cabal-install-solver/src/Distribution/Solver/Modular/MessageUtils.hs +++ b/cabal-install-solver/src/Distribution/Solver/Modular/MessageUtils.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- | Utility functions providing extra context to cabal error messages module Distribution.Solver.Modular.MessageUtils ( @@ -14,7 +15,12 @@ import Data.Ord (comparing) import Distribution.Pretty (prettyShow) -- from Cabal import Language.Haskell.Extension ( Extension(..), Language(..), knownLanguages, knownExtensions ) +#ifdef __MHS__ +-- MicroHs has no edit-distance package; provide a small local +-- Levenshtein implementation preserving solver behavior. +#else import Text.EditDistance ( defaultEditCosts, levenshteinDistance ) +#endif showUnsupportedExtension :: Extension -> String showUnsupportedExtension (UnknownExtension extStr) = formatMessage cutoffRange "extension" extStr (mostSimilarElement extStr allKnownExtensions) @@ -31,8 +37,33 @@ allKnownExtensions = enabledExtensions ++ disabledExtensions disabledExtensions = map (prettyShow . DisableExtension) knownExtensions -- Measure the Levenshtein distance between two strings +#ifdef __MHS__ +defaultEditCosts :: () +defaultEditCosts = () + +levenshteinDistance :: () -> String -> String -> Int +levenshteinDistance _ = lev + where + lev s t = table !! ls !! lt + where + ls = length s + lt = length t + table = [[cell i j | j <- [0 .. lt]] | i <- [0 .. ls]] + cell 0 j = j + cell i 0 = i + cell i j = + minimum + [ table !! (i - 1) !! j + 1 + , table !! i !! (j - 1) + 1 + , table !! (i - 1) !! (j - 1) + if s !! (i - 1) == t !! (j - 1) then 0 else 1 + ] + +distance :: String -> String -> Int +distance = levenshteinDistance defaultEditCosts +#else distance :: String -> String -> Int distance = levenshteinDistance defaultEditCosts +#endif -- Given an `unknownElement` and a list of `elements` return the element -- from the list with the closest Levenshtein distance to the `unknownElement` diff --git a/cabal-install-solver/src/Distribution/Solver/Modular/Validate.hs b/cabal-install-solver/src/Distribution/Solver/Modular/Validate.hs index a88083a3994..52361a6c959 100644 --- a/cabal-install-solver/src/Distribution/Solver/Modular/Validate.hs +++ b/cabal-install-solver/src/Distribution/Solver/Modular/Validate.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} module Distribution.Solver.Modular.Validate (validateTree) where -- Validation of the tree. @@ -8,7 +9,9 @@ module Distribution.Solver.Modular.Validate (validateTree) where import Control.Monad (foldM, mzero, liftM2) import Control.Monad.Reader (MonadReader, Reader, runReader, local, asks) +#ifndef __MHS__ import Data.Either (lefts) +#endif import Data.Function (on) import qualified Data.List as L @@ -35,6 +38,11 @@ import Distribution.Solver.Types.Machine (Machine, PerMachine, onMachine) import Distribution.Types.LibraryName import Distribution.Types.PkgconfigVersionRange +#ifdef __MHS__ +lefts :: [Either a b] -> [a] +lefts xs = [x | Left x <- xs] +#endif + -- In practice, most constraints are implication constraints (IF we have made -- a number of choices, THEN we also have to ensure that). We call constraints -- that for which the preconditions are fulfilled ACTIVE. We maintain a set diff --git a/cabal-install-solver/src/Distribution/Solver/Modular/WeightedPSQ.hs b/cabal-install-solver/src/Distribution/Solver/Modular/WeightedPSQ.hs index f07d0321c45..122f6f6ce4b 100644 --- a/cabal-install-solver/src/Distribution/Solver/Modular/WeightedPSQ.hs +++ b/cabal-install-solver/src/Distribution/Solver/Modular/WeightedPSQ.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} module Distribution.Solver.Modular.WeightedPSQ ( WeightedPSQ , fromList @@ -78,7 +79,12 @@ traverseWithKey -> WeightedPSQ w k v -> f (WeightedPSQ w k v') traverseWithKey f (WeightedPSQ q) = WeightedPSQ <$> +#ifdef __MHS__ + -- MicroHs does not parse tuple sections like (w,k,); spell out the lambda. + traverse (\(w,k,v) -> (\x -> (w, k, x)) <$> f k v) q +#else traverse (\(w,k,v) -> (w,k,) <$> f k v) q +#endif -- | /O((N + M) log (N + M))/. Combine two @WeightedPSQ@s, preserving all -- elements. Elements from the first @WeightedPSQ@ come before elements in the diff --git a/cabal-install-solver/src/Distribution/Solver/Types/ComponentDeps.hs b/cabal-install-solver/src/Distribution/Solver/Types/ComponentDeps.hs index dc40a4594e1..613c61d331e 100644 --- a/cabal-install-solver/src/Distribution/Solver/Types/ComponentDeps.hs +++ b/cabal-install-solver/src/Distribution/Solver/Types/ComponentDeps.hs @@ -38,6 +38,7 @@ module Distribution.Solver.Types.ComponentDeps ( import Prelude () import Distribution.Types.UnqualComponentName +import Data.Foldable (Foldable) import Distribution.Solver.Compat.Prelude hiding (empty,toList,zip) import qualified Data.Map as Map diff --git a/cabal-install-solver/src/Distribution/Solver/Types/Machine.hs b/cabal-install-solver/src/Distribution/Solver/Types/Machine.hs index 86bbcc95880..45349772459 100644 --- a/cabal-install-solver/src/Distribution/Solver/Types/Machine.hs +++ b/cabal-install-solver/src/Distribution/Solver/Types/Machine.hs @@ -14,6 +14,7 @@ module Distribution.Solver.Types.Machine , isCross ) where +import Data.Foldable (Foldable) import Distribution.Compat.Prelude -- | The machine whose toolchain a package is compiled with. diff --git a/cabal-install-solver/src/Distribution/Solver/Types/PkgConfigDb.hs b/cabal-install-solver/src/Distribution/Solver/Types/PkgConfigDb.hs index 7e0c8526384..d412e80c5e8 100644 --- a/cabal-install-solver/src/Distribution/Solver/Types/PkgConfigDb.hs +++ b/cabal-install-solver/src/Distribution/Solver/Types/PkgConfigDb.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- | -- Module : Distribution.Solver.Types.PkgConfigDb -- Copyright : (c) Iñaki García Etxebarria 2016 @@ -20,7 +21,9 @@ import Distribution.Solver.Compat.Prelude import Prelude () import Control.Exception (handle) +#ifndef __MHS__ import Control.Monad (mapM) +#endif import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LBS import qualified Data.Map as M @@ -39,6 +42,9 @@ import Distribution.Simple.Program.Run import Distribution.Simple.Utils (info) import Distribution.Types.PkgconfigVersion import Distribution.Types.PkgconfigVersionRange +#ifdef __MHS__ +import Distribution.Utils.Generic (validateUTF8) +#endif import Distribution.Verbosity (Verbosity) -- | The list of packages installed in the system visible to @@ -86,9 +92,15 @@ readPkgConfigDb verbosity progdb = handle ioErrorHandler $ do -- in multi-byte UTF-8 sequences. . map ((\bsname -> let sbsname = LBS.toStrict bsname +#ifdef __MHS__ + in case validateUTF8 sbsname of + Just _ -> Left (T.unpack (decodeUtf8LenientCompat sbsname)) + Nothing -> Right (T.unpack (decodeUtf8LenientCompat sbsname))) . LBS.takeWhile (not . isAsciiSpace)) +#else in case T.decodeUtf8' sbsname of Left _ -> Left (T.unpack (decodeUtf8LenientCompat sbsname)) Right name -> Right (T.unpack name)) . LBS.takeWhile (not . isAsciiSpace)) +#endif $ pkgList unless (null failedPkgNames) $ info verbosity ("Some pkg-config packages have names containing invalid unicode: " ++ intercalate ", " failedPkgNames) diff --git a/cabal-install-solver/src/Distribution/Solver/Types/ProjectConfigPath.hs b/cabal-install-solver/src/Distribution/Solver/Types/ProjectConfigPath.hs index ec09af76935..18c99274b27 100644 --- a/cabal-install-solver/src/Distribution/Solver/Types/ProjectConfigPath.hs +++ b/cabal-install-solver/src/Distribution/Solver/Types/ProjectConfigPath.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE ViewPatterns #-} module Distribution.Solver.Types.ProjectConfigPath @@ -27,12 +28,13 @@ module Distribution.Solver.Types.ProjectConfigPath import Distribution.Solver.Compat.Prelude hiding (toList, (<>)) import qualified Distribution.Solver.Compat.Prelude as P ((<>)) -import Prelude (sequence) +import Prelude () +import qualified Data.Traversable as T import Data.Coerce (coerce) import Data.List.NonEmpty ((<|)) import Network.URI (parseURI, parseAbsoluteURI) -import System.Directory +import Distribution.Compat.Directory import System.FilePath hiding (splitPath) import qualified System.FilePath as FP (splitPath) import qualified System.FilePath.Posix as Posix @@ -105,7 +107,13 @@ compareLexicographically (ProjectConfigPath as) (ProjectConfigPath bs) = (_, _ :| []) -> GT (a :| aImporters, b :| bImporters) -> case (parseAbsoluteURI a, parseAbsoluteURI b) of - (Just ua, Just ub) -> compare ua ub P.<> compare aImporters bImporters + (Just ua, Just ub) -> +#ifdef __MHS__ + -- MicroHs URI has no Ord; compare renderings instead. + compare (show ua) (show ub) P.<> compare aImporters bImporters +#else + compare ua ub P.<> compare aImporters bImporters +#endif (Just _, Nothing) -> GT (Nothing, Just _) -> LT (Nothing, Nothing) -> compare (splitPath a) (splitPath b) P.<> compare aImporters bImporters @@ -132,7 +140,13 @@ compareSegmentally pa@(ProjectConfigPath as) pb@(ProjectConfigPath bs) = (_, _ :| []) -> GT (a :| _, b :| _) -> case (parseAbsoluteURI a, parseAbsoluteURI b) of - (Just ua, Just ub) -> compare ua ub P.<> compare aImporters bImporters + (Just ua, Just ub) -> +#ifdef __MHS__ + -- MicroHs URI has no Ord; compare renderings instead. + compare (show ua) (show ub) P.<> compare aImporters bImporters +#else + compare ua ub P.<> compare aImporters bImporters +#endif (Just _, Nothing) -> GT (Nothing, Just _) -> LT (Nothing, Nothing) -> @@ -336,7 +350,7 @@ makeRelativeConfigPath dir (ProjectConfigPath p) = -- "https://www.stackage.org/nightly-2024-12-05/cabal.config\n imported by: cabal.project" canonicalizeConfigPath :: FilePath -> ProjectConfigPath -> IO ProjectConfigPath canonicalizeConfigPath d (ProjectConfigPath p) = do - xs <- sequence $ NE.scanr (\importee@(trim -> trimImportee) -> (>>= \importer@(trim -> trimImporter) -> + xs <- T.sequence $ NE.scanr (\importee@(trim -> trimImportee) -> (>>= \importer@(trim -> trimImporter) -> if isURI trimImportee || isURI trimImporter then pure trimImportee else canonicalizePath $ d takeDirectory importer importee)) diff --git a/cabal-install-solver/src/Distribution/Solver/Types/ResolverPackage.hs b/cabal-install-solver/src/Distribution/Solver/Types/ResolverPackage.hs index 1bfc8620e6e..8f55ded9cbf 100644 --- a/cabal-install-solver/src/Distribution/Solver/Types/ResolverPackage.hs +++ b/cabal-install-solver/src/Distribution/Solver/Types/ResolverPackage.hs @@ -1,4 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} module Distribution.Solver.Types.ResolverPackage ( ResolverPackage(..) , solverId @@ -51,8 +50,7 @@ resolverPackageExeDeps :: ResolverPackage loc -> CD.ComponentDeps [SolverId] resolverPackageExeDeps (PreExisting ipkg) = instSolverPkgExeDeps ipkg resolverPackageExeDeps (Configured spkg) = solverPkgExeDeps spkg -instance IsNode (ResolverPackage loc) where - type Key (ResolverPackage loc) = SolverId +instance IsNode SolverId (ResolverPackage loc) where nodeKey = solverId -- Use dependencies for ALL components nodeNeighbors pkg = diff --git a/cabal-install/cabal-install.cabal b/cabal-install/cabal-install.cabal index 9186cdb271f..a6d9f23a780 100644 --- a/cabal-install/cabal-install.cabal +++ b/cabal-install/cabal-install.cabal @@ -18,6 +18,8 @@ Category: Distribution Build-type: Simple Extra-Source-Files: bash-completion/cabal + cbits/mhs_sha256.c + cbits/mhs_sha256.h extra-doc-files: README.md ChangeLog.md @@ -44,6 +46,11 @@ flag legacy-comparison default: False manual: True +flag mhs + description: MicroHs build (uses -mhs package variants for array/binary/pretty/random/network-uri) + default: False + manual: True + common warnings ghc-options: -Wall @@ -123,6 +130,7 @@ library Distribution.Client.CmdTarget Distribution.Client.CmdTest Distribution.Client.CmdUpdate + Distribution.Client.Compat.Base16 Distribution.Client.CmdGenBounds Distribution.Client.Compat.Orphans Distribution.Client.Compat.Prelude @@ -243,38 +251,54 @@ library build-depends: , async >= 2.0 && < 2.3 - , array >= 0.4 && < 0.6 - , base16-bytestring >= 1.0 && < 1.1 - , binary >= 0.7.3 && < 0.9 , bytestring >= 0.10.6.0 && < 0.13 , containers >= 0.5.6.2 && < 0.9 - , cryptohash-sha256 >= 0.11 && < 0.12 , directory >= 1.3.8.5 && < 1.4 - , echo >= 0.1.3 && < 0.2 - , edit-distance >= 0.2.2 && < 0.3 , exceptions >= 0.10.4 && < 0.11 , filepath >= 1.4.301 && < 1.6 , hooks-exe ^>= 3.19 - , HTTP >= 4000.1.5 && < 4000.6 , mtl >= 2.0 && < 2.4 - , network-uri >= 2.6.2.0 && < 2.7 - , pretty >= 1.1 && < 1.2 , process >= 1.6.29.0 && < 1.7 - , random >= 1.2 && < 1.4 , stm >= 2.0 && < 2.6 - , tar >= 0.5.0.3 && < 0.8 , time >= 1.5.0.1 && < 1.17 - , zlib >= 0.6 && < 0.8 - , hackage-security >= 0.6.2.0 && < 0.7 , text >= 1.2.3 && < 1.3 || >= 2.0 && < 2.2 , parsec >= 3.1.13.0 && < 3.2 - , open-browser >= 0.2.1.0 && < 0.6 - , regex-base >= 0.94.0.0 && <0.95 - , regex-posix >= 0.96.0.0 && <0.97 - , safe-exceptions >= 0.1.7.0 && < 0.2 - , semaphore-compat >= 2.0.1 && < 2.1 - if flag(native-dns) + if flag(mhs) + -- MicroHs build: -mhs package variants (same APIs, ported to mhs). + build-depends: + , array-mhs >= 0.5.8 && < 0.6 + , binary-mhs >= 0.8.1 && < 0.9 + , pretty-mhs >= 1.1.3.6 && < 1.2 + , random-mhs >= 1.2 && < 1.4 + , uri-mhs >= 0.1 && < 0.2 + -- SHA256 helper (CommonCrypto on Apple, OpenSSL elsewhere). + c-sources: cbits/mhs_sha256.c + include-dirs: cbits + if !os(darwin) + extra-libraries: crypto + else + build-depends: + , array >= 0.4 && < 0.6 + , base16-bytestring >= 1.0 && < 1.1 + , binary >= 0.7.3 && < 0.9 + , cryptohash-sha256 >= 0.11 && < 0.12 + , echo >= 0.1.3 && < 0.2 + , edit-distance >= 0.2.2 && < 0.3 + , HTTP >= 4000.1.5 && < 4000.6 + , network-uri >= 2.6.2.0 && < 2.7 + , pretty >= 1.1 && < 1.2 + , random >= 1.2 && < 1.4 + , tar >= 0.5.0.3 && < 0.8 + , zlib >= 0.6 && < 0.8 + , hackage-security >= 0.6.2.0 && < 0.7 + , open-browser >= 0.2.1.0 && < 0.6 + , regex-base >= 0.94.0.0 && <0.95 + , regex-posix >= 0.96.0.0 && <0.97 + , safe-exceptions >= 0.1.7.0 && < 0.2 + , semaphore-compat >= 2.0.1 && < 2.1 + + if flag(native-dns) && !flag(mhs) if os(windows) build-depends: windns >= 0.1.0 && < 0.2 else @@ -284,8 +308,9 @@ library build-depends: , Win32 >= 2.8 && < 3 else - build-depends: - , unix >= 2.8.6.0 && < 2.9 + if !flag(mhs) + build-depends: + , unix >= 2.8.6.0 && < 2.9 if flag(git-rev) build-depends: githash ^>= 0.1.7.0 diff --git a/cabal-install/cbits/mhs_sha256.c b/cabal-install/cbits/mhs_sha256.c new file mode 100644 index 00000000000..0fdb79bcb9f --- /dev/null +++ b/cabal-install/cbits/mhs_sha256.c @@ -0,0 +1,27 @@ +/* SHA256 one-shot helper for the MicroHs (MHS) build of cabal-install. + * + * See @mhs_sha256.h@ for the linkage contract. + */ + +#include "mhs_sha256.h" + +#if defined(__APPLE__) +#include + +unsigned char *cabal_sha256(const void *data, unsigned long len, + unsigned char *md) +{ + return CC_SHA256(data, (CC_LONG) len, md); +} + +#else + +#include + +unsigned char *cabal_sha256(const void *data, unsigned long len, + unsigned char *md) +{ + return SHA256((const unsigned char *) data, (size_t) len, md); +} + +#endif diff --git a/cabal-install/cbits/mhs_sha256.h b/cabal-install/cbits/mhs_sha256.h new file mode 100644 index 00000000000..89466bf1864 --- /dev/null +++ b/cabal-install/cbits/mhs_sha256.h @@ -0,0 +1,21 @@ +/* SHA256 one-shot helper for the MicroHs (MHS) build of cabal-install. + * + * MicroHs cannot use the @cryptohash-sha256@ package, so + * 'Distribution.Client.HashValue' calls 'cabal_sha256' through FFI + * (see the @foreign import ccall@ there, which must be + * header-qualified with this file, e.g. + * @foreign import ccall "mhs_sha256.h cabal_sha256" ...@). + * + * On Apple platforms the system SDK provides CommonCrypto's + * @CC_SHA256@ in @libSystem@, so no external library is needed at + * link time. Elsewhere (Linux and other POSIX systems) OpenSSL's + * @SHA256()@ from @@ is used, which needs @-lcrypto@ + * at link time. + */ +#ifndef CABAL_MHS_SHA256_H +#define CABAL_MHS_SHA256_H + +unsigned char *cabal_sha256(const void *data, unsigned long len, + unsigned char *md); + +#endif /* CABAL_MHS_SHA256_H */ diff --git a/cabal-install/parser-tests/Tests/ParserTests.hs b/cabal-install/parser-tests/Tests/ParserTests.hs index 96cf5d0aef8..f869529e58b 100644 --- a/cabal-install/parser-tests/Tests/ParserTests.hs +++ b/cabal-install/parser-tests/Tests/ParserTests.hs @@ -62,7 +62,7 @@ import Distribution.Utils.NubList import Distribution.Verbosity import GHC.Stack (HasCallStack) import Network.URI (parseURI) -import System.Directory (canonicalizePath, doesFileExist) +import Distribution.Compat.Directory (canonicalizePath, doesFileExist) import System.FilePath (()) import Prelude () diff --git a/cabal-install/src/Distribution/Client/BuildReports/Anonymous.hs b/cabal-install/src/Distribution/Client/BuildReports/Anonymous.hs index 9291790c28e..9fe49e4c6cf 100644 --- a/cabal-install/src/Distribution/Client/BuildReports/Anonymous.hs +++ b/cabal-install/src/Distribution/Client/BuildReports/Anonymous.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE ApplicativeDo #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} @@ -28,7 +29,9 @@ module Distribution.Client.BuildReports.Anonymous -- showList, ) where +#ifndef __MHS__ import Data.Either (rights) +#endif import Distribution.Client.Compat.Prelude import Prelude () diff --git a/cabal-install/src/Distribution/Client/BuildReports/Storage.hs b/cabal-install/src/Distribution/Client/BuildReports/Storage.hs index 7bb56affa42..d5ccec41abb 100644 --- a/cabal-install/src/Distribution/Client/BuildReports/Storage.hs +++ b/cabal-install/src/Distribution/Client/BuildReports/Storage.hs @@ -66,7 +66,7 @@ import qualified Data.List as L import Data.List.NonEmpty ( groupBy ) -import System.Directory +import Distribution.Compat.Directory ( createDirectoryIfMissing ) import System.FilePath diff --git a/cabal-install/src/Distribution/Client/Check.hs b/cabal-install/src/Distribution/Client/Check.hs index 6ca20139855..4c4b54693f6 100644 --- a/cabal-install/src/Distribution/Client/Check.hs +++ b/cabal-install/src/Distribution/Client/Check.hs @@ -26,12 +26,12 @@ import Distribution.Parsec import Distribution.Simple.Utils (defaultPackageDescCwd, dieWithException, notice, warn, warnError) import Distribution.Utils.Path (getSymbolicPath) -import qualified Control.Monad as CM +import qualified Data.Foldable as CM import qualified Data.ByteString as BS import qualified Data.Function as F import qualified Data.List as L import qualified Data.List.NonEmpty as NE -import qualified System.Directory as Dir +import qualified Distribution.Compat.Directory as Dir readGenericPackageDescriptionCheck :: Verbosity -> FilePath -> IO ([PWarningWithSource CabalFileSource], GenericPackageDescription) readGenericPackageDescriptionCheck verbosity fpath = do diff --git a/cabal-install/src/Distribution/Client/CmdBench.hs b/cabal-install/src/Distribution/Client/CmdBench.hs index f9adc80432b..04f3c5959e8 100644 --- a/cabal-install/src/Distribution/Client/CmdBench.hs +++ b/cabal-install/src/Distribution/Client/CmdBench.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + -- | cabal-install CLI command: bench module Distribution.Client.CmdBench ( -- * The @bench@ CLI and action @@ -54,9 +56,18 @@ import Distribution.Verbosity ( normal ) +#ifdef __MHS__ +import System.Environment (getArgs) +#else import GHC.Environment ( getFullArgs ) +#endif + +#ifdef __MHS__ +getFullArgs :: IO [String] +getFullArgs = getArgs +#endif benchCommand :: CommandUI (NixStyleFlags ()) benchCommand = diff --git a/cabal-install/src/Distribution/Client/CmdClean.hs b/cabal-install/src/Distribution/Client/CmdClean.hs index 8bdfb345a96..ef8c6f9f3d9 100644 --- a/cabal-install/src/Distribution/Client/CmdClean.hs +++ b/cabal-install/src/Distribution/Client/CmdClean.hs @@ -1,5 +1,6 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE PatternSynonyms #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} module Distribution.Client.CmdClean (cleanCommand, cleanAction) where @@ -76,14 +77,13 @@ import Control.Concurrent import Control.Exception ( throw ) -import Control.Monad - ( forM - , forM_ - , mapM - ) +import Data.Foldable (forM_) +import Data.Traversable (forM) import qualified Data.Set as Set +#ifndef __MHS__ import qualified GHC.IO.Exception as GHC -import System.Directory +#endif +import Distribution.Compat.Directory ( canonicalizePath , doesDirectoryExist , doesFileExist @@ -94,10 +94,13 @@ import System.FilePath ( () ) import System.IO.Error - ( ioeGetErrorType - , isPermissionError + ( +#ifndef __MHS__ + ioeGetErrorType, +#endif + isPermissionError ) -import qualified System.Process as Process +import qualified Distribution.Compat.Process as Process data CleanFlags = CleanFlags { cleanSaveConfig :: Flag Bool @@ -199,7 +202,11 @@ cleanAction (ProjectFlags{..}, CleanFlags{..}) extraArgs _ = do -- Permission error is usually when some files are (temporarily) locked. -- Unsatisfied constraints (directory is non empty) error happens -- when some files inside the directory were not removed (perhaps because they are locked). +#ifdef __MHS__ + if isPermissionError e +#else if isPermissionError e || ioeGetErrorType e == GHC.UnsatisfiedConstraints +#endif then threadDelay 1000 >> removePathForcibly distRoot else throw e ) diff --git a/cabal-install/src/Distribution/Client/CmdConfigure.hs b/cabal-install/src/Distribution/Client/CmdConfigure.hs index a8f62517fd0..ec3641c5472 100644 --- a/cabal-install/src/Distribution/Client/CmdConfigure.hs +++ b/cabal-install/src/Distribution/Client/CmdConfigure.hs @@ -11,7 +11,7 @@ import Distribution.Client.Compat.Prelude import Prelude () import qualified Data.Text as Text -import System.Directory +import Distribution.Compat.Directory import System.FilePath import Distribution.Client.ProjectConfig diff --git a/cabal-install/src/Distribution/Client/CmdGenBounds.hs b/cabal-install/src/Distribution/Client/CmdGenBounds.hs index 79090bb95d2..bddc8855724 100644 --- a/cabal-install/src/Distribution/Client/CmdGenBounds.hs +++ b/cabal-install/src/Distribution/Client/CmdGenBounds.hs @@ -11,7 +11,7 @@ import Prelude () import qualified Data.Map as Map -import Control.Monad (mapM_) +import Data.Foldable (mapM_) import Distribution.Client.Errors diff --git a/cabal-install/src/Distribution/Client/CmdHaddock.hs b/cabal-install/src/Distribution/Client/CmdHaddock.hs index bd779cac51b..95fc6357f1d 100644 --- a/cabal-install/src/Distribution/Client/CmdHaddock.hs +++ b/cabal-install/src/Distribution/Client/CmdHaddock.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RecordWildCards #-} @@ -14,7 +15,7 @@ module Distribution.Client.CmdHaddock ) where import Distribution.Client.Compat.Prelude -import System.Directory (makeAbsolute) +import Distribution.Compat.Directory (makeAbsolute) import Prelude () import Distribution.Client.CmdErrorMessages @@ -72,6 +73,13 @@ import Distribution.Verbosity import Distribution.Client.Errors import qualified System.Exit (exitSuccess) +#ifdef __MHS__ +import Data.Monoid (Last (..)) +import Data.Traversable (Traversable (..)) + +instance Traversable Last where + traverse f (Last ma) = Last <$> traverse f ma +#endif newtype ClientHaddockFlags = ClientHaddockFlags {openInBrowser :: Flag Bool} diff --git a/cabal-install/src/Distribution/Client/CmdHaddockProject.hs b/cabal-install/src/Distribution/Client/CmdHaddockProject.hs index 5b894aae07a..f641cacfff3 100644 --- a/cabal-install/src/Distribution/Client/CmdHaddockProject.hs +++ b/cabal-install/src/Distribution/Client/CmdHaddockProject.hs @@ -6,7 +6,6 @@ module Distribution.Client.CmdHaddockProject , haddockProjectAction ) where -import Control.Monad (mapM) import Distribution.Client.Compat.Prelude hiding (get) import Prelude () @@ -20,6 +19,7 @@ import Distribution.Client.DistDirLayout ) import Distribution.Client.InstallPlan (foldPlanPackage) import qualified Distribution.Client.InstallPlan as InstallPlan +import Distribution.Client.NixStyleOptions (NixStyleFlags (NixStyleFlags, configFlags, haddockFlags)) import qualified Distribution.Client.NixStyleOptions as NixStyleOptions import Distribution.Client.ProjectOrchestration ( AvailableTarget (..) @@ -119,7 +119,7 @@ import Distribution.Verbosity as Verbosity ) import Distribution.Client.Errors -import System.Directory (doesDirectoryExist, doesFileExist) +import Distribution.Compat.Directory (doesDirectoryExist, doesFileExist) import System.FilePath (normalise, takeDirectory, ()) haddockProjectAction :: HaddockProjectFlags -> [String] -> GlobalFlags -> IO () @@ -374,7 +374,7 @@ haddockProjectAction flags _extraArgs globalFlags = do mkVerbosity defaultVerbosityHandles $ fromFlagOrDefault normal (setupVerbosity commonFlags) - haddockFlags = + haddockFlags' = defaultHaddockFlags { haddockCommonFlags = commonFlags , haddockHtml = Flag True @@ -418,8 +418,8 @@ haddockProjectAction flags _extraArgs globalFlags = do nixFlags = (commandDefaultFlags CmdHaddock.haddockCommand) - { NixStyleOptions.haddockFlags = haddockFlags - , NixStyleOptions.configFlags = + { haddockFlags = haddockFlags' + , configFlags = (NixStyleOptions.configFlags (commandDefaultFlags CmdBuild.buildCommand)) { configCommonFlags = commonFlags } diff --git a/cabal-install/src/Distribution/Client/CmdInstall.hs b/cabal-install/src/Distribution/Client/CmdInstall.hs index 32bedbea498..8ef9374f094 100644 --- a/cabal-install/src/Distribution/Client/CmdInstall.hs +++ b/cabal-install/src/Distribution/Client/CmdInstall.hs @@ -231,7 +231,7 @@ import Distribution.Utils.NubList ( fromNubList ) import Network.URI (URI) -import System.Directory +import Distribution.Compat.Directory ( copyFile , createDirectoryIfMissing , doesDirectoryExist diff --git a/cabal-install/src/Distribution/Client/CmdOutdated.hs b/cabal-install/src/Distribution/Client/CmdOutdated.hs index e0d65c78fdb..f7c385725bd 100644 --- a/cabal-install/src/Distribution/Client/CmdOutdated.hs +++ b/cabal-install/src/Distribution/Client/CmdOutdated.hs @@ -57,13 +57,14 @@ import Distribution.Version import qualified Data.Set as S import Distribution.Client.NixStyleOptions -import System.Directory +import Distribution.Compat.Directory ( getCurrentDirectory ) import Distribution.Client.ProjectOrchestration -import Control.Monad +import Control.Monad hiding (forM_, mapM, mapM_, sequence, sequence_) +import Data.Foldable (forM_, mapM_) import Distribution.Client.ScriptUtils import Distribution.Package import Distribution.ReadE diff --git a/cabal-install/src/Distribution/Client/CmdRepl.hs b/cabal-install/src/Distribution/Client/CmdRepl.hs index d31689cf1e8..8c6fd007b01 100644 --- a/cabal-install/src/Distribution/Client/CmdRepl.hs +++ b/cabal-install/src/Distribution/Client/CmdRepl.hs @@ -168,8 +168,6 @@ import Language.Haskell.Extension ( Language (..) ) -import Control.Monad (mapM) -import qualified Data.ByteString.Lazy as BS import Data.List ( (\\) ) @@ -190,12 +188,13 @@ import Distribution.Client.ReplFlags import Distribution.Client.Toolchain (Machine (..)) import Distribution.Compat.Binary (decode) import qualified Distribution.Compat.Graph as Graph +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.Simple.Flag (flagToMaybe, fromFlagOrDefault, pattern Flag) import Distribution.Simple.Program.Builtin (ghcProgram) import Distribution.Simple.Program.Db (requireProgram) import Distribution.Simple.Program.Types import Distribution.Types.PackageName.Magic (fakePackageId) -import System.Directory +import Distribution.Compat.Directory ( doesFileExist , getCurrentDirectory , listDirectory @@ -548,7 +547,7 @@ targetedRepl -- Note: decode is partial. Should we use Structured here? -- This might blow up with @build-type: Custom@ stuff. - ghcProgs <- mapM (\f -> decode @ConfiguredProgram <$> BS.readFile (dir "paths" f)) path_files + ghcProgs <- mapM (\f -> decode @ConfiguredProgram <$> readFileLBS (dir "paths" f)) path_files let all_paths = concatMap programOverrideEnv ghcProgs let sp = intercalate [searchPathSeparator] (map fst (sortBy (comparing @Int snd) $ Map.toList (combine_search_paths all_paths))) diff --git a/cabal-install/src/Distribution/Client/CmdRun.hs b/cabal-install/src/Distribution/Client/CmdRun.hs index 1105b80e487..0869878388f 100644 --- a/cabal-install/src/Distribution/Client/CmdRun.hs +++ b/cabal-install/src/Distribution/Client/CmdRun.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} -- | cabal-install CLI command: run @@ -130,12 +131,23 @@ import Distribution.Verbosity ( normal , silent ) +#ifdef __MHS__ +import System.Environment + ( getArgs + ) +#else import GHC.Environment ( getFullArgs ) -import System.Directory +#endif +import Distribution.Compat.Directory ( doesFileExist ) + +#ifdef __MHS__ +getFullArgs :: IO [String] +getFullArgs = getArgs +#endif import System.FilePath ( isPathSeparator , isValid diff --git a/cabal-install/src/Distribution/Client/CmdSdist.hs b/cabal-install/src/Distribution/Client/CmdSdist.hs index 6ac25d527c1..2eea9658b8d 100644 --- a/cabal-install/src/Distribution/Client/CmdSdist.hs +++ b/cabal-install/src/Distribution/Client/CmdSdist.hs @@ -136,11 +136,12 @@ import Distribution.Verbosity ) import qualified Data.ByteString.Lazy.Char8 as BSL -import System.Directory +import Distribution.Compat.Directory ( createDirectoryIfMissing , getCurrentDirectory , makeAbsolute ) +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import System.FilePath ( makeRelative , normalise @@ -356,7 +357,7 @@ packageToSdist verbosity projectRootDir format outputFile pkg = do Left tgz -> do case format of TarGzArchive -> do - writeLBS =<< BSL.readFile tgz + writeLBS =<< readFileLBS tgz _ -> dieWithException verbosity $ CannotConvertTarballPackage (show format) Right dir -> do case format of diff --git a/cabal-install/src/Distribution/Client/CmdTarget.hs b/cabal-install/src/Distribution/Client/CmdTarget.hs index 84e39e9925f..3e145a2b559 100644 --- a/cabal-install/src/Distribution/Client/CmdTarget.hs +++ b/cabal-install/src/Distribution/Client/CmdTarget.hs @@ -22,7 +22,8 @@ import Distribution.Client.NixStyleOptions import Distribution.Client.ProjectOrchestration import Distribution.Client.ProjectPlanning import Distribution.Client.Setup - ( ConfigFlags (..) + ( CommonSetupFlags (..) + , ConfigFlags (..) , GlobalFlags ) import Distribution.Client.TargetProblem @@ -183,7 +184,7 @@ targetAction flags@NixStyleFlags{..} ts globalFlags = do where verbosity = mkVerbosity defaultVerbosityHandles $ - fromFlagOrDefault normal (configVerbosity configFlags) + fromFlagOrDefault normal (setupVerbosity $ configCommonFlags configFlags) targetStrings = if null ts then ["all"] else ts cliConfig = commandLineFlagsToProjectConfig diff --git a/cabal-install/src/Distribution/Client/CmdTest.hs b/cabal-install/src/Distribution/Client/CmdTest.hs index 6ad41678849..5786d11b184 100644 --- a/cabal-install/src/Distribution/Client/CmdTest.hs +++ b/cabal-install/src/Distribution/Client/CmdTest.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RecordWildCards #-} @@ -67,9 +68,18 @@ import Distribution.Verbosity import qualified System.Exit (exitSuccess) import Distribution.Client.Errors +#ifdef __MHS__ +import System.Environment (getArgs) +#else import GHC.Environment ( getFullArgs ) +#endif + +#ifdef __MHS__ +getFullArgs :: IO [String] +getFullArgs = getArgs +#endif testCommand :: CommandUI (NixStyleFlags ()) testCommand = diff --git a/cabal-install/src/Distribution/Client/CmdUpdate.hs b/cabal-install/src/Distribution/Client/CmdUpdate.hs index 99d35a4e415..2390266eb9f 100644 --- a/cabal-install/src/Distribution/Client/CmdUpdate.hs +++ b/cabal-install/src/Distribution/Client/CmdUpdate.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} -- | cabal-install CLI command: update @@ -71,16 +72,22 @@ import Distribution.Verbosity , modifyVerbosityFlags , normal ) +#ifdef __MHS__ +import Distribution.Compat.Directory + ( setModificationTime + ) +#else import System.Directory ( setModificationTime ) +#endif import qualified Data.Maybe as Unsafe (fromJust) import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp -import qualified Data.ByteString.Lazy as BS import Data.Time (getCurrentTime) +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.Client.GZipUtils (maybeDecompress) import Distribution.Simple.Command ( CommandUI (..) @@ -90,7 +97,9 @@ import System.FilePath (dropExtension, (<.>)) import Distribution.Client.Errors import Distribution.Client.IndexUtils.Timestamp (Timestamp (NoTimestamp)) +#ifndef __MHS__ import qualified Hackage.Security.Client as Sec +#endif updateCommand :: CommandUI (NixStyleFlags ()) updateCommand = @@ -236,9 +245,15 @@ updateRepo verbosity repoCtxt (repo, indexState) = do =<< getCurrentTime FileDownloaded indexPath -> do writeFileAtomic (dropExtension indexPath) . maybeDecompress - =<< BS.readFile indexPath + =<< readFileLBS indexPath updateRepoIndexCache verbosity (RepoIndex repoCtxt repo) - RepoSecure{} -> repoContextWithSecureRepo repoCtxt repo $ \repoSecure -> do + RepoSecure{} -> +#ifdef __MHS__ + -- Secure repositories are not supported in this build. + repoContextWithSecureRepo repoCtxt repo $ \_ -> + error "unreachable: secure repositories are not supported" +#else + repoContextWithSecureRepo repoCtxt repo $ \repoSecure -> do let index = RepoIndex repoCtxt repo -- NB: This may be a NoTimestamp if we've never updated before current_ts <- currentIndexTimestamp (modifyVerbosityFlags lessVerbose verbosity) index @@ -290,3 +305,4 @@ updateRepo verbosity repoCtxt (repo, indexState) = do ++ " cabal v2-update '" ++ prettyShow (UpdateRequest rname (IndexStateTime current_ts)) ++ "'\n" +#endif diff --git a/cabal-install/src/Distribution/Client/Compat/Base16.hs b/cabal-install/src/Distribution/Client/Compat/Base16.hs new file mode 100644 index 00000000000..082910d7133 --- /dev/null +++ b/cabal-install/src/Distribution/Client/Compat/Base16.hs @@ -0,0 +1,49 @@ +{-# LANGUAGE CPP #-} + +-- | Minimal base-16 (hex) codec, mirroring the API of +-- @Data.ByteString.Base16@ ('encode' and 'decode') that is used +-- elsewhere in @cabal-install@. +-- +-- MicroHs has no @base16@ package, so this module is used instead of +-- 'Data.ByteString.Base16' under @__MHS__@ (see the import sites). +-- Behaviour matches the real package on valid input: lowercase hex +-- output, and decoding accepts upper- and lower-case digits. +module Distribution.Client.Compat.Base16 + ( encode + , decode + ) where + +import qualified Data.ByteString as BS +import Data.Word (Word8) + +-- | Encode bytes as lowercase hex. +encode :: BS.ByteString -> BS.ByteString +encode = BS.pack . concatMap byteHex . BS.unpack + where + byteHex :: Word8 -> [Word8] + byteHex w = [hexDigit (w `div` 16), hexDigit (w `mod` 16)] + hexDigit :: Word8 -> Word8 + hexDigit n = fromIntegral (fromEnum c) + where + c = "0123456789abcdef" !! fromIntegral n +-- | Decode hex (upper- or lower-case) to bytes. +decode :: BS.ByteString -> Either String BS.ByteString +decode bs + | odd (BS.length bs) = Left "Base16.decode: odd-length input" + | otherwise = BS.pack <$> traverse hexPair (pairs (BS.unpack bs)) + where + pairs :: [Word8] -> [(Word8, Word8)] + pairs [] = [] + pairs (h : l : t) = (h, l) : pairs t + pairs [_] = [] -- unreachable: the length check above rules this out + hexPair :: (Word8, Word8) -> Either String Word8 + hexPair (h, l) = do + hi <- hexVal h + lo <- hexVal l + return (hi * 16 + lo) + hexVal :: Word8 -> Either String Word8 + hexVal c + | c >= 48 && c <= 57 = Right (c - 48) -- '0'-'9' + | c >= 97 && c <= 102 = Right (c - 87) -- 'a'-'f' + | c >= 65 && c <= 70 = Right (c - 55) -- 'A'-'F' + | otherwise = Left ("Base16.decode: invalid hex digit: " ++ show c) diff --git a/cabal-install/src/Distribution/Client/Compat/Orphans.hs b/cabal-install/src/Distribution/Client/Compat/Orphans.hs index d25d991b023..e99b5637301 100644 --- a/cabal-install/src/Distribution/Client/Compat/Orphans.hs +++ b/cabal-install/src/Distribution/Client/Compat/Orphans.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -Wno-orphans #-} module Distribution.Client.Compat.Orphans () where @@ -8,11 +9,33 @@ import Distribution.Compat.Binary (Binary (..)) import Distribution.Utils.Structured (Structure (Nominal), Structured (..)) import Network.URI (URI (..), URIAuth (..)) import Prelude (error, return) +#ifdef __MHS__ +import Control.DeepSeq (NFData (..)) +import Prelude (Ord (..), (<>), seq) +#endif ------------------------------------------------------------------------------- -- network-uri ------------------------------------------------------------------------------- +#ifdef __MHS__ +-- uri-mhs-0.1.0.0 only provides Eq and Show for URI and URIAuth; +-- network-uri provides Ord and NFData as well. +instance Ord URIAuth where + compare (URIAuth a1 b1 c1) (URIAuth a2 b2 c2) = + compare a1 a2 <> compare b1 b2 <> compare c1 c2 + +instance Ord URI where + compare (URI a1 b1 c1 d1 e1) (URI a2 b2 c2 d2 e2) = + compare a1 a2 <> compare b1 b2 <> compare c1 c2 <> compare d1 d2 <> compare e1 e2 + +instance NFData URIAuth where + rnf (URIAuth a b c) = rnf a `seq` rnf b `seq` rnf c + +instance NFData URI where + rnf (URI a b c d e) = rnf a `seq` rnf b `seq` rnf c `seq` rnf d `seq` rnf e +#endif + -- note, network-uri-2.6.0.3+ provide a Generic instance but earlier -- versions do not, so we use manual Binary instances here instance Binary URI where diff --git a/cabal-install/src/Distribution/Client/Compat/Semaphore.hs b/cabal-install/src/Distribution/Client/Compat/Semaphore.hs index 60fda2cf389..1fbaf8d5707 100644 --- a/cabal-install/src/Distribution/Client/Compat/Semaphore.hs +++ b/cabal-install/src/Distribution/Client/Compat/Semaphore.hs @@ -1,5 +1,3 @@ -{-# OPTIONS_GHC -funbox-strict-fields #-} - module Distribution.Client.Compat.Semaphore ( QSem , newQSem diff --git a/cabal-install/src/Distribution/Client/Compat/Tar.hs b/cabal-install/src/Distribution/Client/Compat/Tar.hs index eb0eb96eeb2..d4392339ae6 100644 --- a/cabal-install/src/Distribution/Client/Compat/Tar.hs +++ b/cabal-install/src/Distribution/Client/Compat/Tar.hs @@ -1,6 +1,462 @@ {-# LANGUAGE CPP #-} +#ifndef __MHS__ {-# OPTIONS_GHC -Wno-orphans #-} +#endif +#ifdef __MHS__ +{- FOURMOLU_DISABLE -} +module Distribution.Client.Compat.Tar + ( extractTarGzFile + , createTarGzFile + -- * Pure tar reader (for index files) + , Entry (..) + , Entries (..) + , EntryContent (..) + , TypeCode + , FormatError (..) + , TarPath (..) + , EpochTime + , Permissions + , ordinaryFilePermissions + , toTarPath + , entryPath + , entryTarPath + , read + , hReadEntry + , nextEntryOffset + , foldEntries + , foldlEntries + -- * Pure tar writer (for @v2-sdist@) + , directoryEntry + , fileEntry + , write + ) where +{- FOURMOLU_ENABLE -} + +import Distribution.Client.Compat.Prelude +import Prelude () + +import qualified Data.ByteString as BS +import qualified Data.ByteString.Char8 as BSChar8 +import Data.ByteString.Lazy (ByteString) +import qualified Data.ByteString.Lazy as LBS +import Data.Char (digitToInt) + +import Distribution.Compat.Directory + ( createDirectoryIfMissing + , findExecutable + ) +import qualified Distribution.Compat.Process as Process +import System.FilePath + ( isAbsolute + , normalise + , splitDirectories + , () + ) +import System.IO + ( Handle + , SeekMode (AbsoluteSeek) +#ifndef __MHS__ + , hSeek +#endif + ) +#ifdef __MHS__ +import Foreign.C.Error (throwErrnoIfMinus1_) +import Foreign.C.Types (CInt (..)) +import Foreign.Ptr (Ptr) +import System.IO.Internal (BFILE, withHandleAny) +#endif +import System.IO.Error (userError) + +-- | A validated path inside a tar archive: relative, without @..@ +-- components. Build one with 'toTarPath'. +newtype TarPath = TarPath { fromTarPath :: FilePath } + deriving (Eq, Ord, Show) + +-- | Time in seconds since the Unix epoch, as stored in tar headers. +type EpochTime = Int64 + +-- | File permission bits (the low 12 bits of the mode field). +type Permissions = Int + +-- | Default permissions for regular files (0o644). +ordinaryFilePermissions :: Permissions +ordinaryFilePermissions = 420 + +-- | Default permissions for directories (0o755). +directoryPermissions :: Permissions +directoryPermissions = 493 + +-- | A tar archive entry: its path, content, permissions and modification time. +data Entry = Entry + { entryTarPath :: TarPath + , entryContent :: EntryContent + , entryPermissions :: Permissions + , entryTime :: EpochTime + } + deriving (Show) + +-- | The file path of a tar archive entry. +entryPath :: Entry -> FilePath +entryPath = fromTarPath . entryTarPath + +-- | Validate a file path for use inside a tar archive. +toTarPath :: Bool -> FilePath -> Either String TarPath +toTarPath _isDir fp + | null norm = Left "empty tar path" + | isAbsolute norm = Left ("absolute tar path: " ++ show fp) + | ".." `elem` splitDirectories norm = Left ("tar path escapes its directory: " ++ show fp) + | otherwise = Right (TarPath norm) + where + norm = normalise fp + +-- | The content of a tar archive entry. +data EntryContent + = NormalFile LBS.ByteString Int + | Directory + | OtherEntryType TypeCode LBS.ByteString Int + deriving (Show) + +-- | Tar type-flag code (a single 'Char'). +type TypeCode = Char + +-- | Failure to parse a tar archive. +data FormatError = FormatError String + deriving (Show) + +instance Exception FormatError + +-- | A (possibly partial) sequence of tar entries. +data Entries e + = Next Entry (Entries e) + | Done + | Fail e + deriving (Show) + +-- | Fold over a sequence of entries. +foldEntries :: (Entry -> a -> a) -> a -> (e -> a) -> Entries e -> a +foldEntries next done fail = go + where + go (Next e es) = next e (go es) + go Done = done + go (Fail e) = fail e + +-- | Strict left fold over a sequence of entries. On a malformed entry +-- the partial accumulator is returned together with the error. +foldlEntries :: (a -> Entry -> a) -> a -> Entries e -> Either (e, a) a +foldlEntries f = go + where + go acc (Next e es) = go (f acc e) es + go acc Done = Right acc + go acc (Fail e) = Left (e, acc) + +-- | Read the entries of an uncompressed tar archive, lazily in the +-- spine of the resulting 'Entries' structure. +read :: LBS.ByteString -> Entries FormatError +read = go Nothing + where + go _longName bs + | LBS.null bs = Done + | isZeroBlock (LBS.take 512 bs) = Done + | LBS.length bs < 512 = Fail (FormatError "short tar archive") + | otherwise = case parseHeader (BS.concat (LBS.toChunks (LBS.take 512 bs))) of + Left err -> Fail err + Right (rawName, size, typeCode, perms, mtime) -> + let body = LBS.take (fromIntegral size) (LBS.drop 512 bs) + rest = dropPadding size (LBS.drop (512 + fromIntegral size) bs) + in if LBS.length body < fromIntegral size + then Fail (FormatError "short tar entry") + else case typeCode of + -- GNU long name: the body is the path of the next entry. + 'L' -> go (Just (normaliseLongName body)) rest + -- GNU long linkname: irrelevant for reading, skip it. + 'K' -> go Nothing rest + _ -> + let name = fromMaybe rawName _longName + in Next (Entry (TarPath name) (mkContent typeCode body size) perms mtime) (go Nothing rest) + +#ifdef __MHS__ +foreign import ccall "mhs_handle.h mhs_handle_seek" + c_handleSeek :: Ptr BFILE -> CInt -> Int64 -> IO CInt + +hSeek :: Handle -> SeekMode -> Integer -> IO () +hSeek h mode off = + withHandleAny h $ \p -> + throwErrnoIfMinus1_ "hSeek" $ + c_handleSeek p (fromIntegral (fromEnum mode)) (fromIntegral off) +#endif + +-- | Read a single entry at the given 512-byte block offset. +-- +-- Throws 'FormatError' on parse failure. +hReadEntry :: Handle -> Word32 -> IO Entry +hReadEntry h blockNo = do + hSeek h AbsoluteSeek (fromIntegral blockNo * 512) + hdr <- readExactly h 512 + (rawName, size, typeCode, perms, mtime) <- either throwIO return (parseHeader hdr) + body <- readExactlyChunks h size + return (Entry (TarPath rawName) (mkContent typeCode (LBS.fromChunks body) size) perms mtime) + +-- | The block offset of the entry following the given one. +nextEntryOffset :: Entry -> Word32 -> Word32 +nextEntryOffset entry blockNo = blockNo + 1 + contentBlocks + where + contentBlocks = fromIntegral ((contentSize + 511) `div` 512) + contentSize :: Int + contentSize = case entryContent entry of + NormalFile content _ -> fromIntegral (LBS.length content) + OtherEntryType _ content _ -> fromIntegral (LBS.length content) + Directory -> 0 + +-- | Skip @size@ bytes of content plus padding to a 512-byte boundary. +dropPadding :: Int -> LBS.ByteString -> LBS.ByteString +dropPadding size bs = LBS.drop (fromIntegral padding) bs + where + padding = (512 - size `mod` 512) `mod` 512 + +mkContent :: TypeCode -> LBS.ByteString -> Int -> EntryContent +mkContent typeCode body size + | typeCode == '0' || typeCode == '\0' = NormalFile body size + | typeCode == '5' = Directory + | otherwise = OtherEntryType typeCode body size + +normaliseLongName :: LBS.ByteString -> FilePath +normaliseLongName = normalise . BSChar8.unpack . BS.concat . LBS.toChunks . fst . LBS.span (/= 0) + +isZeroBlock :: LBS.ByteString -> Bool +isZeroBlock = LBS.all (== 0) + +-- | Parse a 512-byte ustar header block into +-- (path, size, type code, permissions, modification time). +parseHeader :: BS.ByteString -> Either FormatError (FilePath, Int, TypeCode, Permissions, EpochTime) +parseHeader blk + | BS.length blk < 512 = Left (FormatError "short tar header") + | otherwise = do + name <- Right (fieldString 0 100) + prefix <- Right (fieldString 345 155) + size <- parseNumberField blk 124 12 + mode <- parseNumberField blk 100 8 + mtime <- parseNumberField blk 136 12 + let typeCode = if BS.index blk 156 == 0 then '\0' else BSChar8.index blk 156 + path + | null prefix = name + | otherwise = prefix name + return (path, size, typeCode, mode `mod` 4096, fromIntegral mtime) + where + fieldString off len = + BSChar8.unpack (BS.takeWhile (/= 0) (BS.take len (BS.drop off blk))) + +-- | Parse an octal (or base-256) numeric header field. +parseNumberField :: BS.ByteString -> Int -> Int -> Either FormatError Int +parseNumberField blk off len = parseField (BS.take len (BS.drop off blk)) + where + parseField raw + | BS.null raw = Right 0 + | BS.head raw >= 0x80 = Right (base256 (BS.tail raw)) + | otherwise = + let s = filter (/= ' ') (BSChar8.unpack (BS.takeWhile (/= 0) raw)) + in if null s + then Right 0 + else + if all (`elem` ("01234567" :: String)) s + then Right (foldl (\a c -> a * 8 + digitToInt c) 0 s) + else Left (FormatError "bad tar numeric field") + +base256 :: BS.ByteString -> Int +base256 = BS.foldl' (\a b -> a * 256 + fromIntegral b) 0 + +------------------------------------------------------------------------------- +-- Pure tar writer +------------------------------------------------------------------------------- + +-- | A directory entry with default directory permissions. +directoryEntry :: TarPath -> Entry +directoryEntry tp = Entry tp Directory directoryPermissions 0 + +-- | A regular file entry with default file permissions. +fileEntry :: TarPath -> ByteString -> Entry +fileEntry tp content = + Entry tp (NormalFile content (fromIntegral (LBS.length content))) ordinaryFilePermissions 0 + +-- | Serialise entries to an uncompressed tar archive, terminated by two +-- zero blocks as usual. Paths that do not fit the ustar name/prefix +-- fields are stored with a GNU longname (@L@) entry, which 'read' +-- understands. +write :: [Entry] -> ByteString +write entries = LBS.concat (map putEntry entries ++ [LBS.replicate 1024 0]) + +putEntry :: Entry -> ByteString +putEntry entry = LBS.concat (longHeader ++ [hdr, content, pad]) + where + (typeCode, content) = case entryContent entry of + NormalFile c _ -> ('0', c) + Directory -> ('5', LBS.empty) + OtherEntryType t c _ -> (t, c) + size = fromIntegral (LBS.length content) :: Int + rawName = fromTarPath (entryTarPath entry) + -- Directory entries are stored with a trailing slash. + -- NOTE: 'last' is NonEmpty-specialised in this Prelude, so compare + -- the final character via 'drop' instead. + name = case entryContent entry of + Directory | not (null rawName) && drop (length rawName - 1) rawName /= "/" -> rawName ++ "/" + _ -> rawName + (prefix, shortName, longHeader) = encodeName name + hdr = LBS.fromStrict (encodeHeader shortName prefix size (entryPermissions entry) (entryTime entry) typeCode) + pad = LBS.replicate (fromIntegral ((512 - size `mod` 512) `mod` 512)) 0 + +-- | Split a path for the ustar name/prefix fields, falling back to a GNU +-- longname entry. Returns @(prefix, name, extraHeaders)@. +encodeName :: FilePath -> (String, String, [ByteString]) +encodeName name + | length name <= 100 = ("", name, []) + | Just (prefix, base) <- splitUstarName name = (prefix, base, []) + | otherwise = + let content = LBS.fromStrict (BSChar8.pack (name ++ "\0")) + longSize = length name + 1 + hdr = LBS.fromStrict (encodeHeader "././@LongLink" "" longSize 0 0 'L') + pad = LBS.replicate (fromIntegral ((512 - longSize `mod` 512) `mod` 512)) 0 + in ("", take 100 name, [LBS.concat [hdr, content, pad]]) + +-- | Split a long path at a @/@ so that the prefix fits in 155 bytes and +-- the remainder in 100 bytes, preferring the longest such prefix. +splitUstarName :: FilePath -> Maybe (String, String) +splitUstarName name = + listToMaybe + [ (prefix, rest) + | i <- reverse [1 .. length name - 1] + , name !! i == '/' + , let prefix = take i name + , let rest = drop (i + 1) name + , not (null rest) + , length prefix <= 155 + , length rest <= 100 + ] + +-- | Encode a single 512-byte ustar header block. +encodeHeader :: FilePath -> FilePath -> Int -> Permissions -> EpochTime -> TypeCode -> BS.ByteString +encodeHeader name prefix size perms mtime typeCode = BSChar8.pack withChecksum + where + raw = + padField name 100 + ++ octalField 8 perms + ++ octalField 8 0 -- uid + ++ octalField 8 0 -- gid + ++ octalField 12 size + ++ octalField 12 (fromIntegral mtime) + ++ replicate 8 ' ' -- checksum placeholder + ++ [typeCode] + ++ padField "" 100 -- linkname + ++ "ustar\0" + ++ "00" + ++ padField "" 32 -- uname + ++ padField "" 32 -- gname + ++ octalField 8 0 -- devmajor + ++ octalField 8 0 -- devminor + ++ padField prefix 155 + ++ replicate 12 '\0' + chk = sum (map ord raw) + chkField = let s = toOctal chk in replicate (6 - length s) '0' ++ s ++ "\0 " + withChecksum = take 148 raw ++ chkField ++ drop 156 raw + +-- | A NUL-padded string field of the given width. +padField :: String -> Int -> String +padField s w = take w (s ++ repeat '\0') + +-- | An octal numeric field of the given width, NUL-terminated. +octalField :: Int -> Int -> String +octalField w v = replicate (w - 1 - length s) '0' ++ s ++ "\0" + where + s = toOctal v + +-- | Render a non-negative number in octal. +toOctal :: Int -> String +toOctal 0 = "0" +toOctal n = reverse (go n) + where + go 0 = [] + go x = "01234567" !! (x `mod` 8) : go (x `div` 8) + +readExactly :: Handle -> Int -> IO BS.ByteString +readExactly h n = BS.concat <$> readExactlyChunks h n + +readExactlyChunks :: Handle -> Int -> IO [BS.ByteString] +readExactlyChunks _ n | n <= 0 = return [] +readExactlyChunks h n = do + chunk <- BS.hGet h n + if BS.null chunk + then throwIO (FormatError "short tar archive") + else (chunk :) <$> readExactlyChunks h (n - BS.length chunk) + +------------------------------------------------------------------------------- +-- External @tar@ for packing and unpacking +------------------------------------------------------------------------------- + +-- | Unpack a @.tar.gz@ file into a destination directory, checking for +-- tarbombs: every entry must live under the expected subdirectory, and +-- no entry may be absolute or contain @..@. +extractTarGzFile + :: FilePath + -- ^ Destination directory + -> FilePath + -- ^ Expected subdir (to check for tarbombs) + -> FilePath + -- ^ Tarball + -> IO () +extractTarGzFile dir expected tar = do + tarProg <- findTar + listing <- + Process.readCreateProcessWithExitCode + (Process.proc tarProg ["-tzf", tar]) + "" + names <- case listing of + (ExitSuccess, out, _) -> return (lines out) + (ExitFailure n, _, err) -> + throwIO $ + userError $ + "tar -tzf failed with exit code " ++ show n ++ ": " ++ err + traverse_ (checkEntry expected) names + createDirectoryIfMissing True dir + Process.callProcess tarProg ["-xzf", tar, "-C", dir] + +-- | Create a @.tar.gz@ file from a directory, relative to a base directory. +createTarGzFile + :: FilePath + -- ^ Full Tarball path + -> FilePath + -- ^ Base directory + -> FilePath + -- ^ Directory to archive, relative to base dir + -> IO () +createTarGzFile tar base dir = do + tarProg <- findTar + Process.callProcess tarProg ["-czf", tar, "-C", base, dir] + +findTar :: IO FilePath +findTar = do + mbTar <- findExecutable "tar" + case mbTar of + Just tar -> return tar + Nothing -> throwIO (userError "The external 'tar' program is required but was not found on PATH.") + +checkEntry :: FilePath -> FilePath -> IO () +checkEntry expected rawName = do + let name = stripTrailingSlash (stripDotSlash (normalise rawName)) + when (null name || isAbsolute name || (".." `elem` splitDirectories name)) $ + throwIO (userError ("tar entry is not a safe relative path: " ++ show rawName)) + unless (name == expected || (expected ++ "/") `isPrefixOf` name) $ + throwIO (userError ("tar entry outside expected directory " ++ show expected ++ ": " ++ show rawName)) + +stripDotSlash :: FilePath -> FilePath +stripDotSlash name + | "./" `isPrefixOf` name = stripDotSlash (drop 2 name) + | otherwise = name + +stripTrailingSlash :: FilePath -> FilePath +stripTrailingSlash name + | "/" `isSuffixOf` name && length name > 1 = stripTrailingSlash (take (length name - 1) name) + | otherwise = name + +#else {- FOURMOLU_DISABLE -} module Distribution.Client.Compat.Tar ( extractTarGzFile @@ -84,3 +540,4 @@ createTarGzFile tar base dir = #endif {- FOURMOLU_ENABLE -} +#endif diff --git a/cabal-install/src/Distribution/Client/Config.hs b/cabal-install/src/Distribution/Client/Config.hs index eb5e5739096..0af2f2d4f2f 100644 --- a/cabal-install/src/Distribution/Client/Config.hs +++ b/cabal-install/src/Distribution/Client/Config.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} @@ -218,7 +219,7 @@ import Network.URI , URIAuth (..) , parseURI ) -import System.Directory +import Distribution.Compat.Directory ( XdgDirectory (XdgCache, XdgConfig, XdgState) , createDirectoryIfMissing , doesDirectoryExist @@ -236,18 +237,30 @@ import System.FilePath import System.IO.Error ( isDoesNotExistError ) +#ifdef __MHS__ +-- @pretty-mhs@ provides only 'Text.PrettyPrint' (no @HughesPJ@ +-- submodule), which exports the same 'Doc'/'text' API. +import Text.PrettyPrint + ( Doc + , text + , ($+$) + ) +#else import Text.PrettyPrint ( ($+$) ) +#endif import qualified Text.PrettyPrint as Disp ( empty , render , text ) +#ifndef __MHS__ import Text.PrettyPrint.HughesPJ ( Doc , text ) +#endif -- diff --git a/cabal-install/src/Distribution/Client/Configure.hs b/cabal-install/src/Distribution/Client/Configure.hs index 5f15fc65bfa..99125cbfc22 100644 --- a/cabal-install/src/Distribution/Client/Configure.hs +++ b/cabal-install/src/Distribution/Client/Configure.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE DataKinds #-} - -- | -- Module : Distribution.Client.Configure -- Copyright : (c) David Himmelstrup 2005, diff --git a/cabal-install/src/Distribution/Client/Dependency.hs b/cabal-install/src/Distribution/Client/Dependency.hs index 25e93089ca7..4eb6912771f 100644 --- a/cabal-install/src/Distribution/Client/Dependency.hs +++ b/cabal-install/src/Distribution/Client/Dependency.hs @@ -1,5 +1,6 @@ ----------------------------------------------------------------------------- +{-# LANGUAGE CPP #-} -- | -- Module : Distribution.Client.Dependency -- Copyright : (c) David Himmelstrup 2005, @@ -67,6 +68,7 @@ module Distribution.Client.Dependency ) where import Distribution.Client.Compat.Prelude +import Prelude () import Distribution.Client.Dependency.Types ( PackagesPreferenceDefault (..) @@ -720,6 +722,7 @@ addDefaultSetupDependencies applyDefaultSetupDeps defaultSetupDeps params = -- packages to not depend on @Cabal@ at all (although basically unheard of -- in practice). addCabalDepForHooks :: PD.BuildType -> Maybe PD.SetupBuildInfo -> Maybe PD.SetupBuildInfo +#ifndef __MHS__ addCabalDepForHooks PD.Hooks = fmap addDep where addDep sbi@(PD.SetupBuildInfo{PD.setupDepends = deps}) @@ -728,6 +731,7 @@ addCabalDepForHooks PD.Hooks = fmap addDep | otherwise = sbi{PD.setupDepends = Dependency cabalPkgName anyVersion mainLibSet : deps} cabalPkgName = mkPackageName "Cabal" +#endif addCabalDepForHooks _ = id -- | Provides the fallback default "setup-depends", when: @@ -1042,7 +1046,7 @@ validateSolverResult toolchains indepGoals pkgs = Left problems -> fail (formatPlanProblems problems) problems -> fail (formatPkgProblems problems) where - graph :: Graph.Graph (ResolverPackage UnresolvedPkgLoc) + graph :: Graph.Graph SolverId (ResolverPackage UnresolvedPkgLoc) graph = Graph.fromDistinctList pkgs formatPkgProblems :: [PlanPackageProblem] -> String diff --git a/cabal-install/src/Distribution/Client/Errors.hs b/cabal-install/src/Distribution/Client/Errors.hs index 158402b4764..382e91e93ed 100644 --- a/cabal-install/src/Distribution/Client/Errors.hs +++ b/cabal-install/src/Distribution/Client/Errors.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- Module : Distribution.Client.Errors -- Copyright : Suganya Arun -- License : BSD3 @@ -13,13 +14,18 @@ module Distribution.Client.Errors ) where import Data.ByteString (ByteString) +#ifdef __MHS__ +import qualified Distribution.Client.Compat.Base16 as Base16 +#else import qualified Data.ByteString.Base16 as Base16 +#endif import qualified Data.ByteString.Char8 as BS8 import Data.List (groupBy) import Distribution.Client.IndexUtils.Timestamp import qualified Distribution.Client.Types.Repo as Repo import qualified Distribution.Client.Types.RepoName as RepoName import Distribution.Compat.Prelude +import Prelude () import Distribution.Deprecated.ParseUtils (PWarning, showPWarning) import Distribution.Package import Distribution.Pretty @@ -28,7 +34,6 @@ import Distribution.Simple.Utils import Network.URI import Text.PrettyPrint hiding (render, (<>)) import qualified Text.PrettyPrint as PP -import Text.Regex.Posix.ByteString (WrapError) import Distribution.Client.Errors.Parser @@ -98,7 +103,7 @@ data CabalInstallException | ReplTakesNoArguments [String] | ReplTakesSingleArgument [String] | RenderReplTargetProblem [String] - | GetPkgList String WrapError + | GetPkgList String String | GatherPkgInfo PackageName VersionRange | UnableToParseRepo String | NullUnknownrepos [String] [String] @@ -464,7 +469,7 @@ exceptionMessageCabalInstall e = case e of ReplTakesNoArguments targetStrings -> "'repl' takes no arguments or a script argument outside a project: " ++ unwords targetStrings ReplTakesSingleArgument targetStrings -> "'repl' takes a single argument which should be a script: " ++ unwords targetStrings RenderReplTargetProblem renderProblem -> unlines renderProblem - GetPkgList pat err -> "Failed to compile regex " ++ pat ++ ": " ++ snd err + GetPkgList pat err -> "Failed to compile regex " ++ pat ++ ": " ++ err GatherPkgInfo name verConstraint -> "There is no available version of " ++ prettyShow name diff --git a/cabal-install/src/Distribution/Client/FetchUtils.hs b/cabal-install/src/Distribution/Client/FetchUtils.hs index ad76b32ec04..979bfa2893c 100644 --- a/cabal-install/src/Distribution/Client/FetchUtils.hs +++ b/cabal-install/src/Distribution/Client/FetchUtils.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} -- | @@ -70,17 +71,31 @@ import Distribution.Verbosity import Control.Concurrent.Async import Control.Concurrent.MVar +#ifdef __MHS__ +import qualified Control.Exception as Safe + ( try + ) +#else import qualified Control.Exception.Safe as Safe +#endif import qualified Data.Map as Map import Network.URI ( URI (uriPath) ) +#ifdef __MHS__ +import Distribution.Compat.Directory + ( createDirectoryIfMissing + , doesFileExist + , getTemporaryDirectory + ) +#else import System.Directory ( createDirectoryIfMissing , doesFileExist , getFileSize , getTemporaryDirectory ) +#endif import System.FilePath ( (<.>) , () @@ -91,14 +106,20 @@ import qualified System.FilePath.Posix as FilePath.Posix ) import System.IO ( hClose - , openTempFile ) +#ifdef __MHS__ +import Distribution.Compat.Internal.TempFile (openTempFile) +#else +import System.IO (openTempFile) +#endif import Control.Monad (forM) import Distribution.Client.Errors +#ifndef __MHS__ import qualified Hackage.Security.Client as Sec import qualified Hackage.Security.Util.Checked as Sec import qualified Hackage.Security.Util.Path as Sec +#endif -- ------------------------------------------------------------ @@ -159,6 +180,34 @@ verifyFetchedTarballs (Repo, PackageId) -- Verified (Repo, PackageId) -- unverified) ] +#ifdef __MHS__ +verifyFetchedTarballs verbosity repoCtxt repo pkgids = + case repo of + -- Secure repositories are not supported in this build. + RepoSecure{} -> repoContextWithSecureRepo repoCtxt repo $ \_ -> + error "unreachable: secure repositories are not supported" + _ -> forM pkgids $ \pkgid -> do + let file = packageFile repo pkgid + res <- verifyFetchedTarball verbosity file pkgid + return $ if res then Left (repo, pkgid) else Right (repo, pkgid) + +verifyFetchedTarball :: Verbosity -> FilePath -> PackageId -> IO Bool +verifyFetchedTarball verbosity file _pkgid = + let + handleError :: IO Bool -> IO Bool + handleError act = do + res <- Safe.try act + case res of + Left e -> warn verbosity ("Error verifying fetched tarball " ++ file ++ ", will redownload: " ++ show (e :: SomeException)) >> pure False + Right b -> pure b + in + handleError $ do + -- Without repository metadata there are no hashes to verify + -- against, so an existing file is accepted as-is, while a + -- missing file vacuously passes validation (it will be + -- downloaded, and the download hash-checked, as necessary). + doesFileExist file +#else verifyFetchedTarballs verbosity repoCtxt repo pkgids = -- Establish the context once per repo (see #10110), this codepath is important -- to be fast as it can happen when no other building happens. @@ -208,6 +257,7 @@ verifyFetchedTarball verbosity file mCallbacks pkgid = `Sec.catchChecked` (\(e :: Sec.InvalidPackageException) -> warnAndFail (show e)) `Sec.catchChecked` (\(e :: Sec.VerificationError) -> warnAndFail (show e)) _ -> pure True +#endif -- | Fetch a package if we don't have it already. fetchPackage @@ -275,14 +325,21 @@ fetchRepoTarball verbosity' repoCtxt repo pkgid = do createDirectoryIfMissing True dir _ <- downloadURI transport verbosity uri path return path - RepoSecure{} -> repoContextWithSecureRepo repoCtxt repo $ \rep -> do - let dir = packageDir repo pkgid - path = packageFile repo pkgid - createDirectoryIfMissing True dir - Sec.uncheckClientErrors $ do - info verbosity ("Writing " ++ path) - Sec.downloadPackage' rep pkgid path - return path + RepoSecure{} -> +#ifdef __MHS__ + -- Secure repositories are not supported in this build. + repoContextWithSecureRepo repoCtxt repo $ \_ -> + error "unreachable: secure repositories are not supported" +#else + repoContextWithSecureRepo repoCtxt repo $ \rep -> do + let dir = packageDir repo pkgid + path = packageFile repo pkgid + createDirectoryIfMissing True dir + Sec.uncheckClientErrors $ do + info verbosity ("Writing " ++ path) + Sec.downloadPackage' rep pkgid path + return path +#endif -- | Downloads an index file to [config-dir/packages/serv-id] without -- hackage-security. You probably don't want to call this directly; diff --git a/cabal-install/src/Distribution/Client/FileMonitor.hs b/cabal-install/src/Distribution/Client/FileMonitor.hs index 2a6ae7ef79b..a5b2157bc3e 100644 --- a/cabal-install/src/Distribution/Client/FileMonitor.hs +++ b/cabal-install/src/Distribution/Client/FileMonitor.hs @@ -32,7 +32,8 @@ import qualified Data.ByteString.Lazy as BS import qualified Data.Map.Strict as Map import Control.Exception -import Control.Monad +import Control.Monad hiding (forM_, mapM, mapM_, sequence, sequence_) +import Data.Foldable (forM_, mapM_) import Control.Monad.Except ( ExceptT , runExceptT @@ -51,7 +52,8 @@ import Distribution.Simple.FileMonitor.Types import Distribution.Simple.Utils (handleDoesNotExist, writeFileAtomic) import Distribution.Utils.Structured (Tag (..), structuredEncode) -import System.Directory +import Distribution.Compat.Directory +import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS) import System.FilePath import System.IO @@ -429,7 +431,7 @@ withCacheFile -> IO r withCacheFile (FileMonitor{fileMonitorCacheFile}) k = withBinaryFile fileMonitorCacheFile ReadMode $ \hnd -> do - contents <- structuredDecodeTriple <$> BS.hGetContents hnd + contents <- structuredDecodeTriple <$> hGetContentsLBS hnd k contents -- | Helper for writing the cache file. diff --git a/cabal-install/src/Distribution/Client/GZipUtils.hs b/cabal-install/src/Distribution/Client/GZipUtils.hs index 8946ddd946a..112ae24c0c8 100644 --- a/cabal-install/src/Distribution/Client/GZipUtils.hs +++ b/cabal-install/src/Distribution/Client/GZipUtils.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- | -- Module : Distribution.Client.GZipUtils -- Copyright : (c) Dmitry Astapov 2010 @@ -11,16 +12,147 @@ -- be zipped. module Distribution.Client.GZipUtils ( maybeDecompress +#ifdef __MHS__ + , gzipCompress +#endif ) where import Distribution.Client.Compat.Prelude import Prelude () +#ifdef __MHS__ +import Data.ByteString.Lazy (ByteString) +import qualified Data.ByteString as StrictBS +import qualified Data.ByteString.Lazy as BS +import qualified Distribution.Compat.Process as Process +import Distribution.Compat.Directory + ( getTemporaryDirectory + , removeFile + ) +import Distribution.Compat.Internal.TempFile (openBinaryTempFile) +import System.IO + ( hClose + ) +import System.IO.Error (userError) +import System.IO.Unsafe (unsafePerformIO) + +import Control.Exception (bracket) +#else import Codec.Compression.Zlib.Internal import Control.Exception (throw) import Control.Monad.ST.Lazy (ST, runST) import qualified Data.ByteString as Strict import Data.ByteString.Lazy.Internal as BS (ByteString (Chunk, Empty)) +#endif + +#ifdef __MHS__ +-- | Attempts to decompress the @bytes@ when they start with the gzip +-- magic bytes (@1F 8B@), passing them through the external @gzip -dc@ +-- program; anything else is returned as-is. Corrupt gzip input raises +-- an 'IOException'. Callers should make sanity checks to verify that +-- a pass-through result is not, in fact, garbage. +-- +-- This used to also handle raw zlib streams (to deal with http proxies +-- that lie to us and transparently decompress without removing the +-- content-encoding header, see +-- ), but proxy support has +-- been removed and only gzip is used for index files and tarballs, so +-- non-gzip input is now returned untouched. +maybeDecompress :: ByteString -> ByteString +maybeDecompress bs + | hasGzipMagic bs = unsafePerformIO (gunzip bs) + | otherwise = bs + +hasGzipMagic :: ByteString -> Bool +hasGzipMagic bs = BS.take 2 bs == BS.pack [0x1f, 0x8b] + +-- | Decompress gzip data using the external @gzip -dc@ program. +-- +-- The input is staged through a temporary file so that the child only +-- ever reads from the file and writes to its stdout pipe; this avoids +-- any stdin/stdout pipe deadlock. Corrupt input (or a missing @gzip@ +-- program) raises an 'IOException'. The staging handle is binary: +-- 'BS.hPut' on a text-mode handle would re-encode every byte +-- @0x80..0xFF@ as two UTF-8 bytes. +gunzip :: ByteString -> IO ByteString +gunzip input = + bracket + ( do + tmpDir <- getTemporaryDirectory + (path, h) <- openBinaryTempFile tmpDir "cabal-gunzip.gz" + BS.hPut h input + hClose h + return path + ) + (\path -> removeFile path `catchIO` \_ -> return ()) + runGzip + +-- | Compress bytes with the external @gzip -n -c@ program (no embedded +-- file name or timestamp, so the output is deterministic). +gzipCompress :: ByteString -> IO ByteString +gzipCompress input = + bracket + ( do + tmpDir <- getTemporaryDirectory + (path, h) <- openBinaryTempFile tmpDir "cabal-gzip.tar" + BS.hPut h input + hClose h + return path + ) + (\path -> removeFile path `catchIO` \_ -> return ()) + runGzipCompress + +runGzipCompress :: FilePath -> IO ByteString +runGzipCompress path = do + -- Capture discipline: the child is reaped before its outputs are + -- read, so temporary-file redirection is complete by construction. + -- Outputs are read with strict 'StrictBS.readFile' (raw 'c_readb'): + -- lazy 'BS.readFile' needs 'hGetSome', which MicroHs does not + -- implement. + (code, captured) <- + Process.captureProcess + (Process.proc "gzip" ["-n", "-c", path]) + Process.NoInput + out <- BS.fromStrict <$> StrictBS.readFile (Process.capturedOutPath captured) + _ <- evaluate (BS.length out) + err <- readFile (Process.capturedErrPath captured) + _ <- evaluate (length err) + Process.capturedRelease captured + case code of + ExitSuccess -> return out + ExitFailure n -> + throwIO $ + userError $ + "gzip -n -c failed with exit code " + ++ show n + ++ (if null err then "" else ": " ++ err) + +runGzip :: FilePath -> IO ByteString +runGzip path = do + -- Capture discipline: the child is reaped before its outputs are + -- read, so temporary-file redirection is complete by construction. + -- Outputs are read with strict 'StrictBS.readFile' (raw 'c_readb'): + -- lazy 'BS.readFile' needs 'hGetSome', which MicroHs does not + -- implement. + (code, captured) <- + Process.captureProcess + (Process.proc "gzip" ["-dc", path]) + Process.NoInput + out <- BS.fromStrict <$> StrictBS.readFile (Process.capturedOutPath captured) + _ <- evaluate (BS.length out) + err <- readFile (Process.capturedErrPath captured) + _ <- evaluate (length err) + Process.capturedRelease captured + case code of + ExitSuccess -> return out + ExitFailure n -> + throwIO $ + userError $ + "gzip -dc failed with exit code " + ++ show n + ++ (if null err then "" else ": " ++ err) + +#else -- | Attempts to decompress the `bytes' under the assumption that -- "data format" error at the very beginning of the stream means @@ -63,3 +195,4 @@ maybeDecompress bytes = runST (go bytes decompressor) uncons :: ByteString -> (Strict.ByteString, ByteString) uncons Empty = (Strict.empty, Empty) uncons (Chunk c cs) = (c, cs) +#endif diff --git a/cabal-install/src/Distribution/Client/Get.hs b/cabal-install/src/Distribution/Client/Get.hs index 94338f77e40..43b460f0c3b 100644 --- a/cabal-install/src/Distribution/Client/Get.hs +++ b/cabal-install/src/Distribution/Client/Get.hs @@ -71,14 +71,14 @@ import Distribution.PackageDescription.PrettyPrint import Distribution.Solver.Types.Machine (always) import Distribution.Solver.Types.SourcePackage -import Control.Monad (mapM_) +import Data.Foldable (mapM_) import qualified Data.Map as Map import qualified Data.Text as Text import Distribution.Client.Errors import Distribution.Utils.NubList ( fromNubList ) -import System.Directory +import Distribution.Compat.Directory ( createDirectoryIfMissing , doesDirectoryExist , doesFileExist diff --git a/cabal-install/src/Distribution/Client/Glob.hs b/cabal-install/src/Distribution/Client/Glob.hs index c94b91196fa..8000ae0f94f 100644 --- a/cabal-install/src/Distribution/Client/Glob.hs +++ b/cabal-install/src/Distribution/Client/Glob.hs @@ -24,7 +24,7 @@ import Distribution.Simple.Glob.Internal , GlobPieces ) -import System.Directory +import Distribution.Compat.Directory import System.FilePath -------------------------------------------------------------------------------- diff --git a/cabal-install/src/Distribution/Client/GlobalFlags.hs b/cabal-install/src/Distribution/Client/GlobalFlags.hs index 51640847104..af3f0790c56 100644 --- a/cabal-install/src/Distribution/Client/GlobalFlags.hs +++ b/cabal-install/src/Distribution/Client/GlobalFlags.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RecordWildCards #-} @@ -48,6 +49,7 @@ import Control.Concurrent , modifyMVar , newMVar ) +#ifndef __MHS__ import qualified Data.Map as Map import qualified Data.Text as Text import Network.URI @@ -55,11 +57,14 @@ import Network.URI , uriPath , uriScheme ) +#endif import System.FilePath ( isAbsolute , () ) +import System.IO.Error (userError) +#ifndef __MHS__ import qualified Distribution.Client.Security.DNS as Sec.DNS import qualified Distribution.Client.Security.HTTP as Sec.HTTP import qualified Hackage.Security.Client as Sec @@ -68,6 +73,7 @@ import qualified Hackage.Security.Client.Repository.Local as Sec.Local import qualified Hackage.Security.Client.Repository.Remote as Sec.Remote import qualified Hackage.Security.Util.Path as Sec import qualified Hackage.Security.Util.Pretty as Sec +#endif -- ------------------------------------------------------------ @@ -140,18 +146,40 @@ data RepoContext = RepoContext , repoContextWithSecureRepo :: forall a . Repo +#ifdef __MHS__ + -> (SecureRepository SecureRepoTag -> IO a) +#else -> (forall down. Sec.Repository down -> IO a) +#endif -> IO a -- ^ Get the (initialized) secure repo -- +#ifdef __MHS__ + -- Secure repositories are not supported in this MHS build: using this + -- accessor always fails with an error. + -- +#endif -- (the 'Repo' type itself is stateless and must remain so, because it -- must be serializable) , repoContextIgnoreExpiry :: Bool -- ^ Should we ignore expiry times (when checking security)? } +#ifdef __MHS__ +-- | A secure repository handle. +-- +-- Secure repositories are not supported in this build, so this type has +-- no constructors: 'repoContextWithSecureRepo' always fails. +data SecureRepository down + +-- | Tag for 'SecureRepository'. The stub accessor above is monomorphic +-- in the tag (instead of rank-2 as upstream) because GHC rejects +-- rank-2 record selectors used as functions. +data SecureRepoTag +#else -- | Wrapper around 'Repository', hiding the type argument data SecureRepo = forall down. SecureRepo (Sec.Repository down) +#endif withRepoContext :: Verbosity -> GlobalFlags -> (RepoContext -> IO a) -> IO a withRepoContext verbosity globalFlags = @@ -188,6 +216,20 @@ withRepoContext' "file+noindex " ++ unRepoName (localRepoName local) ++ " repository path is not absolute; this is fragile, and not recommended" transportRef <- newMVar Nothing +#ifdef __MHS__ + callback + RepoContext + { repoContextRepos = + allRemoteRepos + ++ allLocalNoIndexRepos + , repoContextGetTransport = getTransport transportRef + , repoContextWithSecureRepo = \_ _ -> + throwIO $ + userError + "Secure repositories are not supported in this build of cabal-install." + , repoContextIgnoreExpiry = fromMaybe False ignoreExpiry + } +#else let httpLib = Sec.HTTP.transportAdapter verbosity @@ -202,10 +244,13 @@ withRepoContext' , repoContextWithSecureRepo = withSecureRepo secureRepos' , repoContextIgnoreExpiry = fromMaybe False ignoreExpiry } +#endif where +#ifndef __MHS__ secureRemoteRepos = [(remote, cacheDir) | RepoSecure remote cacheDir <- allRemoteRepos] +#endif allRemoteRepos :: [Repo] allRemoteRepos = [ (if isSecure then RepoSecure else RepoRemote) remote cacheDir @@ -231,6 +276,7 @@ withRepoContext' Nothing -> configureTransport verbosity extraPaths httpTransport return (Just transport, transport) +#ifndef __MHS__ withSecureRepo :: Map Repo SecureRepo -> Repo @@ -240,7 +286,9 @@ withRepoContext' case Map.lookup repo secureRepos of Just (SecureRepo secureRepo) -> callback secureRepo Nothing -> throwIO $ userError "repoContextWithSecureRepo: unknown repo" +#endif +#ifndef __MHS__ -- | Initialize the provided secure repositories -- -- Assumed invariant: `remoteRepoSecure` should be set for all these repos. @@ -343,3 +391,4 @@ initSecureRepo verbosity httpLib RemoteRepo{..} cachePath = \callback -> do -- is thrown will of course be shown. logTUF :: Sec.LogMessage -> IO () logTUF = info verbosity . Sec.pretty +#endif diff --git a/cabal-install/src/Distribution/Client/Haddock.hs b/cabal-install/src/Distribution/Client/Haddock.hs index 0bf3ee11857..1052f9aafa0 100644 --- a/cabal-install/src/Distribution/Client/Haddock.hs +++ b/cabal-install/src/Distribution/Client/Haddock.hs @@ -43,7 +43,7 @@ import Distribution.Simple.Utils , withTempDirectory ) import Distribution.Version (mkVersion, orLaterVersion) -import System.Directory (createDirectoryIfMissing, renameFile) +import Distribution.Compat.Directory (createDirectoryIfMissing, renameFile) import System.FilePath (splitFileName, ()) regenerateHaddockIndex diff --git a/cabal-install/src/Distribution/Client/HashValue.hs b/cabal-install/src/Distribution/Client/HashValue.hs index a3a67c9ff29..dead5ee7b10 100644 --- a/cabal-install/src/Distribution/Client/HashValue.hs +++ b/cabal-install/src/Distribution/Client/HashValue.hs @@ -1,6 +1,9 @@ +{-# LANGUAGE CPP #-} + module Distribution.Client.HashValue ( HashValue , hashValue + , unHashValue , truncateHash , showHashValue , readFileHashValue @@ -11,14 +14,36 @@ import Control.Monad ((<=<)) import Distribution.Client.Compat.Prelude import Prelude () -import qualified Hackage.Security.Client as Sec - -import qualified Crypto.Hash.SHA256 as SHA256 +import qualified Data.ByteString as BS +#ifdef __MHS__ +import qualified Distribution.Client.Compat.Base16 as Base16 +#else import qualified Data.ByteString.Base16 as Base16 -import qualified Data.ByteString.Char8 as BS +#endif +import qualified Data.ByteString.Char8 as BSChar8 import qualified Data.ByteString.Lazy.Char8 as LBS +import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS) + +#ifndef __MHS__ +import qualified Hackage.Security.Client as Sec +import qualified Crypto.Hash.SHA256 as SHA256 +#endif import System.IO (IOMode (..), withBinaryFile) +import System.IO.Unsafe (unsafePerformIO) + +#ifdef __MHS__ +import Foreign.C.Types (CSize (..), CUChar (..)) +import Foreign.Marshal.Alloc (allocaBytes) +import Foreign.Ptr (Ptr, castPtr) + +-- MicroHs cannot use the @cryptohash-sha256@ package, so the C helper +-- @cabal_sha256@ in @cbits/mhs_sha256.c@ is used instead. On Apple +-- platforms that helper uses CommonCrypto's @CC_SHA256@ (in +-- @libSystem@, no extra library needed); elsewhere it uses OpenSSL's +-- @SHA256()@ (needs @-lcrypto@ at link time). +foreign import ccall "mhs_sha256.h cabal_sha256" c_SHA256 :: Ptr CUChar -> CSize -> Ptr CUChar -> IO (Ptr CUChar) +#endif ----------------------------------------------- -- The specific choice of hash implementation @@ -47,16 +72,38 @@ instance Structured HashValue -- | Hash some data. Currently uses SHA256. hashValue :: LBS.ByteString -> HashValue +#ifdef __MHS__ +hashValue = HashValue . sha256Bytes . BS.concat . LBS.toChunks +#else hashValue = HashValue . SHA256.hashlazy +#endif + +-- | Project a 'HashValue' to its raw digest bytes. +unHashValue :: HashValue -> BS.ByteString +unHashValue (HashValue digest) = digest showHashValue :: HashValue -> String -showHashValue (HashValue digest) = BS.unpack (Base16.encode digest) +showHashValue (HashValue digest) = BSChar8.unpack (Base16.encode digest) -- | Hash the content of a file. Uses SHA256. readFileHashValue :: FilePath -> IO HashValue readFileHashValue tarball = - withBinaryFile tarball ReadMode (evaluate . hashValue <=< LBS.hGetContents) + withBinaryFile tarball ReadMode (evaluate . hashValue <=< hGetContentsLBS) +#ifdef __MHS__ +-- | Convert a base16-encoded hash string from TUF metadata into a +-- 'HashValue'. +-- +-- Note that TUF hashes don't necessarily have to be SHA256, since it can +-- support new algorithms in future. +hashFromTUF :: String -> HashValue +hashFromTUF hashstr = + -- TODO: [code cleanup] either we should get TUF to use raw bytestrings or + -- perhaps we should also just use a base16 string as the internal rep. + case Base16.decode (BSChar8.pack hashstr) of + Right hash -> HashValue hash + Left _ -> error "hashFromTUF: cannot decode base16" +#else -- | Convert a hash from TUF metadata into a 'PackageSourceHash'. -- -- Note that TUF hashes don't necessarily have to be SHA256, since it can @@ -65,9 +112,10 @@ hashFromTUF :: Sec.Hash -> HashValue hashFromTUF (Sec.Hash hashstr) = -- TODO: [code cleanup] either we should get TUF to use raw bytestrings or -- perhaps we should also just use a base16 string as the internal rep. - case Base16.decode (BS.pack hashstr) of + case Base16.decode (BSChar8.pack hashstr) of Right hash -> HashValue hash Left _ -> error "hashFromTUF: cannot decode base16" +#endif -- | Truncate a 32 byte SHA256 hash to -- @@ -75,3 +123,25 @@ hashFromTUF (Sec.Hash hashstr) = -- Or even 4 bytes for 'hashedInstalledPackageIdShort' truncateHash :: Int -> HashValue -> HashValue truncateHash n (HashValue h) = HashValue (BS.take n h) + +#ifdef __MHS__ +----------------------------------------------- +-- SHA256 via statically linked system libcrypto +-- +-- MicroHs cannot use the @cryptohash-sha256@ package, so the system +-- libcrypto (@SHA256()@) is used through a foreign import instead. +-- This needs @-lcrypto@ at link time. +-- + +sha256DigestSize :: Int +sha256DigestSize = 32 + +-- | One-shot SHA256 over a strict 'BS.ByteString', via the statically +-- linked system libcrypto (see the 'foreign import' above). +sha256Bytes :: BS.ByteString -> BS.ByteString +sha256Bytes input = unsafePerformIO $ + BS.useAsCStringLen input $ \(ptr, len) -> + allocaBytes sha256DigestSize $ \out -> do + _ <- c_SHA256 (castPtr ptr) (fromIntegral len) (castPtr out) + BS.packCStringLen (castPtr out, sha256DigestSize) +#endif diff --git a/cabal-install/src/Distribution/Client/HttpUtils.hs b/cabal-install/src/Distribution/Client/HttpUtils.hs index 4d23a88ef52..b541cc7a22b 100644 --- a/cabal-install/src/Distribution/Client/HttpUtils.hs +++ b/cabal-install/src/Distribution/Client/HttpUtils.hs @@ -1,9 +1,15 @@ +{-# LANGUAGE CPP #-} -- | Separate module for HTTP actions, using a proxy server if one exists. module Distribution.Client.HttpUtils ( DownloadResult (..) , configureTransport , HttpTransport (..) , HttpCode +#ifdef __MHS__ + , Header (..) + , HeaderName (..) + , headerNameString +#endif , downloadURI , transportCheckHttps , remoteRepoCheckHttps @@ -11,11 +17,21 @@ module Distribution.Client.HttpUtils , isOldHackageURI ) where +#ifdef __MHS__ +import Distribution.Client.Compat.Prelude +#else import Distribution.Client.Compat.Prelude hiding (Proxy (..)) +#endif import Distribution.Utils.Generic import Prelude () import qualified Control.Exception as Exception +#ifdef __MHS__ +import Distribution.Client.HashValue + ( hashValue + , unHashValue + ) +#endif import Distribution.Client.Types ( RemoteRepo (..) , unRepoName @@ -63,6 +79,7 @@ import Distribution.System , buildOS ) import Distribution.Utils.String (trim) +#ifndef __MHS__ import Network.Browser ( browse , request @@ -82,17 +99,26 @@ import Network.HTTP , lookupHeader ) import Network.HTTP.Proxy (Proxy (..), fetchProxy) +#endif import Network.URI ( URI (..) , URIAuth (..) , uriToString ) import Numeric (showHex) +#ifdef __MHS__ +import Distribution.Compat.Directory + ( canonicalizePath + , doesFileExist + , renameFile + ) +#else import System.Directory ( canonicalizePath , doesFileExist , renameFile ) +#endif import System.FilePath ( takeDirectory , takeFileName @@ -107,20 +133,29 @@ import System.IO , hGetContents , withFile ) +#ifndef __MHS__ import System.IO.Error ( isDoesNotExistError ) +#endif import System.Random (randomRIO) +#ifndef __MHS__ import qualified Crypto.Hash.SHA256 as SHA256 +#endif import qualified Data.ByteString as BS +#ifdef __MHS__ +import qualified Distribution.Client.Compat.Base16 as Base16 +#else import qualified Data.ByteString.Base16 as Base16 +#endif import qualified Data.ByteString.Char8 as BS8 import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Lazy.Char8 as LBS8 import qualified Data.Char as Char import Distribution.Client.Errors import qualified Distribution.Compat.CharParsing as P +import Distribution.Compat.Internal.LazyByteString (readFileLBS) ------------------------------------------------------------------------------ -- Downloading a URI, given an HttpTransport @@ -140,6 +175,73 @@ data DownloadCheck NeedsDownload (Maybe BS.ByteString) deriving (Eq) +#ifdef __MHS__ +------------------------------------------------------------------------------ +-- HTTP headers +-- +-- Local replacement for the @HTTP@ package's 'Network.HTTP.Header' +-- type, so that the external-program transports below do not need the +-- @HTTP@ package (in particular its pure-Haskell @plainHttpTransport@ +-- and @Network.Browser@ proxy handling, which have been removed). +-- + +-- | An HTTP header: a name and its value. +data Header = Header HeaderName String + deriving (Eq) + +instance Show Header where + showsPrec _ (Header name value) = + showString (headerNameString name ++ ": " ++ value) + +-- | An HTTP header name. +data HeaderName + = HdrAccept + | HdrAuthorization + | HdrCacheControl + | HdrConnection + | HdrContentEncoding + | HdrContentLength + | HdrContentType + | HdrDate + | HdrETag + | HdrExpect + | HdrHost + | HdrIfModifiedSince + | HdrIfNoneMatch + | HdrRange + | HdrReferer + | HdrTransferEncoding + | HdrUserAgent + | HdrCustom String + deriving (Eq) + +instance Show HeaderName where + showsPrec _ name = showString (headerNameString name) + +-- | The canonical rendering of a 'HeaderName', e.g. for @--header@ +-- arguments to external download programs. +headerNameString :: HeaderName -> String +headerNameString name = case name of + HdrAccept -> "Accept" + HdrAuthorization -> "Authorization" + HdrCacheControl -> "Cache-Control" + HdrConnection -> "Connection" + HdrContentEncoding -> "Content-Encoding" + HdrContentLength -> "Content-Length" + HdrContentType -> "Content-Type" + HdrDate -> "Date" + HdrETag -> "ETag" + HdrExpect -> "Expect" + HdrHost -> "Host" + HdrIfModifiedSince -> "If-Modified-Since" + HdrIfNoneMatch -> "If-None-Match" + HdrRange -> "Range" + HdrReferer -> "Referer" + HdrTransferEncoding -> "Transfer-Encoding" + HdrUserAgent -> "User-Agent" + HdrCustom s -> s +#endif + downloadURI :: HttpTransport -> Verbosity @@ -163,8 +265,12 @@ downloadURI transport verbosity uri path = do then case sha256parsed of -- we know the hash, and target exists Right expected | targetExists -> do - contents <- LBS.readFile path + contents <- readFileLBS path +#ifdef __MHS__ + let actual = unHashValue (hashValue contents) +#else let actual = SHA256.hashlazy contents +#endif if expected == actual then return Downloaded else return (NeedsDownload (Just expected)) @@ -182,6 +288,12 @@ downloadURI transport verbosity uri path = do then return (CheckETag etagPath) else return (NeedsDownload Nothing) +#ifdef __MHS__ + case downloadCheck of + Downloaded -> return FileAlreadyInCache + CheckETag etag -> makeDownload transport Nothing (Just etag) + NeedsDownload hash -> makeDownload transport hash Nothing +#else -- Only use the external http transports if we actually have to -- (or have been told to do so) let transport' @@ -195,6 +307,7 @@ downloadURI transport verbosity uri path = do Downloaded -> return FileAlreadyInCache CheckETag etag -> makeDownload transport' Nothing (Just etag) NeedsDownload hash -> makeDownload transport' hash Nothing +#endif where makeDownload :: HttpTransport -> Maybe BS8.ByteString -> Maybe String -> IO DownloadResult makeDownload transport' sha256 etag = withTempFileName (takeDirectory path) (takeFileName path) $ \tmpFile -> do @@ -205,8 +318,12 @@ downloadURI transport verbosity uri path = do case result of -- if we have hash, we don't care about etag. (200, _) | Just expected <- sha256 -> do - contents <- LBS.readFile tmpFile + contents <- readFileLBS tmpFile +#ifdef __MHS__ + let actual = unHashValue (hashValue contents) +#else let actual = SHA256.hashlazy contents +#endif unless (actual == expected) $ dieWithException verbosity $ MakeDownload uri expected actual @@ -397,12 +514,14 @@ supportedTransports = , True , \db -> powershellTransport <$> lookupProgram prog db ) +#ifndef __MHS__ , ( "plain-http" , Nothing , False , \_ -> Just plainHttpTransport ) +#endif ] configureTransport :: Verbosity -> [FilePath] -> Maybe String -> IO HttpTransport @@ -440,8 +559,18 @@ configureTransport verbosity extraPath Nothing = do | (name, _, _, mkTrans) <- supportedTransports , transport <- maybeToList (mkTrans progdb) ] +#ifdef __MHS__ + (name, transport) <- case safeHead availableTransports of + Just selected -> return selected + Nothing -> + dieWithException verbosity $ + UnknownHttpTransportSpecified + "(automatic selection)" + [name' | (name', _, _, _) <- supportedTransports] +#else let (name, transport) = fromMaybe ("plain-http", plainHttpTransport) (safeHead availableTransports) +#endif debug verbosity $ "Selected http transport implementation: " ++ name return transport{transportManuallySelected = False} @@ -967,6 +1096,7 @@ powershellTransport prog = , "}" ] +#ifndef __MHS__ ------------------------------------------------------------------------------ -- The builtin plain HttpTransport -- @@ -1019,7 +1149,7 @@ plainHttpTransport = return (convertRspCode (rspCode resp), rspErrorString resp) puthttpfile verbosity uri path auth headers = do - body <- LBS8.readFile path + body <- readFileLBS path let req = Request { rqURI = uri @@ -1066,6 +1196,7 @@ plainHttpTransport = fixupEmptyProxy (Proxy uri _) | null uri = NoProxy fixupEmptyProxy p = p +#endif ------------------------------------------------------------------------------ -- Common stuff used by multiple transport impls @@ -1093,7 +1224,7 @@ statusParseFail verbosity uri r = generateMultipartBody :: FilePath -> IO (LBS.ByteString, String) generateMultipartBody path = do - content <- LBS.readFile path + content <- readFileLBS path boundary <- genBoundary let !body = formatBody content (LBS8.pack boundary) return (body, boundary) diff --git a/cabal-install/src/Distribution/Client/InLibrary.hs b/cabal-install/src/Distribution/Client/InLibrary.hs index f8a4074d200..3f44475198e 100644 --- a/cabal-install/src/Distribution/Client/InLibrary.hs +++ b/cabal-install/src/Distribution/Client/InLibrary.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DuplicateRecordFields #-} module Distribution.Client.InLibrary @@ -53,7 +54,16 @@ import Distribution.Verbosity ) import Distribution.Types.HookedBuildInfo (emptyHookedBuildInfo) -import System.Directory (canonicalizePath) +import Distribution.Compat.Directory (canonicalizePath) + +-- Note [MHS support] +-- ~~~~~~~~~~~~~~~~~~ +-- When cabal-install itself is built with MHS (MicroHS), the in-library +-- setup method is unavailable (see Note [MHS support] in +-- "Distribution.Client.SetupWrapper", which always selects the external +-- setup method). Under @__MHS__@ this module therefore only provides +-- stubs with the same types as the GHC implementation, so that callers +-- keep typechecking while the stubs are never invoked at runtime. -------------------------------------------------------------------------------- -- Configure @@ -131,6 +141,10 @@ configure :: LibraryConfigureInputs -> Cabal.ConfigFlags -> IO LocalBuildInfo +#ifdef __MHS__ +configure _ _ = + error "Distribution.Client.InLibrary.configure: in-library setup is not supported under MHS" +#else configure LibraryConfigureInputs { verbosityHandles = verbHandles @@ -227,6 +241,7 @@ configure Just pkgFile -> return pkgFile Nothing -> relativeSymbolicPath <$> tryFindPackageDesc verbosity mbWorkDir return $ lbi1{pkgDescrFile = Just pkgDescrFilePath} +#endif -------------------------------------------------------------------------------- -- Build @@ -237,6 +252,10 @@ build -> LocalBuildInfo -> [String] -> IO [MonitorFilePath] +#ifdef __MHS__ +build _ _ _ _ = + error "Distribution.Client.InLibrary.build: in-library setup is not supported under MHS" +#else build verbHandles flags lbi _args = build_setupHooks (preBuildHook, postBuildHook) verbHandles pkgDescr lbi flags Cabal.knownSuffixHandlers where @@ -254,6 +273,7 @@ build verbHandles flags lbi _args = bt = PD.buildType pkgDescr mbWorkDir = mbWorkDirLBI lbi distPref = Cabal.fromFlag $ Cabal.buildDistPref flags +#endif -------------------------------------------------------------------------------- -- Haddock @@ -264,6 +284,10 @@ haddock -> LocalBuildInfo -> [String] -> IO [MonitorFilePath] +#ifdef __MHS__ +haddock _ _ _ _ = + error "Distribution.Client.InLibrary.haddock: in-library setup is not supported under MHS" +#else haddock verbHandles flags lbi _args = haddock_setupHooks preBuildHook verbHandles pkgDescr lbi Cabal.knownSuffixHandlers flags where @@ -272,6 +296,7 @@ haddock verbHandles flags lbi _args = bt = PD.buildType pkgDescr mbWorkDir = mbWorkDirLBI lbi distPref = Cabal.fromFlag $ Cabal.haddockDistPref flags +#endif -------------------------------------------------------------------------------- -- Repl @@ -282,6 +307,10 @@ repl -> LocalBuildInfo -> [String] -> IO [MonitorFilePath] +#ifdef __MHS__ +repl _ _ _ _ = + error "Distribution.Client.InLibrary.repl: in-library setup is not supported under MHS" +#else repl verbHandles flags lbi _args = repl_setupHooks preBuildHook verbHandles pkgDescr lbi flags Cabal.knownSuffixHandlers [] where @@ -290,6 +319,7 @@ repl verbHandles flags lbi _args = bt = PD.buildType pkgDescr mbWorkDir = mbWorkDirLBI lbi distPref = Cabal.fromFlag $ Cabal.replDistPref flags +#endif -------------------------------------------------------------------------------- -- Copy @@ -300,6 +330,10 @@ copy -> LocalBuildInfo -> [String] -> IO () +#ifdef __MHS__ +copy _ _ _ _ = + error "Distribution.Client.InLibrary.copy: in-library setup is not supported under MHS" +#else copy verbHandles flags lbi _args = install_setupHooks hooks verbHandles pkgDescr lbi flags where @@ -309,6 +343,7 @@ copy verbHandles flags lbi _args = bt = PD.buildType pkgDescr mbWorkDir = mbWorkDirLBI lbi distPref = Cabal.fromFlag $ Cabal.copyDistPref flags +#endif -------------------------------------------------------------------------------- -- Test, bench, register. @@ -321,10 +356,15 @@ test -> LocalBuildInfo -> [String] -> IO () +#ifdef __MHS__ +test _ _ _ _ = + error "Distribution.Client.InLibrary.test: in-library setup is not supported under MHS" +#else test verb flags lbi args = Cabal.test args verb pkgDescr lbi flags where pkgDescr = localPkgDescr lbi +#endif bench :: VerbosityHandles @@ -333,7 +373,11 @@ bench -> [String] -> IO () bench verb flags lbi args = +#ifdef __MHS__ + error "Distribution.Client.InLibrary.bench: in-library setup is not supported under MHS" +#else Cabal.bench args verb pkgDescr lbi flags +#endif where pkgDescr = localPkgDescr lbi @@ -342,6 +386,11 @@ register -> LocalBuildInfo -> [String] -> IO () +#ifdef __MHS__ +register _ _ _ = + error "Distribution.Client.InLibrary.register: in-library setup is not supported under MHS" +#else register flags lbi _args = Cabal.register pkgDescr lbi flags where pkgDescr = localPkgDescr lbi +#endif diff --git a/cabal-install/src/Distribution/Client/IndexUtils.hs b/cabal-install/src/Distribution/Client/IndexUtils.hs index 70f1119c1ea..41448553edd 100644 --- a/cabal-install/src/Distribution/Client/IndexUtils.hs +++ b/cabal-install/src/Distribution/Client/IndexUtils.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} @@ -49,9 +50,13 @@ module Distribution.Client.IndexUtils import Distribution.Client.Compat.Prelude import Prelude () +#ifdef __MHS__ +import qualified Distribution.Client.Compat.Tar as Tar +#else import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Archive.Tar.Index as Tar +#endif import Distribution.Client.IndexUtils.ActiveRepos import Distribution.Client.IndexUtils.IndexState import Distribution.Client.IndexUtils.Timestamp @@ -116,14 +121,18 @@ import Distribution.Solver.Types.PackageIndex (PackageIndex) import qualified Distribution.Solver.Types.PackageIndex as PackageIndex import Distribution.Solver.Types.SourcePackage +#ifndef __MHS__ import qualified Codec.Compression.GZip as GZip +#endif import Control.Exception import qualified Data.ByteString.Char8 as BSS import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy as BS +#ifndef __MHS__ import Data.Either ( rights ) +#endif import Data.List (stripPrefix) import qualified Data.Map as Map import qualified Data.Set as Set @@ -132,10 +141,15 @@ import Distribution.Client.Utils ( byteStringToFilePath , tryReadAddSourcePackageDesc ) +import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS, readFileLBS) import Distribution.Compat.Time (getFileAge, getModTime) import Distribution.Utils.Generic (fstOf3) import Distribution.Utils.Structured (Structured (..), nominalStructure, structuredDecodeFileOrFail, structuredEncodeFile) +#ifdef __MHS__ +import Distribution.Compat.Directory (doesDirectoryExist, doesFileExist, listDirectory) +#else import System.Directory (doesDirectoryExist, doesFileExist, listDirectory) +#endif import System.FilePath ( normalise , splitDirectories @@ -151,8 +165,10 @@ import System.IO.Error (isDoesNotExistError) import System.IO.Unsafe (unsafeInterleaveIO) import Distribution.Client.Errors +#ifndef __MHS__ import qualified Hackage.Security.Client as Sec import qualified Hackage.Security.Util.Some as Sec +#endif -- | Reduced-verbosity version of 'Configure.getInstalledPackages' getInstalledPackages @@ -775,6 +791,7 @@ lazySequence = unsafeInterleaveIO . go xs' <- lazySequence xs return (x' : xs') +#ifndef __MHS__ -- | A lazy unfolder for lookup operations which return the current -- value and (possibly) the next key lazyUnfold :: (k -> IO (v, Maybe k)) -> k -> IO [(k, v)] @@ -787,6 +804,7 @@ lazyUnfold step = goLazy . Just (v, mk') <- step k vs' <- goLazy mk' return ((k, v) : vs') +#endif -- | Which index do we mean? data Index @@ -859,6 +877,11 @@ withIndexEntries -> ([NoIndexCacheEntry] -> IO a) -> IO a withIndexEntries _ (RepoIndex repoCtxt repo@RepoSecure{}) callback _ = +#ifdef __MHS__ + -- Secure repositories are not supported in this build. + repoContextWithSecureRepo repoCtxt repo $ \_ -> + error "unreachable: secure repositories are not supported" +#else repoContextWithSecureRepo repoCtxt repo $ \repoSecure -> Sec.withIndex repoSecure $ \Sec.IndexCallbacks{..} -> do -- Incrementally (lazily) read all the entries in the tar file in order, @@ -891,6 +914,7 @@ withIndexEntries _ (RepoIndex repoCtxt repo@RepoSecure{}) callback _ = timestamp = epochTimeToTimestamp $ Sec.indexEntryTime sie +#endif withIndexEntries verbosity (RepoIndex _repoCtxt (RepoLocalNoIndex (LocalRepo name localDir _) _cacheDir)) _ callback = do dirContents <- listDirectory localDir let contentSet = Set.fromList dirContents @@ -899,7 +923,7 @@ withIndexEntries verbosity (RepoIndex _repoCtxt (RepoLocalNoIndex (LocalRepo nam case isTarGz file of Nothing | isPreferredVersions file -> do - contents <- BS.readFile (localDir file) + contents <- readFileLBS (localDir file) let versionPreferencesParsed = parsePreferredVersionsWarnings contents let (warnings, versionPreferences) = partitionEithers versionPreferencesParsed unless (null warnings) $ do @@ -924,8 +948,12 @@ withIndexEntries verbosity (RepoIndex _repoCtxt (RepoLocalNoIndex (LocalRepo nam Just pkgId -> do let tarFile = localDir file -- check for the right named .cabal file in the compressed tarball - tarGz <- BS.readFile tarFile + tarGz <- readFileLBS tarFile +#ifdef __MHS__ + let tar = maybeDecompress tarGz +#else let tar = GZip.decompress tarGz +#endif entries = Tar.read tar expectFilename = prettyShow pkgId FilePath. prettyShow (packageName pkgId) ++ ".cabal" @@ -1019,8 +1047,8 @@ withIndexEntries verbosity (RepoIndex _repoCtxt (RepoLocalNoIndex (LocalRepo nam _ -> pure Nothing withIndexEntries verbosity index callback _ = do -- non-secure repositories - withFile (indexFile index) ReadMode $ \h -> do - bs <- maybeDecompress `fmap` BS.hGetContents h + withBinaryFile (indexFile index) ReadMode $ \h -> do + bs <- maybeDecompress `fmap` hGetContentsLBS h pkgsOrPrefs <- lazySequence $ parsePackageIndex verbosity bs callback $ map toCache (catMaybes pkgsOrPrefs) where @@ -1466,7 +1494,7 @@ read00IndexCacheEntry = \line -> | otherwise = Nothing parseVer str vs = - case BSS.readInt str of + case bssReadInt str of Nothing -> Nothing Just (v, str') -> case BSS.uncons str' of Just ('.', str'') -> parseVer str'' (v : vs) @@ -1474,11 +1502,29 @@ read00IndexCacheEntry = \line -> Nothing -> Just (mkVersion (reverse (v : vs))) parseBlockNo str = - case BSS.readInt str of + case bssReadInt str of Just (blockno, remainder) | BSS.null remainder -> Just (fromIntegral blockno) _ -> Nothing +#ifdef __MHS__ + bssReadInt :: BSS.ByteString -> Maybe (Int, BSS.ByteString) + bssReadInt bs = + case BSS.uncons bs of + Just ('-', bs') -> first negate <$> readUint bs' + Just ('+', bs') -> readUint bs' + _ -> readUint bs + where + readUint s = + let (digits, rest) = BSS.span isDigit s + in if BSS.null digits + then Nothing + else Just (foldl' (\acc c -> acc * 10 + (ord c - ord '0')) 0 (BSS.unpack digits), rest) +#else + bssReadInt :: BSS.ByteString -> Maybe (Int, BSS.ByteString) + bssReadInt = BSS.readInt +#endif + parseRefType str = case BSS.uncons str of Just (typeCode, remainder) diff --git a/cabal-install/src/Distribution/Client/IndexUtils/IndexState.hs b/cabal-install/src/Distribution/Client/IndexUtils/IndexState.hs index 10d531f7fe1..f663cbbe81e 100644 --- a/cabal-install/src/Distribution/Client/IndexUtils/IndexState.hs +++ b/cabal-install/src/Distribution/Client/IndexUtils/IndexState.hs @@ -16,6 +16,7 @@ module Distribution.Client.IndexUtils.IndexState ) where import Distribution.Client.Compat.Prelude +import Prelude () import Distribution.Client.IndexUtils.Timestamp (Timestamp) import Distribution.Client.Types.RepoName (RepoName (..)) diff --git a/cabal-install/src/Distribution/Client/IndexUtils/Timestamp.hs b/cabal-install/src/Distribution/Client/IndexUtils/Timestamp.hs index 5f70cfd6b0e..1ad4e57f651 100644 --- a/cabal-install/src/Distribution/Client/IndexUtils/Timestamp.hs +++ b/cabal-install/src/Distribution/Client/IndexUtils/Timestamp.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} @@ -24,15 +25,24 @@ import Prelude (read) import Data.Time (UTCTime (..), fromGregorianValid, makeTimeOfDayValid, showGregorian, timeOfDayToTime, timeToTimeOfDay) import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) -import qualified Codec.Archive.Tar.Entry as Tar import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp -- | UNIX timestamp (expressed in seconds since unix epoch, i.e. 1970). -data Timestamp = NoTimestamp | TS Int64 -- Tar.EpochTime +data Timestamp = NoTimestamp | TS Int64 +#ifdef __MHS__ + -- MicroHs cannot derive 'NFData' (no Generic-based default method), + -- so spell out the trivial instance. + deriving (Eq, Ord, Show, Generic) + +instance NFData Timestamp where + rnf NoTimestamp = () + rnf (TS t) = rnf t +#else deriving (Eq, Ord, NFData, Show, Generic) +#endif -epochTimeToTimestamp :: Tar.EpochTime -> Timestamp +epochTimeToTimestamp :: Int64 -> Timestamp epochTimeToTimestamp = TS timestampToUTCTime :: Timestamp -> Maybe UTCTime diff --git a/cabal-install/src/Distribution/Client/Init/FileCreators.hs b/cabal-install/src/Distribution/Client/Init/FileCreators.hs index be9f1ff9f60..8f38c477776 100644 --- a/cabal-install/src/Distribution/Client/Init/FileCreators.hs +++ b/cabal-install/src/Distribution/Client/Init/FileCreators.hs @@ -26,7 +26,7 @@ module Distribution.Client.Init.FileCreators ) where import Distribution.Client.Compat.Prelude hiding (empty, head, readFile, writeFile) -import Prelude hiding (readFile, writeFile) +import Prelude () import qualified Data.Set as Set (member) diff --git a/cabal-install/src/Distribution/Client/Init/Format.hs b/cabal-install/src/Distribution/Client/Init/Format.hs index 078b1b67eee..6eb05f4bf1e 100644 --- a/cabal-install/src/Distribution/Client/Init/Format.hs +++ b/cabal-install/src/Distribution/Client/Init/Format.hs @@ -41,6 +41,7 @@ import Distribution.Pretty import qualified Distribution.SPDX.License as SPDX import Distribution.Simple.Utils hiding (cabalVersion) import Distribution.Solver.Compat.Prelude hiding (empty) +import Prelude () import Distribution.Utils.Path import Text.PrettyPrint diff --git a/cabal-install/src/Distribution/Client/Init/NonInteractive/Command.hs b/cabal-install/src/Distribution/Client/Init/NonInteractive/Command.hs index e25d5293149..73ed55181ba 100644 --- a/cabal-install/src/Distribution/Client/Init/NonInteractive/Command.hs +++ b/cabal-install/src/Distribution/Client/Init/NonInteractive/Command.hs @@ -474,7 +474,7 @@ buildToolsHeuristics -> CabalSpecVersion -> m [Dependency] buildToolsHeuristics flags fp v = case buildTools flags of - Flag{} -> getBuildTools flags + Flag _ -> getBuildTools flags NoFlag -> retrieveBuildTools v fp -- | Retrieve the list of dependencies diff --git a/cabal-install/src/Distribution/Client/Init/NonInteractive/Heuristics.hs b/cabal-install/src/Distribution/Client/Init/NonInteractive/Heuristics.hs index 789bde1619e..634b2972dbc 100644 --- a/cabal-install/src/Distribution/Client/Init/NonInteractive/Heuristics.hs +++ b/cabal-install/src/Distribution/Client/Init/NonInteractive/Heuristics.hs @@ -28,6 +28,7 @@ module Distribution.Client.Init.NonInteractive.Heuristics ) where import Distribution.Client.Compat.Prelude hiding (many, readFile, (<|>)) +import Prelude () import Distribution.Simple.Setup (fromFlagOrDefault) diff --git a/cabal-install/src/Distribution/Client/Init/Prompt.hs b/cabal-install/src/Distribution/Client/Init/Prompt.hs index ca0ab3bf324..5d6be7fd497 100644 --- a/cabal-install/src/Distribution/Client/Init/Prompt.hs +++ b/cabal-install/src/Distribution/Client/Init/Prompt.hs @@ -22,9 +22,8 @@ module Distribution.Client.Init.Prompt , promptList ) where -import Prelude hiding (break, getLine, putStr, putStrLn) - import Distribution.Client.Compat.Prelude hiding (break, empty, getLine, putStr, putStrLn) +import Prelude () import Distribution.Client.Init.Types import qualified System.IO diff --git a/cabal-install/src/Distribution/Client/Init/Types.hs b/cabal-install/src/Distribution/Client/Init/Types.hs index b36428e9a89..0843e6643c0 100644 --- a/cabal-install/src/Distribution/Client/Init/Types.hs +++ b/cabal-install/src/Distribution/Client/Init/Types.hs @@ -85,9 +85,9 @@ import qualified System.IO import qualified Distribution.Compat.Environment as P import Distribution.FieldGrammar.Newtypes (SpecLicense) -import qualified System.Directory as P +import qualified Distribution.Compat.Directory as P import System.FilePath -import qualified System.Process as Process +import qualified Distribution.Compat.Process as Process -- -------------------------------------------------------------------- -- -- Flags diff --git a/cabal-install/src/Distribution/Client/Init/Utils.hs b/cabal-install/src/Distribution/Client/Init/Utils.hs index 0ac2221a2f0..3316dc6735f 100644 --- a/cabal-install/src/Distribution/Client/Init/Utils.hs +++ b/cabal-install/src/Distribution/Client/Init/Utils.hs @@ -25,9 +25,9 @@ module Distribution.Client.Init.Utils import Distribution.Client.Compat.Prelude hiding (Parsec, empty, many, putStrLn, readFile) import Distribution.Utils.Generic (isInfixOf, safeLast) -import qualified Prelude () +import Prelude () -import Control.Monad (forM) +import Data.Traversable (forM) import qualified Data.List.NonEmpty as NE import qualified Data.Map as M diff --git a/cabal-install/src/Distribution/Client/Install.hs b/cabal-install/src/Distribution/Client/Install.hs index 0ae7ad433a5..b691771c005 100644 --- a/cabal-install/src/Distribution/Client/Install.hs +++ b/cabal-install/src/Distribution/Client/Install.hs @@ -1,5 +1,4 @@ {-# LANGUAGE CPP #-} -{-# LANGUAGE DataKinds #-} -- | -- Module : Distribution.Client.Install @@ -40,7 +39,7 @@ import Control.Exception as Exception ) import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map -import System.Directory +import Distribution.Compat.Directory ( createDirectoryIfMissing , doesDirectoryExist , doesFileExist diff --git a/cabal-install/src/Distribution/Client/InstallPlan.hs b/cabal-install/src/Distribution/Client/InstallPlan.hs index 6383bb61208..fcfdbfc9075 100644 --- a/cabal-install/src/Distribution/Client/InstallPlan.hs +++ b/cabal-install/src/Distribution/Client/InstallPlan.hs @@ -1,4 +1,6 @@ -{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE CPP #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE UndecidableInstances #-} -- | -- Module : Distribution.Client.InstallPlan @@ -94,6 +96,7 @@ import Distribution.Package ( HasMungedPackageId (..) , HasUnitId (..) , Package (..) + , UnitId ) import Distribution.Pretty (defaultStyle) import Distribution.Solver.Types.SolverPackage @@ -177,11 +180,10 @@ data GenericPlanPackage ipkg srcpkg deriving (Eq, Show, Generic) -- | @ipkg@ and @srcpkg@ are the two node types of a single graph: both are --- 'IsNode's sharing a common key type. The shared key is spelled @'Key' ipkg@. -type IsGraph ipkg srcpkg = (IsNode ipkg, IsNode srcpkg, Key ipkg ~ Key srcpkg) +-- 'IsNode's sharing a common key type @k@. +type IsGraph k ipkg srcpkg = (IsNode k ipkg, IsNode k srcpkg) -instance IsGraph ipkg srcpkg => IsNode (GenericPlanPackage ipkg srcpkg) where - type Key (GenericPlanPackage ipkg srcpkg) = Key ipkg +instance IsGraph k ipkg srcpkg => IsNode k (GenericPlanPackage ipkg srcpkg) where nodeKey (PreExisting ipkg) = nodeKey ipkg nodeKey (Configured spkg) = nodeKey spkg nodeKey (Installed spkg) = nodeKey spkg @@ -225,7 +227,7 @@ instance configuredId (Configured spkg) = configuredId spkg configuredId (Installed spkg) = configuredId spkg -displayGenericPlanPackage :: (IsGraph ipkg srcpkg, Pretty (Key ipkg)) => GenericPlanPackage ipkg srcpkg -> String +displayGenericPlanPackage :: (IsGraph k ipkg srcpkg, Pretty k) => GenericPlanPackage ipkg srcpkg -> String displayGenericPlanPackage (PreExisting pkg) = "PreExisting " ++ prettyShow (nodeKey pkg) displayGenericPlanPackage (Configured pkg) = "Configured " ++ prettyShow (nodeKey pkg) displayGenericPlanPackage (Installed pkg) = "Installed " ++ prettyShow (nodeKey pkg) @@ -243,7 +245,7 @@ foldPlanPackage f _ (PreExisting ipkg) = f ipkg foldPlanPackage _ g (Configured srcpkg) = g srcpkg foldPlanPackage _ g (Installed srcpkg) = g srcpkg -depends :: IsNode a => a -> [Key a] +depends :: IsNode k a => a -> [k] depends = nodeNeighbors type PlanPackage = @@ -251,26 +253,27 @@ type PlanPackage = InstalledPackageInfo (ConfiguredPackage UnresolvedPkgLoc) -data GenericInstallPlan ipkg srcpkg = GenericInstallPlan - { planGraph :: !(Graph (GenericPlanPackage ipkg srcpkg)) +data GenericInstallPlan k ipkg srcpkg = GenericInstallPlan + { planGraph :: !(Graph k (GenericPlanPackage ipkg srcpkg)) , planIndepGoals :: !IndependentGoals } -- | 'GenericInstallPlan' specialised to most commonly used types. type InstallPlan = GenericInstallPlan + UnitId InstalledPackageInfo (ConfiguredPackage UnresolvedPkgLoc) -- | Smart constructor that deals with caching the 'Graph' representation. mkInstallPlan - :: ( IsGraph ipkg srcpkg - , Pretty (Key ipkg) + :: ( IsGraph k ipkg srcpkg + , Pretty k ) => String - -> Graph (GenericPlanPackage ipkg srcpkg) + -> Graph k (GenericPlanPackage ipkg srcpkg) -> IndependentGoals - -> GenericInstallPlan ipkg srcpkg + -> GenericInstallPlan k ipkg srcpkg mkInstallPlan loc graph indepGoals = assert (valid loc graph) @@ -287,24 +290,25 @@ internalError loc msg = ++ if null msg then "" else ": " ++ msg instance - (Structured ipkg, Structured srcpkg) - => Structured (GenericInstallPlan ipkg srcpkg) + (Structured k, Structured ipkg, Structured srcpkg) + => Structured (GenericInstallPlan k ipkg srcpkg) where structure p = Nominal (typeRep p) 0 "GenericInstallPlan" - [ structure (Proxy :: Proxy ipkg) + [ structure (Proxy :: Proxy k) + , structure (Proxy :: Proxy ipkg) , structure (Proxy :: Proxy srcpkg) ] instance - ( IsGraph ipkg srcpkg + ( IsGraph k ipkg srcpkg , Binary ipkg , Binary srcpkg ) - => Binary (GenericInstallPlan ipkg srcpkg) + => Binary (GenericInstallPlan k ipkg srcpkg) where put GenericInstallPlan @@ -332,24 +336,28 @@ showPlanGraph graph = vcat (map dispPlanPackage graph) where dispPlanPackage (ShowPlanNode herald neighbours) = +#ifdef __MHS__ + sep [herald, nest 2 (vcat neighbours)] +#else hang herald 2 (vcat neighbours) +#endif -- | Generic way to show a 'GenericInstallPlan' which elicits quite a lot of information showInstallPlan_gen - :: forall ipkg srcpkg + :: forall k ipkg srcpkg . (GenericPlanPackage ipkg srcpkg -> ShowPlanNode) - -> GenericInstallPlan ipkg srcpkg + -> GenericInstallPlan k ipkg srcpkg -> String showInstallPlan_gen toShow = showPlanGraph . fmap toShow . Foldable.toList . planGraph showInstallPlan - :: forall ipkg srcpkg - . ( IsGraph ipkg srcpkg + :: forall k ipkg srcpkg + . ( IsGraph k ipkg srcpkg , Package ipkg , Package srcpkg - , Pretty (Key ipkg) + , Pretty k ) - => GenericInstallPlan ipkg srcpkg + => GenericInstallPlan k ipkg srcpkg -> String showInstallPlan = showInstallPlan_gen toShow where @@ -371,33 +379,33 @@ showPlanPackageTag (Installed _) = "Installed" -- | Build an installation plan from a valid set of resolved packages. new - :: ( IsGraph ipkg srcpkg - , Pretty (Key ipkg) + :: ( IsGraph k ipkg srcpkg + , Pretty k ) => IndependentGoals - -> Graph (GenericPlanPackage ipkg srcpkg) - -> GenericInstallPlan ipkg srcpkg + -> Graph k (GenericPlanPackage ipkg srcpkg) + -> GenericInstallPlan k ipkg srcpkg new indepGoals graph = mkInstallPlan "new" graph indepGoals toGraph - :: GenericInstallPlan ipkg srcpkg - -> Graph (GenericPlanPackage ipkg srcpkg) + :: GenericInstallPlan k ipkg srcpkg + -> Graph k (GenericPlanPackage ipkg srcpkg) toGraph = planGraph toList - :: GenericInstallPlan ipkg srcpkg + :: GenericInstallPlan k ipkg srcpkg -> [GenericPlanPackage ipkg srcpkg] toList = Foldable.toList . planGraph toMap - :: GenericInstallPlan ipkg srcpkg - -> Map (Key ipkg) (GenericPlanPackage ipkg srcpkg) + :: GenericInstallPlan k ipkg srcpkg + -> Map k (GenericPlanPackage ipkg srcpkg) toMap = Graph.toMap . planGraph -keys :: GenericInstallPlan ipkg srcpkg -> [Key ipkg] +keys :: GenericInstallPlan k ipkg srcpkg -> [k] keys = Graph.keys . planGraph -keysSet :: GenericInstallPlan ipkg srcpkg -> Set (Key ipkg) +keysSet :: GenericInstallPlan k ipkg srcpkg -> Set k keysSet = Graph.keysSet . planGraph -- | Remove packages from the install plan. This will result in an @@ -406,13 +414,13 @@ keysSet = Graph.keysSet . planGraph -- the dependencies of a package or set of packages without actually -- installing the package itself, as when doing development. remove - :: ( IsGraph ipkg srcpkg - , Pretty (Key ipkg) - , Show (Key ipkg) + :: ( IsGraph k ipkg srcpkg + , Pretty k + , Show k ) => (GenericPlanPackage ipkg srcpkg -> Bool) - -> GenericInstallPlan ipkg srcpkg - -> GenericInstallPlan ipkg srcpkg + -> GenericInstallPlan k ipkg srcpkg + -> GenericInstallPlan k ipkg srcpkg remove shouldRemove plan = mkInstallPlan "remove" newGraph (planIndepGoals plan) where @@ -426,10 +434,10 @@ remove shouldRemove plan = -- To preserve invariants, the package must have all of its dependencies -- already installed too (that is 'PreExisting' or 'Installed'). installed - :: IsGraph ipkg srcpkg + :: IsGraph k ipkg srcpkg => (srcpkg -> Bool) - -> GenericInstallPlan ipkg srcpkg - -> GenericInstallPlan ipkg srcpkg + -> GenericInstallPlan k ipkg srcpkg + -> GenericInstallPlan k ipkg srcpkg installed shouldBeInstalled installPlan = foldl' markInstalled @@ -447,9 +455,9 @@ installed shouldBeInstalled installPlan = -- | Lookup a package in the plan. lookup - :: IsGraph ipkg srcpkg - => GenericInstallPlan ipkg srcpkg - -> Key ipkg + :: IsGraph k ipkg srcpkg + => GenericInstallPlan k ipkg srcpkg + -> k -> Maybe (GenericPlanPackage ipkg srcpkg) lookup plan pkgid = Graph.lookup pkgid (planGraph plan) @@ -457,8 +465,8 @@ lookup plan pkgid = Graph.lookup pkgid (planGraph plan) -- -- Note that the package must exist in the plan or it is an error. directDeps - :: GenericInstallPlan ipkg srcpkg - -> Key ipkg + :: GenericInstallPlan k ipkg srcpkg + -> k -> [GenericPlanPackage ipkg srcpkg] directDeps plan pkgid = case Graph.neighbors (planGraph plan) pkgid of @@ -469,8 +477,8 @@ directDeps plan pkgid = -- -- Note that the package must exist in the plan or it is an error. revDirectDeps - :: GenericInstallPlan ipkg srcpkg - -> Key ipkg + :: GenericInstallPlan k ipkg srcpkg + -> k -> [GenericPlanPackage ipkg srcpkg] revDirectDeps plan pkgid = case Graph.revNeighbors (planGraph plan) pkgid of @@ -485,15 +493,15 @@ revDirectDeps plan pkgid = -- and 'executionOrder' produce reverse topological orderings of the package -- dependency graph, it is not necessarily exactly the same order. reverseTopologicalOrder - :: GenericInstallPlan ipkg srcpkg + :: GenericInstallPlan k ipkg srcpkg -> [GenericPlanPackage ipkg srcpkg] reverseTopologicalOrder plan = Graph.revTopSort (planGraph plan) -- | Return the packages in the plan that are direct or indirect dependencies of -- the given packages. dependencyClosure - :: GenericInstallPlan ipkg srcpkg - -> [Key ipkg] + :: GenericInstallPlan k ipkg srcpkg + -> [k] -> [GenericPlanPackage ipkg srcpkg] dependencyClosure plan = fromMaybe [] @@ -502,8 +510,8 @@ dependencyClosure plan = -- | Return the packages in the plan that depend directly or indirectly on the -- given packages. reverseDependencyClosure - :: GenericInstallPlan ipkg srcpkg - -> [Key ipkg] + :: GenericInstallPlan k ipkg srcpkg + -> [k] -> [GenericPlanPackage ipkg srcpkg] reverseDependencyClosure plan = fromMaybe [] @@ -523,16 +531,16 @@ reverseDependencyClosure plan = -- because that's not enough information. fromSolverInstallPlan - :: ( IsGraph ipkg srcpkg - , Pretty (Key ipkg) - , Show (Key ipkg) + :: ( IsGraph k ipkg srcpkg + , Pretty k + , Show k ) => ( (SolverId -> [GenericPlanPackage ipkg srcpkg]) -> SolverInstallPlan.SolverPlanPackage -> [GenericPlanPackage ipkg srcpkg] ) -> SolverInstallPlan - -> GenericInstallPlan ipkg srcpkg + -> GenericInstallPlan k ipkg srcpkg fromSolverInstallPlan f plan = mkInstallPlan "fromSolverInstallPlan" @@ -566,16 +574,16 @@ fromSolverInstallPlan f plan = -- by the reverse top-sort (we assume the graph is not broken). fromSolverInstallPlanWithProgress - :: ( IsGraph ipkg srcpkg - , Pretty (Key ipkg) - , Show (Key ipkg) + :: ( IsGraph k ipkg srcpkg + , Pretty k + , Show k ) => ( (SolverId -> [GenericPlanPackage ipkg srcpkg]) -> SolverInstallPlan.SolverPlanPackage -> LogProgress [GenericPlanPackage ipkg srcpkg] ) -> SolverInstallPlan - -> LogProgress (GenericInstallPlan ipkg srcpkg) + -> LogProgress (GenericInstallPlan k ipkg srcpkg) fromSolverInstallPlanWithProgress f plan = do (_, _, pkgs'') <- foldM @@ -704,9 +712,9 @@ data Processing key = Processing !(Set key) !(Set key) !(Set key) -- all the packages that are ready will now be processed and so we can consider -- them to be in the processing state. ready - :: IsGraph ipkg srcpkg - => GenericInstallPlan ipkg srcpkg - -> ([GenericReadyPackage srcpkg], Processing (Key ipkg)) + :: IsGraph k ipkg srcpkg + => GenericInstallPlan k ipkg srcpkg + -> ([GenericReadyPackage srcpkg], Processing k) ready plan = assert (processingInvariant plan processing) (readyPackages, processing) where @@ -730,12 +738,12 @@ isInstalled _ = False -- and return any packages that are newly in the processing state (ie ready to -- process), along with the updated 'Processing' state. completed - :: forall ipkg srcpkg - . (IsGraph ipkg srcpkg, Pretty (Key ipkg)) - => GenericInstallPlan ipkg srcpkg - -> Processing (Key ipkg) - -> Key ipkg - -> ([GenericReadyPackage srcpkg], Processing (Key ipkg)) + :: forall k ipkg srcpkg + . (IsGraph k ipkg srcpkg, Pretty k) + => GenericInstallPlan k ipkg srcpkg + -> Processing k + -> k + -> ([GenericReadyPackage srcpkg], Processing k) completed plan (Processing processingSet completedSet failedSet) pkgid = assert (pkgid `Set.member` processingSet) $ assert @@ -767,11 +775,11 @@ completed plan (Processing processingSet completedSet failedSet) pkgid = asReadyPackage pkg = internalError "completed" $ "not in configured state: " ++ displayGenericPlanPackage pkg failed - :: (IsGraph ipkg srcpkg, Pretty (Key ipkg)) - => GenericInstallPlan ipkg srcpkg - -> Processing (Key ipkg) - -> Key ipkg - -> ([srcpkg], Processing (Key ipkg)) + :: (IsGraph k ipkg srcpkg, Pretty k) + => GenericInstallPlan k ipkg srcpkg + -> Processing k + -> k + -> ([srcpkg], Processing k) failed plan (Processing processingSet completedSet failedSet) pkgid = assert (pkgid `Set.member` processingSet) $ assert (all (`Set.notMember` processingSet) (drop 1 newlyFailedIds)) $ @@ -797,9 +805,9 @@ failed plan (Processing processingSet completedSet failedSet) pkgid = asConfiguredPackage pkg = internalError "failed" $ "not in configured state: " ++ displayGenericPlanPackage pkg processingInvariant - :: IsGraph ipkg srcpkg - => GenericInstallPlan ipkg srcpkg - -> Processing (Key ipkg) + :: IsGraph k ipkg srcpkg + => GenericInstallPlan k ipkg srcpkg + -> Processing k -> Bool processingInvariant plan (Processing processingSet completedSet failedSet) = -- All the packages in the three sets are actually in the graph @@ -878,8 +886,8 @@ processingInvariant plan (Processing processingSet completedSet failedSet) = -- source packages in the dependency graph, albeit not necessarily exactly the -- same ordering as that produced by 'reverseTopologicalOrder'. executionOrder - :: (IsGraph ipkg srcpkg, Pretty (Key ipkg)) - => GenericInstallPlan ipkg srcpkg + :: (IsGraph k ipkg srcpkg, Pretty k) + => GenericInstallPlan k ipkg srcpkg -> [GenericReadyPackage srcpkg] executionOrder plan = let (newpkgs, processing) = ready plan @@ -904,7 +912,7 @@ type BuildOutcomes key failure result = Map key (Either failure result) -- | Lookup the build result for a single package. lookupBuildOutcome - :: (IsNode pkg, Key pkg ~ key) + :: IsNode key pkg => pkg -> BuildOutcomes key failure result -> Maybe (Either failure result) @@ -925,31 +933,30 @@ lookupBuildOutcome = Map.lookup . nodeKey -- possible after a failure then there may be packages which are skipped and -- these will have no 'BuildOutcome'. execute - :: forall m ipkg srcpkg result failure - . ( IsGraph ipkg srcpkg + :: forall m k ipkg srcpkg result failure + . ( IsGraph k ipkg srcpkg , Monad m - , Pretty (Key srcpkg) + , Pretty k ) - => JobControl m (Key ipkg, Either failure result) + => JobControl m (k, Either failure result) -> Bool -- ^ Keep going after failure -> (srcpkg -> failure) -- ^ Value for dependents of failed packages - -> GenericInstallPlan ipkg srcpkg + -> GenericInstallPlan k ipkg srcpkg -> (GenericReadyPackage srcpkg -> m (Either failure result)) - -> m (BuildOutcomes (Key ipkg) failure result) + -> m (BuildOutcomes k failure result) execute jobCtl keepGoing depFailure plan installPkg = let (newpkgs, processing) = ready plan in tryNewTasks mempty False False processing newpkgs where tryNewTasks - :: Key srcpkg ~ key - => BuildOutcomes key failure result + :: BuildOutcomes k failure result -> Bool -> Bool - -> Processing key + -> Processing k -> [GenericReadyPackage srcpkg] - -> m (BuildOutcomes key failure result) + -> m (BuildOutcomes k failure result) tryNewTasks !results tasksFailed tasksRemaining !processing newpkgs -- we were in the process of cancelling and now we're finished @@ -976,11 +983,10 @@ execute jobCtl keepGoing depFailure plan installPkg = waitForTasks results tasksFailed processing waitForTasks - :: Key srcpkg ~ key - => BuildOutcomes key failure result + :: BuildOutcomes k failure result -> Bool - -> Processing key - -> m (BuildOutcomes key failure result) + -> Processing k + -> m (BuildOutcomes k failure result) waitForTasks !results tasksFailed !processing = do (pkgid, result) <- collectJob jobCtl @@ -1024,29 +1030,29 @@ execute jobCtl keepGoing depFailure plan installPkg = -- -- * if the result is @False@ use 'problems' to get a detailed list. valid - :: ( IsGraph ipkg srcpkg - , Pretty (Key ipkg) + :: ( IsGraph k ipkg srcpkg + , Pretty k ) => String - -> Graph (GenericPlanPackage ipkg srcpkg) + -> Graph k (GenericPlanPackage ipkg srcpkg) -> Bool valid loc graph = case problems graph of [] -> True ps -> internalError loc ('\n' : unlines (map showPlanProblem ps)) -data PlanProblem ipkg srcpkg - = PackageMissingDeps (GenericPlanPackage ipkg srcpkg) (NonEmpty (Key ipkg)) +data PlanProblem k ipkg srcpkg + = PackageMissingDeps (GenericPlanPackage ipkg srcpkg) (NonEmpty k) | PackageCycle [GenericPlanPackage ipkg srcpkg] | PackageStateInvalid (GenericPlanPackage ipkg srcpkg) (GenericPlanPackage ipkg srcpkg) showPlanProblem - :: ( IsGraph ipkg srcpkg - , Pretty (Key ipkg) + :: ( IsGraph k ipkg srcpkg + , Pretty k ) - => PlanProblem ipkg srcpkg + => PlanProblem k ipkg srcpkg -> String showPlanProblem (PackageMissingDeps pkg missingDeps) = "Package " @@ -1071,9 +1077,9 @@ showPlanProblem (PackageStateInvalid pkg pkg') = -- error messages. This is mainly intended for debugging purposes. -- Use 'showPlanProblem' for a human readable explanation. problems - :: IsGraph ipkg srcpkg - => Graph (GenericPlanPackage ipkg srcpkg) - -> [PlanProblem ipkg srcpkg] + :: IsGraph k ipkg srcpkg + => Graph k (GenericPlanPackage ipkg srcpkg) + -> [PlanProblem k ipkg srcpkg] problems graph = [ PackageMissingDeps pkg diff --git a/cabal-install/src/Distribution/Client/InstallSymlink.hs b/cabal-install/src/Distribution/Client/InstallSymlink.hs index 32823ddec6f..99ed805775e 100644 --- a/cabal-install/src/Distribution/Client/InstallSymlink.hs +++ b/cabal-install/src/Distribution/Client/InstallSymlink.hs @@ -71,7 +71,7 @@ import Distribution.Types.DependencySatisfaction ) import Distribution.Types.UnqualComponentName -import System.Directory +import Distribution.Compat.Directory ( canonicalizePath , createFileLink , getSymbolicLinkTarget diff --git a/cabal-install/src/Distribution/Client/JobControl.hs b/cabal-install/src/Distribution/Client/JobControl.hs index 3cb2162581f..0786ed46ea3 100644 --- a/cabal-install/src/Distribution/Client/JobControl.hs +++ b/cabal-install/src/Distribution/Client/JobControl.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- | -- Module : Distribution.Client.JobControl -- Copyright : (c) Duncan Coutts 2012 @@ -47,7 +48,16 @@ import Distribution.Compat.Stack import Distribution.Simple.Compiler import Distribution.Simple.Utils import Distribution.Types.ParStrat +#ifndef __MHS__ import System.Semaphore +#endif + +#ifdef __MHS__ +-- | MHS fallback: @semaphore-compat@ is unavailable, so the semaphore +-- identifier is just its (opaque) name and semaphore job control +-- degrades to plain parallel job control (see 'newSemaphoreJobControl'). +type SemaphoreIdentifier = String +#endif -- | A simple concurrency abstraction. Jobs can be spawned and can complete -- in any order. This allows both serial and parallel implementations. @@ -173,6 +183,10 @@ readAllTChan qvar = go [] -- This uses the GHC -jsem option to allow GHC to take additional semaphore slots -- if we are not using them all. newSemaphoreJobControl :: WithCallStack (Verbosity -> Int -> IO (JobControl IO a)) +#ifdef __MHS__ +-- No @-jsem@ support in the MHS build: cap jobs locally instead. +newSemaphoreJobControl _ = newParallelJobControl +#else newSemaphoreJobControl _ n | n < 1 || n > 1000 = error $ "newParallelJobControl: not a sensible number of jobs: " ++ show n @@ -250,6 +264,7 @@ newSemaphoreJobControl verbosity maxJobLimit = do atomically $ do xs <- readAllTChan inqVar modifyTVar' countVar (subtract (length xs)) +#endif ------------------------- -- Job limits and locks @@ -290,6 +305,10 @@ newJobControlFromParStrat newJobControlFromParStrat verbosity mcompiler parStrat numJobsCap = case parStrat of Serial -> newSerialJobControl NumJobs n -> newParallelJobControl (capJobs (fromMaybe numberOfProcessors n)) +#ifdef __MHS__ + -- No @-jsem@ support in the MHS build: cap jobs locally instead. + UseSem n -> newParallelJobControl (capJobs n) +#else UseSem n -> case mcompiler of Just compiler @@ -315,17 +334,23 @@ newJobControlFromParStrat verbosity mcompiler parStrat numJobsCap = case parStra Nothing -> -- Don't warn in the Nothing case, as there isn't really a "selected" compiler. newParallelJobControl (capJobs n) +#endif where capJobs n = min (fromMaybe maxBound numJobsCap) n -- | Check if the compiler's semaphore version is compatible with ours, -- per 'versionsAreCompatible'. A compiler that doesn't report a -- @"Semaphore version"@ field is treated as v1. +#ifdef __MHS__ +isJsemCompatible :: Compiler -> Bool +isJsemCompatible _ = False +#else isJsemCompatible :: Compiler -> Bool isJsemCompatible compiler = versionsAreCompatible (SemaphoreProtocolVersion v) semaphoreVersion where v = fromMaybe 1 (jsemVersion compiler) +#endif withJobControl :: IO (JobControl IO a) -> (JobControl IO a -> IO b) -> IO b withJobControl mkJC = bracket mkJC cleanupJobControl diff --git a/cabal-install/src/Distribution/Client/List.hs b/cabal-install/src/Distribution/Client/List.hs index 03a03fceefc..dc510df952e 100644 --- a/cabal-install/src/Distribution/Client/List.hs +++ b/cabal-install/src/Distribution/Client/List.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- | -- Module : Distribution.Client.List -- Copyright : (c) David Himmelstrup 2005 @@ -41,6 +42,9 @@ import Distribution.Simple.Setup (fromFlag, fromFlagOrDefault) import Distribution.Simple.Utils ( dieWithException , equating +#ifdef __MHS__ + , lowercase +#endif , notice ) import Distribution.Version @@ -90,9 +94,14 @@ import Distribution.Client.Utils import Control.Exception ( assert ) +#ifndef __MHS__ import Data.Bits ((.|.)) +#endif import Data.List ( maximumBy +#ifdef __MHS__ + , isInfixOf +#endif ) import qualified Data.List as L import Data.List.NonEmpty (groupBy) @@ -102,9 +111,15 @@ import Data.Maybe ) import qualified Data.Text as Text import Data.Tree as Tree +#ifdef __MHS__ +import Distribution.Compat.Directory + ( doesDirectoryExist + ) +#else import System.Directory ( doesDirectoryExist ) +#endif import Text.PrettyPrint ( Doc , char @@ -124,8 +139,10 @@ import qualified Text.PrettyPrint as Disp import Distribution.Client.Errors import Distribution.Utils.ShortText (ShortText) import qualified Distribution.Utils.ShortText as ShortText +#ifndef __MHS__ import qualified Text.Regex.Base as Regex import qualified Text.Regex.Posix.String as Regex +#endif -- | Return a list of packages matching given search strings. getPkgList @@ -141,11 +158,13 @@ getPkgList verbosity packageDBs repoCtxt mcompprogdb listFlags pats = do getInstalledPackages verbosity comp packageDBs progdb sourcePkgDb <- getSourcePackages verbosity repoCtxt +#ifndef __MHS__ regexps <- for pats $ \pat -> do e <- Regex.compile compOption Regex.execBlank pat case e of Right r -> return r - Left err -> dieWithException verbosity $ GetPkgList pat err + Left err -> dieWithException verbosity $ GetPkgList pat (snd err) +#endif let sourcePkgIndex = packageIndex sourcePkgDb prefs name = @@ -154,15 +173,24 @@ getPkgList verbosity packageDBs repoCtxt mcompprogdb listFlags pats = do pkgsInfoMatching :: [(PackageName, [Installed.InstalledPackageInfo], [UnresolvedSourcePackage])] pkgsInfoMatching = +#ifdef __MHS__ + let matchingInstalled = maybe [] (matchingPackages InstalledPackageIndex.searchWithPredicate pats) installedPkgIndex + matchingSource = matchingPackages (\idx n -> concatMap snd (PackageIndex.searchWithPredicate idx n)) pats sourcePkgIndex +#else let matchingInstalled = maybe [] (matchingPackages InstalledPackageIndex.searchWithPredicate regexps) installedPkgIndex matchingSource = matchingPackages (\idx n -> concatMap snd (PackageIndex.searchWithPredicate idx n)) regexps sourcePkgIndex +#endif in mergePackages matchingInstalled matchingSource pkgsInfo :: [(PackageName, [Installed.InstalledPackageInfo], [UnresolvedSourcePackage])] pkgsInfo -- gather info for all packages +#ifdef __MHS__ + | null pats = +#else | null regexps = +#endif mergePackages (maybe [] InstalledPackageIndex.allPackages installedPkgIndex) (PackageIndex.allPackages sourcePkgIndex) @@ -187,6 +215,19 @@ getPkgList verbosity packageDBs repoCtxt mcompprogdb listFlags pats = do onlyInstalled = fromFlagOrDefault False (listInstalled listFlags) caseInsensitive = fromFlagOrDefault True (listCaseInsensitive listFlags) +#ifdef __MHS__ + -- Substring fallback for matching package names, used in place of + -- regular expressions. + matchingPackages search pats index = + [ pkg + | pat <- pats + , pkg <- search index (matchSubstring pat) + ] + where + matchSubstring pat + | caseInsensitive = \name -> lowercase pat `isInfixOf` lowercase name + | otherwise = isInfixOf pat +#else compOption | caseInsensitive = Regex.compExtended .|. Regex.compIgnoreCase | otherwise = Regex.compExtended @@ -196,6 +237,7 @@ getPkgList verbosity packageDBs repoCtxt mcompprogdb listFlags pats = do | re <- regexps , pkg <- search index (Regex.matchTest re) ] +#endif -- | Show information about packages. list diff --git a/cabal-install/src/Distribution/Client/Main.hs b/cabal-install/src/Distribution/Client/Main.hs index 2dd8fed4a4a..f900152875e 100644 --- a/cabal-install/src/Distribution/Client/Main.hs +++ b/cabal-install/src/Distribution/Client/Main.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} @@ -264,10 +264,14 @@ import Distribution.Version , orLaterVersion ) +#ifdef __MHS__ +import Control.Exception (try) +#else import Control.Exception (AssertionFailed, assert, try) +#endif import Data.Monoid (Any (..)) import Distribution.Client.Types -import System.Directory +import Distribution.Compat.Directory ( doesFileExist , withCurrentDirectory ) @@ -286,7 +290,7 @@ import System.IO , stderr , stdout ) -import System.Process (createProcess, env, proc, waitForProcess) +import Distribution.Compat.Process (createProcess, env, proc, waitForProcess) -- | Entry point -- @@ -326,6 +330,9 @@ main args = do -- | Check whether assertions are enabled and print a warning in that case. warnIfAssertionsAreEnabled :: IO () +#ifdef __MHS__ +warnIfAssertionsAreEnabled = return () +#else warnIfAssertionsAreEnabled = assert False (return ()) `catch` (\(_e :: AssertionFailed) -> hPutStrLn stderr assertionsEnabledMsg) @@ -336,6 +343,7 @@ warnIfAssertionsAreEnabled = assertionsEnabledMsg = "Warning: this is a debug build of cabal-install with assertions enabled." +#endif -- | Core worker, similar to 'defaultMainHelper' in Cabal/Distribution.Simple -- @@ -979,7 +987,7 @@ testAction (buildFlags, testFlags) extraArgs globalFlags = do { testCommonFlags = (testCommonFlags testFlags){setupDistPref = toFlag distPref} } - mbWorkDir = flagToMaybe $ testWorkingDir testFlags + mbWorkDir = flagToMaybe $ setupWorkingDir $ testCommonFlags testFlags -- The package was just configured, so the LBI must be available. names <- @@ -1103,7 +1111,7 @@ benchmarkAction { setupDistPref = toFlag distPref } } - mbWorkDir = flagToMaybe $ benchmarkWorkingDir benchmarkFlags + mbWorkDir = flagToMaybe $ setupWorkingDir $ benchmarkCommonFlags benchmarkFlags -- The package was just configured, so the LBI must be available. names <- @@ -1421,7 +1429,7 @@ uploadAction uploadFlags extraArgs globalFlags = do [] globalFlags distPref <- findSavedDistPref config NoFlag - let mbWorkDir = flagToMaybe $ configWorkingDir $ savedConfigureFlags config + let mbWorkDir = flagToMaybe $ setupWorkingDir $ configCommonFlags $ savedConfigureFlags config pkg <- fmap LBI.localPkgDescr (getPersistBuildConfig mbWorkDir distPref) return $ getSymbolicPath distPref display (packageId pkg) ++ "-docs" <.> "tar.gz" diff --git a/cabal-install/src/Distribution/Client/Manpage.hs b/cabal-install/src/Distribution/Client/Manpage.hs index d5e22ce0bbb..4a961259f53 100644 --- a/cabal-install/src/Distribution/Client/Manpage.hs +++ b/cabal-install/src/Distribution/Client/Manpage.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} -- | -- Module : Distribution.Client.Manpage -- Copyright : (c) Maciek Makowski 2015 @@ -40,7 +41,7 @@ import Distribution.Simple.Utils import Distribution.Verbosity import System.Environment (lookupEnv) import System.IO (hClose, hPutStr) -import qualified System.Process as Process +import qualified Distribution.Compat.Process as Process data FileInfo = -- | path, description @@ -92,6 +93,18 @@ manpageCmd pname commands flags [] -> dieWithException verbosity EmptyValuePagerEnvVariable (p : pa) -> pure (p, pa) -- Pipe output of @nroff@ into @less@ +#ifdef __MHS__ + -- MHS: stage the input before spawn; a 'CreatePipe' stdin + -- would hand the child an empty file while the parent has + -- not written yet, with no way to synchronize. + (inH, cleanupIn) <- Process.newStagedInput formatted + (ec2, _) <- + rawSystemProcAction + verbosity + (proc pager pagerArgs){Process.std_in = Process.UseHandle inH} + $ \_ _ _ -> return () + cleanupIn +#else (ec2, _) <- rawSystemProcAction verbosity (proc pager pagerArgs){Process.std_in = Process.CreatePipe} @@ -99,6 +112,7 @@ manpageCmd pname commands flags let wIn = fromCreatePipe mIn hPutStr wIn formatted hClose wIn +#endif exitWith ec2 where contents :: String diff --git a/cabal-install/src/Distribution/Client/ManpageFlags.hs b/cabal-install/src/Distribution/Client/ManpageFlags.hs index a791bde5306..66d134fc6c3 100644 --- a/cabal-install/src/Distribution/Client/ManpageFlags.hs +++ b/cabal-install/src/Distribution/Client/ManpageFlags.hs @@ -7,6 +7,7 @@ module Distribution.Client.ManpageFlags ) where import Distribution.Client.Compat.Prelude +import Prelude () import Distribution.Simple.Command (OptionField (..), ShowOrParseArgs (..), option) import Distribution.Simple.Setup (Flag, optionVerbosity, toFlag, trueArg) diff --git a/cabal-install/src/Distribution/Client/PackageHash.hs b/cabal-install/src/Distribution/Client/PackageHash.hs index f9cec43abd8..0eadc0d21c0 100644 --- a/cabal-install/src/Distribution/Client/PackageHash.hs +++ b/cabal-install/src/Distribution/Client/PackageHash.hs @@ -139,6 +139,7 @@ hashedInstalledPackageIdShort pkghashinputs@PackageHashInputs{pkgHashPkgId} = | length s <= n = s | otherwise = take (n - 1) s ++ "_" + -- | All the information that contributes to a package's hash, and thus its -- 'InstalledPackageId'. data PackageHashInputs = PackageHashInputs diff --git a/cabal-install/src/Distribution/Client/ProjectBuilding.hs b/cabal-install/src/Distribution/Client/ProjectBuilding.hs index 4658889b9ee..cdc24cdcbf7 100644 --- a/cabal-install/src/Distribution/Client/ProjectBuilding.hs +++ b/cabal-install/src/Distribution/Client/ProjectBuilding.hs @@ -1,6 +1,6 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE RecordWildCards #-} -{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE NoMonoLocalBinds #-} module Distribution.Client.ProjectBuilding @@ -94,9 +94,13 @@ import Control.Exception (handle, try) import Data.Either (isLeft) import qualified Distribution.Client.IndexUtils as IndexUtils import Distribution.Simple.PackageIndex (InstalledPackageIndex) -import System.Directory (doesDirectoryExist, doesFileExist, renameDirectory) +import Distribution.Compat.Directory (doesDirectoryExist, doesFileExist, renameDirectory) import System.FilePath (makeRelative, normalise, takeDirectory, takeFileName, (<.>), ()) +#ifdef __MHS__ +type SemaphoreIdentifier = String +#else import System.Semaphore (SemaphoreIdentifier) +#endif import Distribution.Client.Errors import Distribution.Simple.Flag (fromFlagOrDefault) @@ -265,21 +269,21 @@ rebuildTargetsDryRun distDirLayout@DistDirLayout{..} shared = -- visiting function is passed the results for all the immediate package -- dependencies. This can be used to propagate information from dependencies. foldMInstallPlanDepOrder - :: forall m ipkg srcpkg b - . (Monad m, IsGraph ipkg srcpkg) + :: forall m k ipkg srcpkg b + . (Monad m, IsGraph k ipkg srcpkg) => ( GenericPlanPackage ipkg srcpkg -> [b] -> m b ) - -> GenericInstallPlan ipkg srcpkg - -> m (Map (Key ipkg) b) + -> GenericInstallPlan k ipkg srcpkg + -> m (Map k b) foldMInstallPlanDepOrder visit = go Map.empty . InstallPlan.reverseTopologicalOrder where go - :: Map (Key ipkg) b + :: Map k b -> [GenericPlanPackage ipkg srcpkg] - -> m (Map (Key ipkg) b) + -> m (Map k b) go !results [] = return results go !results (pkg : pkgs) = do -- we go in the right order so the results map has entries for all deps diff --git a/cabal-install/src/Distribution/Client/ProjectBuilding/UnpackedPackage.hs b/cabal-install/src/Distribution/Client/ProjectBuilding/UnpackedPackage.hs index a3e5f3361f2..a63d8517d57 100644 --- a/cabal-install/src/Distribution/Client/ProjectBuilding/UnpackedPackage.hs +++ b/cabal-install/src/Distribution/Client/ProjectBuilding/UnpackedPackage.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} @@ -115,15 +115,36 @@ import qualified Data.List.NonEmpty as NE import Control.Concurrent.STM (TVar, atomically, modifyTVar) import Control.Exception (ErrorCall, Handler (..), SomeAsyncException, assert, catches, onException) import Data.IORef (newIORef, readIORef, writeIORef) +#ifndef __MHS__ import GHC.Clock (getMonotonicTime) -import System.Directory (canonicalizePath, createDirectoryIfMissing) -import System.FilePath (takeDirectory, (<.>), ()) +#endif +#ifdef __MHS__ +import System.CPUTime (getCPUTime) +#endif +import Distribution.Compat.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, listDirectory) +import System.FilePath (dropDrive, normalise, takeDirectory, (<.>), ()) import System.IO (Handle, IOMode (AppendMode), withFile) +#ifdef __MHS__ +type SemaphoreIdentifier = String +#else import System.Semaphore (SemaphoreIdentifier) +#endif import Text.Printf (printf) import GHC.Stack +#ifndef __MHS__ import Web.Browser (openBrowser) +#endif + +#ifdef __MHS__ +-- | MHS fallback for 'GHC.Clock.getMonotonicTime', via CPU time. +getMonotonicTime :: IO Double +getMonotonicTime = (/ 1e12) . fromIntegral <$> getCPUTime + +-- | MHS fallback for @open-browser@: print the URL instead of opening it. +openBrowser :: String -> IO Bool +openBrowser url = putStrLn url >> return True +#endif -- | Each unpacked package is processed in the following phases: -- @@ -140,23 +161,22 @@ import Web.Browser (openBrowser) -- the phases will be carried out differently. For example, when installing, -- the test, benchmark, and repl phase are ignored. data PackageBuildingPhase r where - PBConfigurePhase :: {runConfigure :: IO (Maybe Cabal.LocalBuildInfo)} -> PackageBuildingPhase (Maybe Cabal.LocalBuildInfo) - PBBuildPhase :: {runBuild :: IO [MonitorFilePath]} -> PackageBuildingPhase () - PBHaddockPhase :: {runHaddock :: IO [MonitorFilePath]} -> PackageBuildingPhase () - PBReplPhase :: {runRepl :: IO [MonitorFilePath]} -> PackageBuildingPhase () + PBConfigurePhase :: IO (Maybe Cabal.LocalBuildInfo) -> PackageBuildingPhase (Maybe Cabal.LocalBuildInfo) + PBBuildPhase :: IO [MonitorFilePath] -> PackageBuildingPhase () + PBHaddockPhase :: IO [MonitorFilePath] -> PackageBuildingPhase () + PBReplPhase :: IO [MonitorFilePath] -> PackageBuildingPhase () PBInstallPhase - :: { runCopy :: Cabal.CopyDest -> IO () - , runRegister - :: PackageDBStackCWD - -> Cabal.RegisterOptions - -> IO InstalledPackageInfo - , getInstalledPackageInfo :: IO InstalledPackageInfo - -- ^ Compute the 'InstalledPackageInfo' from the build output, - -- without registering with @ghc-pkg@. Deterministic. - } + :: (Cabal.CopyDest -> IO ()) + -> ( PackageDBStackCWD + -> Cabal.RegisterOptions + -> IO InstalledPackageInfo + ) + -> IO InstalledPackageInfo + -- ^ Compute the 'InstalledPackageInfo' from the build output, + -- without registering with @ghc-pkg@. Deterministic. -> PackageBuildingPhase () - PBTestPhase :: {runTest :: IO ()} -> PackageBuildingPhase () - PBBenchPhase :: {runBench :: IO ()} -> PackageBuildingPhase () + PBTestPhase :: IO () -> PackageBuildingPhase () + PBBenchPhase :: IO () -> PackageBuildingPhase () -- | Structures the phases of building and registering a package amongst others -- (see t'PackageBuildingPhase'). Delegates logic specific to a certain @@ -251,7 +271,7 @@ buildAndRegisterUnpackedPackage return ipkg0{Installed.installedUnitId = uid} timedDelegate $ PBInstallPhase - { runCopy = \dest -> + ( \dest -> annotateFailure mlogFile InstallFailed $ setup Cabal.copyCommand @@ -259,7 +279,8 @@ buildAndRegisterUnpackedPackage (return . copyFlags dest) copyArgs (InLibraryArgs $ InLibraryPostConfigureArgs SCopyPhase mbLBI) - , runRegister = \pkgDBStack registerOpts -> + ) + ( \pkgDBStack registerOpts -> annotateFailure mlogFile InstallFailed $ do -- We register ourselves, rather than via Setup.hs. ipkg <- getIpkg @@ -273,8 +294,8 @@ buildAndRegisterUnpackedPackage ipkg registerOpts return ipkg - , getInstalledPackageInfo = getIpkg - } + ) + getIpkg -- Test phase whenTest $ @@ -451,13 +472,13 @@ buildAndRegisterUnpackedPackage cacheLock setup - :: (HasCallStack, RightFlagsForPhase flags setupSpec) + :: HasCallStack => CommandUI flags -> (flags -> CommonSetupFlags) -> (Version -> IO flags) -> (Version -> [String]) - -> SetupRunnerArgs setupSpec - -> IO (SetupRunnerRes setupSpec) + -> SetupRunnerArgs flags result + -> IO result setup cmd getCommonFlags flags args wrapperArgs = withLogging $ \mLogFileHandle -> setupWrapper @@ -478,13 +499,12 @@ buildAndRegisterUnpackedPackage wrapperArgs setupInteractive - :: RightFlagsForPhase flags setupSpec - => CommandUI flags + :: CommandUI flags -> (flags -> CommonSetupFlags) -> (Version -> IO flags) -> (Version -> [String]) - -> SetupRunnerArgs setupSpec - -> IO (SetupRunnerRes setupSpec) + -> SetupRunnerArgs flags result + -> IO result setupInteractive = setupWrapper verbosity @@ -584,17 +604,17 @@ buildInplaceUnpackedPackage builddir Nothing -- no log file for inplace builds! $ \case - PBConfigurePhase{runConfigure} -> + PBConfigurePhase runConfigure -> whenReconfigure $ do mbLBI <- runConfigure invalidatePackageRegFileMonitor packageFileMonitor updatePackageConfigFileMonitor packageFileMonitor (getSymbolicPath srcdir) pkg return mbLBI - PBBuildPhase{runBuild} -> + PBBuildPhase runBuild -> whenRebuild $ withFileMonitor runBuild - PBReplPhase{runRepl} -> + PBReplPhase runRepl -> withFileMonitor runRepl - PBHaddockPhase{runHaddock} -> do + PBHaddockPhase runHaddock -> do withFileMonitor runHaddock let haddockTarget = elabHaddockForHackage pkg when (haddockTarget == Cabal.ForHackage) $ do @@ -620,7 +640,7 @@ buildInplaceUnpackedPackage FindOpenProgramLocationErr $ "Unsupported OS: " <> show os ) - PBInstallPhase{runCopy = _runCopy, runRegister} -> do + PBInstallPhase _runCopy runRegister _getInstalledPackageInfo -> do -- PURPOSELY omitted: no copy! whenReRegister $ do @@ -640,8 +660,8 @@ buildInplaceUnpackedPackage else return Nothing updatePackageRegFileMonitor packageFileMonitor (getSymbolicPath srcdir) mipkg - PBTestPhase{runTest} -> runTest - PBBenchPhase{runBench} -> runBench + PBTestPhase runTest -> runTest + PBBenchPhase runBench -> runBench return BuildResult @@ -825,18 +845,18 @@ buildAndInstallUnpackedPackage builddir mlogFile $ \case - PBConfigurePhase{runConfigure} -> do + PBConfigurePhase runConfigure -> do noticeProgress ProgressStarting runConfigure - PBBuildPhase{runBuild} -> do + PBBuildPhase runBuild -> do noticeProgress ProgressBuilding _monitors <- runBuild return () - PBHaddockPhase{runHaddock} -> do + PBHaddockPhase runHaddock -> do noticeProgress ProgressHaddock _monitors <- runHaddock return () - PBInstallPhase{runCopy, runRegister, getInstalledPackageInfo} -> do + PBInstallPhase runCopy runRegister getInstalledPackageInfo -> do noticeProgress ProgressInstalling -- Create an IORef used to retrieve the InstalledPackageInfo computed diff --git a/cabal-install/src/Distribution/Client/ProjectConfig.hs b/cabal-install/src/Distribution/Client/ProjectConfig.hs index 328bfa81f6e..d1f5226df50 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RecordWildCards #-} @@ -90,6 +91,11 @@ import Distribution.Simple.Utils import Text.PrettyPrint (cat, colon, comma, empty, hsep, nest, quotes, render, text, vcat) import Prelude () +#ifdef __MHS__ +instance Ord (Proxy a) where + compare _ _ = EQ +#endif + import Distribution.Client.Glob ( isTrivialRootedGlob ) @@ -215,8 +221,12 @@ import Distribution.Utils.NubList import Distribution.Verbosity import Distribution.Version +#ifdef __MHS__ +import qualified Distribution.Client.Compat.Tar as Tar +#else import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar +#endif import qualified Distribution.Client.GZipUtils as GZipUtils import qualified Distribution.Client.Tar as Tar @@ -236,7 +246,7 @@ import Network.URI , parseAbsoluteURI , uriToString ) -import System.Directory +import Distribution.Compat.Directory ( canonicalizePath , doesDirectoryExist , doesFileExist @@ -246,6 +256,7 @@ import System.Directory , listDirectory , pathIsSymbolicLink ) +import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS) import System.FilePath hiding (combine) import System.IO ( IOMode (ReadMode) @@ -628,7 +639,7 @@ findProjectRoot verbosity mprojectDir mprojectFile = do probeProjectRoot :: Maybe FilePath -> IO (Either BadProjectRoot ProjectRoot) probeProjectRoot mprojectFile = do - startdir <- System.Directory.getCurrentDirectory + startdir <- Distribution.Compat.Directory.getCurrentDirectory homedir <- getHomeDirectory probe startdir homedir where @@ -1792,7 +1803,7 @@ instance Exception CabalFileSearchFailure extractTarballPackageCabalFile :: FilePath -> IO (FilePath, BS.ByteString) extractTarballPackageCabalFile tarballFile = withBinaryFile tarballFile ReadMode $ \hnd -> do - content <- LBS.hGetContents hnd + content <- hGetContentsLBS hnd case extractTarballPackageCabalFilePure tarballFile content of Left (Left e) -> throwIO e Left (Right e) -> throwIO e @@ -1812,7 +1823,7 @@ extractTarballPackageCabalFilePure extractTarballPackageCabalFilePure tarballFile = check . accumEntryMap - . Tar.filterEntries isCabalFile + . Tar.foldEntries (\e es -> if isCabalFile e then Tar.Next e es else es) Tar.Done Tar.Fail . Tar.read . GZipUtils.maybeDecompress where diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/FieldGrammar.hs b/cabal-install/src/Distribution/Client/ProjectConfig/FieldGrammar.hs index 9a6016d94e6..6af173e8703 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/FieldGrammar.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/FieldGrammar.hs @@ -16,6 +16,7 @@ import qualified Distribution.Client.ProjectConfig.Lens as L import Distribution.Client.ProjectConfig.Types (PackageConfig (..), ProjectConfig (..), ProjectConfigBuildOnly (..), ProjectConfigProvenance (..), ProjectConfigShared (..)) import Distribution.Client.Utils.Parsec import Distribution.Compat.Prelude +import Prelude () import Distribution.FieldGrammar import Distribution.Simple.Flag import Distribution.Simple.InstallDirs diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/Import.hs b/cabal-install/src/Distribution/Client/ProjectConfig/Import.hs index 27e49006c3e..cd5fcd554d7 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/Import.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/Import.hs @@ -29,6 +29,7 @@ import Data.List ((\\)) import qualified Data.Map as Map import Distribution.Client.Compat.Prelude hiding (empty, (<>)) import qualified Distribution.Client.Compat.Prelude as Prelude ((<>)) +import Prelude () import Distribution.Client.HttpUtils import Distribution.Client.ProjectConfig.Types import Distribution.Compat.Lens (view) @@ -38,7 +39,7 @@ import Distribution.Solver.Types.ProjectConfigPath import Distribution.Types.CondTree (CondTree (..), traverseCondTreeA) import Distribution.Utils.String (trim) import Network.URI (URI (..), parseURI) -import System.Directory (createDirectoryIfMissing) +import Distribution.Compat.Directory (createDirectoryIfMissing) import System.FilePath (isAbsolute, isPathSeparator, makeValid, ()) import Text.PrettyPrint (Doc, empty, int, nest, semi, text, vcat, (<>)) diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/Legacy.hs b/cabal-install/src/Distribution/Client/ProjectConfig/Legacy.hs index a9e080327dd..bb2f7cd4441 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/Legacy.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/Legacy.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DerivingVia #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE PatternSynonyms #-} @@ -34,6 +35,9 @@ module Distribution.Client.ProjectConfig.Legacy ) where import Distribution.Client.Compat.Prelude +#ifdef __MHS__ +import Prelude (mapM_) +#endif import Distribution.Types.Flag (FlagName, parsecFlagAssignment) @@ -200,7 +204,7 @@ import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import Network.URI (URI (..), nullURIAuth) -import System.Directory (makeAbsolute) +import Distribution.Compat.Directory (makeAbsolute) import System.FilePath (splitFileName) import Text.PrettyPrint ( Doc diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/Lens.hs b/cabal-install/src/Distribution/Client/ProjectConfig/Lens.hs index 6423434701d..5f6e1747c7b 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/Lens.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/Lens.hs @@ -19,6 +19,7 @@ import Distribution.Client.Types.SourceRepo (SourceRepoList) import Distribution.Client.Types.WriteGhcEnvironmentFilesPolicy (WriteGhcEnvironmentFilesPolicy) import Distribution.Compat.Lens import Distribution.Compat.Prelude +import Prelude () import Distribution.Compiler (CompilerFlavor (..)) import Distribution.Package ( PackageName diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/Parsec.hs b/cabal-install/src/Distribution/Client/ProjectConfig/Parsec.hs index 64e0a023b32..88e36e40537 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/Parsec.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/Parsec.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} -- | Parsing project configuration. @@ -23,6 +24,9 @@ import Distribution.Client.Types.SourceRepo (sourceRepositoryPackageGrammar) import Distribution.Client.Utils.Parsec import Distribution.Compat.Lens import Distribution.Compat.Prelude +#ifdef __MHS__ +import Prelude (mapM_) +#endif import Distribution.FieldGrammar import Distribution.FieldGrammar.Parsec (NamelessField (..), namelessFieldAnn) import Distribution.Fields (Field (..), FieldLine (..), FieldName, Name (..), SectionArg (..), readFields') @@ -56,7 +60,7 @@ import qualified Data.Set as Set import Distribution.Client.Errors.Parser (ProjectFileSource (..)) import qualified Distribution.Compat.CharParsing as P import Network.URI (URI, uriFragment, uriPath, uriScheme) -import System.Directory (makeAbsolute) +import Distribution.Compat.Directory (makeAbsolute) import System.FilePath (splitFileName) import qualified Text.Parsec import Text.PrettyPrint (render) diff --git a/cabal-install/src/Distribution/Client/ProjectFlags.hs b/cabal-install/src/Distribution/Client/ProjectFlags.hs index d33afd8b9b4..4dacc3188bc 100644 --- a/cabal-install/src/Distribution/Client/ProjectFlags.hs +++ b/cabal-install/src/Distribution/Client/ProjectFlags.hs @@ -1,5 +1,4 @@ {-# LANGUAGE DerivingVia #-} -{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PatternSynonyms #-} module Distribution.Client.ProjectFlags diff --git a/cabal-install/src/Distribution/Client/ProjectOrchestration.hs b/cabal-install/src/Distribution/Client/ProjectOrchestration.hs index ccabd4fe8bb..2dbdc9e0e83 100644 --- a/cabal-install/src/Distribution/Client/ProjectOrchestration.hs +++ b/cabal-install/src/Distribution/Client/ProjectOrchestration.hs @@ -103,7 +103,7 @@ module Distribution.Client.ProjectOrchestration ) where import Distribution.Client.Compat.Prelude -import System.Directory +import Distribution.Compat.Directory ( makeAbsolute ) import Prelude () diff --git a/cabal-install/src/Distribution/Client/ProjectPlanOutput.hs b/cabal-install/src/Distribution/Client/ProjectPlanOutput.hs index ff394124191..b5a5f8d38f9 100644 --- a/cabal-install/src/Distribution/Client/ProjectPlanOutput.hs +++ b/cabal-install/src/Distribution/Client/ProjectPlanOutput.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} @@ -36,6 +37,7 @@ import qualified Distribution.Solver.Types.ComponentDeps as ComponentDeps import qualified Distribution.Compat.Binary as Binary import Distribution.Compat.Graph (Graph, Node) import qualified Distribution.Compat.Graph as Graph +import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS) import Distribution.InstalledPackageInfo (InstalledPackageInfo) import Distribution.Package import qualified Distribution.PackageDescription as PD @@ -69,8 +71,9 @@ import Prelude () import Control.Monad ((<=<)) import qualified Data.ByteString.Builder as BB -import qualified Data.ByteString.Lazy as BS +#ifndef __MHS__ import Data.Either (fromRight) +#endif import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Text as Text @@ -80,6 +83,12 @@ import System.IO import Distribution.Simple.Program.GHC (packageDbArgsDb) +#ifdef __MHS__ +fromRight :: b -> Either a b -> b +fromRight _ (Right x) = x +fromRight d (Left _) = d +#endif + ----------------------------------------------------------------------------- -- Writing plan.json files -- @@ -521,7 +530,7 @@ data PostBuildProjectStatus = PostBuildProjectStatus -- or data file generation failing. -- -- This is a subset of 'packagesInvalidByChangedLibDeps'. - , packagesLibDepGraph :: Graph (Node (WithMachine UnitId) ElaboratedPlanPackage) + , packagesLibDepGraph :: Graph (WithMachine UnitId) (Node (WithMachine UnitId) ElaboratedPlanPackage) -- ^ A subset of the plan graph, including only dependency-on-library -- edges. That is, dependencies /on/ libraries, not dependencies /of/ -- libraries. This tells us all the libraries that packages link to. @@ -644,7 +653,7 @@ postBuildProjectStatus -- The plan graph but only counting dependency-on-library edges. A -- library dependency is always on the same machine as the package. - packagesLibDepGraph :: Graph (Node (WithMachine UnitId) ElaboratedPlanPackage) + packagesLibDepGraph :: Graph (WithMachine UnitId) (Node (WithMachine UnitId) ElaboratedPlanPackage) packagesLibDepGraph = Graph.fromDistinctList [ Graph.N pkg (Graph.nodeKey pkg) libdeps @@ -795,7 +804,7 @@ readPackagesUpToDateCacheFile DistDirLayout{distProjectCacheFile} = withBinaryFile (distProjectCacheFile "up-to-date") ReadMode - (Binary.decodeOrFailIO <=< BS.hGetContents) + (Binary.decodeOrFailIO <=< hGetContentsLBS) where handleDecodeFailure = fmap (fromRight Set.empty) diff --git a/cabal-install/src/Distribution/Client/ProjectPlanning.hs b/cabal-install/src/Distribution/Client/ProjectPlanning.hs index 0a7e17758d9..5e9379a63f7 100644 --- a/cabal-install/src/Distribution/Client/ProjectPlanning.hs +++ b/cabal-install/src/Distribution/Client/ProjectPlanning.hs @@ -1,8 +1,8 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} -{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} -- | @@ -73,6 +73,7 @@ module Distribution.Client.ProjectPlanning -- * Utils required for building , pkgHasEphemeralBuildTargets , elabBuildTargetWholeComponents + , determineCoverageFor , configureCompiler , configureToolchains , projectPackageDbsFor @@ -109,7 +110,9 @@ import Text.PrettyPrint ( colon , comma , fsep +#ifndef __MHS__ , hang +#endif , punctuate , quotes , render @@ -118,6 +121,7 @@ import Text.PrettyPrint , ($$) , ($+$) ) +import Distribution.Utils.LogProgress import Prelude () import Distribution.Client.Config @@ -174,7 +178,9 @@ import Distribution.Utils.Path hiding , () ) +#ifndef __MHS__ import qualified Hackage.Security.Client as Sec +#endif import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.InstSolverPackage @@ -238,6 +244,7 @@ import qualified Distribution.PackageDescription as PD import qualified Distribution.PackageDescription.Configuration as PD import qualified Distribution.Simple.Configure as Cabal import qualified Distribution.Simple.GHC as GHC +import Distribution.Simple.InstallDirs (InstallDirs (InstallDirs, datasubdir, libexecsubdir, libsubdir)) import qualified Distribution.Simple.InstallDirs as InstallDirs import qualified Distribution.Simple.LocalBuildInfo as Cabal import qualified Distribution.Simple.Setup as Cabal @@ -246,10 +253,9 @@ import qualified Distribution.Solver.Types.ComponentDeps as CD import qualified Distribution.Compat.Graph as Graph import Control.Exception (assert) -import Control.Monad (mapM_, sequence) import Control.Monad.IO.Class (liftIO) import Control.Monad.State as State (State, execState, runState, state) -import Data.Foldable (fold) +import Data.Foldable (fold, mapM_) import Data.Functor ((<&>)) import Data.List (deleteBy, groupBy) import qualified Data.List.NonEmpty as NE @@ -260,7 +266,7 @@ import Data.Traversable (mapAccumM) import Distribution.Client.Errors import Distribution.Solver.Types.ProjectConfigPath import GHC.Stack (HasCallStack) -import System.Directory (getCurrentDirectory) +import Distribution.Compat.Directory (getCurrentDirectory) import System.FilePath import qualified Text.PrettyPrint as Disp @@ -278,6 +284,21 @@ unhashedComponentIdOf elab = ++ case elabComponentName elab >>= Cabal.componentNameString of Nothing -> "" Just s -> "-" ++ prettyShow s +#ifdef __MHS__ +import Data.Monoid (Last (..)) + +instance Binary a => Binary (Last a) where + put (Last x) = put x + get = Last <$> get + +instance (Binary a1, Binary a2, Binary a3, Binary a4, Binary a5, Binary a6) => Binary (a1, a2, a3, a4, a5, a6) where + put (x1, x2, x3, x4, x5, x6) = put x1 >> put x2 >> put x3 >> put x4 >> put x5 >> put x6 + get = (,,,,,) <$> get <*> get <*> get <*> get <*> get <*> get + +instance (Binary a1, Binary a2, Binary a3, Binary a4, Binary a5, Binary a6, Binary a7) => Binary (a1, a2, a3, a4, a5, a6, a7) where + put (x1, x2, x3, x4, x5, x6, x7) = put x1 >> put x2 >> put x3 >> put x4 >> put x5 >> put x6 >> put x7 + get = (,,,,,,) <$> get <*> get <*> get <*> get <*> get <*> get <*> get +#endif -- | Check that an 'ElaboratedConfiguredPackage' actually makes -- sense under some 'ElaboratedSharedConfig'. @@ -1021,14 +1042,15 @@ rebuildInstallPlan -- each machine against that machine's compiler. liftIO $ sequence_ $ - mapWithMachine - ( \machine toolchain -> - checkBadPerPackageCompilerPaths - (machineProgramPaths machine) - (configuredPrograms (toolchainProgramDb toolchain)) - (getMapMappend (projectConfigSpecificPackage projectConfig)) - ) - toolchains + toList $ + mapWithMachine + ( \machine toolchain -> + checkBadPerPackageCompilerPaths + (machineProgramPaths machine) + (configuredPrograms (toolchainProgramDb toolchain)) + (getMapMappend (projectConfigSpecificPackage projectConfig)) + ) + toolchains -- Without cross-compilation there is no build machine, so nothing -- uses the build-machine program settings. They do not fall back to @@ -1556,6 +1578,13 @@ getPackageSourceHashes verbosity withRepoCtx solverPlan = do if null repoTarballPkgsToDownload && null repoTarballPkgsWithMetadata then return (Map.empty, []) else liftIO $ withRepoCtx $ \repoctx -> do +#ifdef __MHS__ + -- Secure repositories (the only ones carrying hashes as part of + -- their repo metadata) are not supported in this build, so there + -- are never any hashes available from repo metadata. (Uses of + -- secure repositories fail earlier, in 'verifyFetchedTarballs'.) + let hashesFromRepoMetadata = Map.empty +#else -- For tarballs from repos that do have hashes available as part of the -- repo metadata we now load up the index for each repo and retrieve -- the hashes for the packages @@ -1586,6 +1615,7 @@ getPackageSourceHashes verbosity withRepoCtx solverPlan = do $ repoTarballPkgsWithMetadata ] ) +#endif -- For tarballs from repos that do not have hashes available, download -- the ones we previously determined we need. @@ -2295,6 +2325,7 @@ elaborateInstallPlan , Just paths <- [Map.lookup (ann_id aid) exe_map1] , path <- paths ] + elab_comp :: ElaboratedComponent elab_comp = ElaboratedComponent{..} -- 3. Construct a preliminary ElaboratedConfiguredPackage, @@ -2533,6 +2564,7 @@ elaborateInstallPlan (elab0@ElaboratedConfiguredPackage{..}, elaborationWarnings) = elaborateSolverToCommon pkg + elab1, elab :: ElaboratedConfiguredPackage elab1 = elab0 { elabUnitId = newSimpleUnitId pkgInstalledId @@ -2645,6 +2677,7 @@ elaborateInstallPlan ) = (elaboratedPackage, libraryWayWarnings toolchains perPkgOption elabMachine pkgid >> buildOptionsAdjustmentWarnings) where + elaboratedPackage :: ElaboratedConfiguredPackage elaboratedPackage = ElaboratedConfiguredPackage{..} -- The machine this package is elaborated for, and the toolchain that @@ -3203,7 +3236,7 @@ needsProfilingLibShared lookupFlag compiler pkgid = -- | The 'Machine' of a solver-plan node, read from its machine-carrying -- 'SolverId' graph key. -solverNodeMachine :: (Graph.IsNode a, Graph.Key a ~ SolverId) => a -> Machine +solverNodeMachine :: Graph.IsNode SolverId a => a -> Machine solverNodeMachine = solverMachine . Graph.nodeKey -- | Decide, for every @(machine, package)@ in the plan, which library ways it @@ -3215,7 +3248,7 @@ solverNodeMachine = solverMachine . Graph.nodeKey -- over the whole plan partitions cleanly by machine. elaborateLibraryWays :: Toolchains - -> Graph.Graph NonSetupLibDepSolverPlanPackage + -> Graph.Graph SolverId NonSetupLibDepSolverPlanPackage -> (Machine -> PerPkgConfigFlag) -- ^ the per-package option lookup for a package of a given machine -> LibraryWays @@ -4033,8 +4066,7 @@ instance Package PrunedPackage where instance HasUnitId PrunedPackage where installedUnitId (PrunedPackage elab _) = installedUnitId elab -instance Graph.IsNode PrunedPackage where - type Key PrunedPackage = WithMachine UnitId +instance Graph.IsNode (WithMachine UnitId) PrunedPackage where nodeKey (PrunedPackage elab _) = Graph.nodeKey elab nodeNeighbors (PrunedPackage _ deps) = deps @@ -4130,7 +4162,7 @@ pruneInstallPlanPass1 pkgs pruned_packages :: [ElaboratedPlanPackage] pruned_packages = maybe [] (map (mapConfiguredPackage fromPrunedPackage)) (Graph.closure graph roots) - closed_graph :: Graph.Graph ElaboratedPlanPackage + closed_graph :: Graph.Graph (WithMachine UnitId) ElaboratedPlanPackage closed_graph = Graph.fromDistinctList pruned_packages -- whether any package has repl targets enabled, and we need to use multi-repl. @@ -4585,10 +4617,10 @@ pruneInstallPlanToDependencies pkgTargets installPlan = -- if the remaining graph is broken or not, ie any packages with dangling -- dependencies. If there are then we cannot prune the given targets. checkBrokenDeps - :: Graph.Graph ElaboratedPlanPackage + :: Graph.Graph (WithMachine UnitId) ElaboratedPlanPackage -> Either CannotPruneDependencies - (Graph.Graph ElaboratedPlanPackage) + (Graph.Graph (WithMachine UnitId) ElaboratedPlanPackage) checkBrokenDeps graph = case Graph.broken graph of [] -> Right graph @@ -4738,9 +4770,10 @@ storePackageInstallDirs' -- directory, not at a directory of its own: one @lib@ holding a -- directory per unit, one @bin@, one package database beside them. -- A store laid out this way can be consumed directly by another build - -- system -- GHC's assembles its binary distribution by copying @lib/*@ - -- and @package.conf.d/*@ out of it -- which per-unit roots do not - -- allow, as there is then no one directory holding all the libraries. + -- system -- GHC's assembles its binary distribution by copying the + -- contents of @lib@ and @package.conf.d@ out of it -- which per-unit + -- roots do not allow, as there is then no one directory holding all + -- the libraries. prefix = storeDirectory machine toolchain bindir = prefix "bin" libdir = prefix "lib" prettyShow unitid @@ -4782,9 +4815,9 @@ computeInstallDirs storeDirLayout defaultInstallDirs elaboratedShared elab ) { -- absoluteInstallDirs sets these as 'undefined' but we have -- to use them as "Setup.hs configure" args - InstallDirs.libsubdir = "" - , InstallDirs.libexecsubdir = "" - , InstallDirs.datasubdir = "" + libsubdir = "" + , libexecsubdir = "" + , datasubdir = "" } | otherwise = -- use special simplified install dirs diff --git a/cabal-install/src/Distribution/Client/ProjectPlanning/Machine.hs b/cabal-install/src/Distribution/Client/ProjectPlanning/Machine.hs index 5d8e6b2a752..681ddeea338 100644 --- a/cabal-install/src/Distribution/Client/ProjectPlanning/Machine.hs +++ b/cabal-install/src/Distribution/Client/ProjectPlanning/Machine.hs @@ -1,6 +1,6 @@ {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} -{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE UndecidableInstances #-} -- | -- Module : Distribution.Client.ProjectPlanning.Machine @@ -17,6 +17,7 @@ module Distribution.Client.ProjectPlanning.Machine , toolMachine ) where +import Data.Foldable (Foldable) import Distribution.Client.Compat.Prelude import Prelude () @@ -44,8 +45,7 @@ instance Structured a => Structured (WithMachine a) instance Package pkg => Package (WithMachine pkg) where packageId (WithMachine _machine pkg) = packageId pkg -instance IsNode a => IsNode (WithMachine a) where - type Key (WithMachine a) = WithMachine (Key a) +instance IsNode k a => IsNode (WithMachine k) (WithMachine a) where nodeKey = fmap nodeKey nodeNeighbors = traverse nodeNeighbors diff --git a/cabal-install/src/Distribution/Client/ProjectPlanning/SetupPolicy.hs b/cabal-install/src/Distribution/Client/ProjectPlanning/SetupPolicy.hs index 1ac2e31b4ea..2e7cfa82dcc 100644 --- a/cabal-install/src/Distribution/Client/ProjectPlanning/SetupPolicy.hs +++ b/cabal-install/src/Distribution/Client/ProjectPlanning/SetupPolicy.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} - -- | Setup.hs script policy -- -- Handling for Setup.hs scripts is a bit tricky, part of it lives in the @@ -161,9 +159,7 @@ instance Package NonSetupLibDepSolverPlanPackage where packageId (NonSetupLibDepSolverPlanPackage spkg) = packageId spkg -instance IsNode NonSetupLibDepSolverPlanPackage where - type Key NonSetupLibDepSolverPlanPackage = SolverId - +instance IsNode SolverId NonSetupLibDepSolverPlanPackage where nodeKey (NonSetupLibDepSolverPlanPackage spkg) = nodeKey spkg @@ -181,7 +177,7 @@ instance IsNode NonSetupLibDepSolverPlanPackage where packageSetupScriptSpecVersion :: SetupScriptStyle -> PackageDescription - -> Graph.Graph NonSetupLibDepSolverPlanPackage + -> Graph.Graph SolverId NonSetupLibDepSolverPlanPackage -> ComponentDeps [SolverId] -> SetupCliVersion -- We're going to be using the internal Cabal library, so the spec version of diff --git a/cabal-install/src/Distribution/Client/ProjectPlanning/Types.hs b/cabal-install/src/Distribution/Client/ProjectPlanning/Types.hs index 933ee5c16e5..f24a748674c 100644 --- a/cabal-install/src/Distribution/Client/ProjectPlanning/Types.hs +++ b/cabal-install/src/Distribution/Client/ProjectPlanning/Types.hs @@ -1,5 +1,4 @@ {-# LANGUAGE LambdaCase #-} -{-# LANGUAGE TypeFamilies #-} -- | Types used while planning how to build everything in a project. -- @@ -157,6 +156,7 @@ import Text.PrettyPrint (hsep, parens, text) -- connections). type ElaboratedInstallPlan = GenericInstallPlan + (WithMachine UnitId) ElaboratedInstalledPackageInfo ElaboratedConfiguredPackage @@ -612,8 +612,7 @@ instance HasConfiguredId ElaboratedConfiguredPackage where instance HasUnitId ElaboratedConfiguredPackage where installedUnitId = elabUnitId -instance IsNode ElaboratedConfiguredPackage where - type Key ElaboratedConfiguredPackage = WithMachine UnitId +instance IsNode (WithMachine UnitId) ElaboratedConfiguredPackage where nodeKey elab = WithMachine (elabMachine elab) (elabUnitId elab) -- Each neighbour carries the machine of the plan node it refers to; see diff --git a/cabal-install/src/Distribution/Client/RebuildMonad.hs b/cabal-install/src/Distribution/Client/RebuildMonad.hs index adb3e049660..ddb1e251074 100644 --- a/cabal-install/src/Distribution/Client/RebuildMonad.hs +++ b/cabal-install/src/Distribution/Client/RebuildMonad.hs @@ -72,7 +72,7 @@ import Control.Monad import Control.Monad.Reader as Reader import Control.Monad.State as State import qualified Data.Map.Strict as Map -import System.Directory +import Distribution.Compat.Directory import System.FilePath -- | A monad layered on top of 'IO' to help with re-running actions when the diff --git a/cabal-install/src/Distribution/Client/Reconfigure.hs b/cabal-install/src/Distribution/Client/Reconfigure.hs index 680bfb4fc28..1d91f61797a 100644 --- a/cabal-install/src/Distribution/Client/Reconfigure.hs +++ b/cabal-install/src/Distribution/Client/Reconfigure.hs @@ -3,9 +3,10 @@ module Distribution.Client.Reconfigure (Check (..), reconfigure) where import Distribution.Client.Compat.Prelude +import Prelude () import Data.Monoid (Any (..)) -import System.Directory (doesFileExist) +import Distribution.Compat.Directory (doesFileExist) import Distribution.Simple.Configure (localBuildInfoFile) import Distribution.Simple.Setup (Flag, flagToMaybe, toFlag) @@ -123,7 +124,7 @@ reconfigure when frc $ configureAction flags extraArgs globalFlags return config' where - mbWorkDir = flagToMaybe $ configWorkingDir $ savedConfigureFlags config + mbWorkDir = flagToMaybe $ setupWorkingDir $ configCommonFlags $ savedConfigureFlags config -- Changing the verbosity does not require reconfiguration, but the new -- verbosity should be used if reconfiguring. checkVerb :: Check (ConfigFlags, b) diff --git a/cabal-install/src/Distribution/Client/Run.hs b/cabal-install/src/Distribution/Client/Run.hs index 6a09dd97289..114592a4530 100644 --- a/cabal-install/src/Distribution/Client/Run.hs +++ b/cabal-install/src/Distribution/Client/Run.hs @@ -40,7 +40,7 @@ import Distribution.Simple.Program.Find import Distribution.Simple.Program.Run import Distribution.Simple.Register (internalPackageDBPath) -import Distribution.Simple.Setup (ConfigFlags (..)) +import Distribution.Simple.Setup (CommonSetupFlags (..), ConfigFlags (..)) import Distribution.Simple.Utils ( addLibraryPath , dieWithException @@ -137,7 +137,7 @@ run :: Verbosity -> LocalBuildInfo -> Executable -> [String] -> IO () run verbosity lbi exe@Executable{exeName} exeArgs = do let exeName' = prettyShow exeName curDir <- absoluteWorkingDirLBI lbi - let distPref = fromFlag $ configDistPref $ configFlags lbi + let distPref = fromFlag $ setupDistPref $ configCommonFlags $ configFlags lbi buildPref = buildDir lbi pkg_descr = localPkgDescr lbi i = interpretSymbolicPathLBI lbi -- See Note [Symbolic paths] in Distribution.Utils.Path diff --git a/cabal-install/src/Distribution/Client/Sandbox.hs b/cabal-install/src/Distribution/Client/Sandbox.hs index 97828dcf283..22cd60aa630 100644 --- a/cabal-install/src/Distribution/Client/Sandbox.hs +++ b/cabal-install/src/Distribution/Client/Sandbox.hs @@ -56,7 +56,7 @@ import Distribution.Utils.Path hiding , () ) -import System.Directory +import Distribution.Compat.Directory ( getCurrentDirectory ) diff --git a/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs b/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs index afcc9e52c43..83f076d4d7b 100644 --- a/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs +++ b/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs @@ -55,7 +55,7 @@ import Distribution.Simple.Setup ) import Distribution.Simple.Utils (debug, warn) import Distribution.Solver.Types.ConstraintSource -import System.Directory (doesFileExist) +import Distribution.Compat.Directory (doesFileExist) import System.FilePath (()) import System.IO.Error (isDoesNotExistError) import Text.PrettyPrint (($+$)) diff --git a/cabal-install/src/Distribution/Client/SavedFlags.hs b/cabal-install/src/Distribution/Client/SavedFlags.hs index c28eea5fcdf..65067aabdd3 100644 --- a/cabal-install/src/Distribution/Client/SavedFlags.hs +++ b/cabal-install/src/Distribution/Client/SavedFlags.hs @@ -16,7 +16,7 @@ import Distribution.Simple.Utils ) import Distribution.Verbosity -import System.Directory (doesFileExist) +import Distribution.Compat.Directory (doesFileExist) import System.FilePath (takeDirectory) writeSavedArgs :: Verbosity -> FilePath -> [String] -> IO () diff --git a/cabal-install/src/Distribution/Client/ScriptUtils.hs b/cabal-install/src/Distribution/Client/ScriptUtils.hs index 42162241a2b..bc280926194 100644 --- a/cabal-install/src/Distribution/Client/ScriptUtils.hs +++ b/cabal-install/src/Distribution/Client/ScriptUtils.hs @@ -206,7 +206,7 @@ import Distribution.Client.Errors import Distribution.Utils.Path ( unsafeMakeSymbolicPath ) -import System.Directory +import Distribution.Compat.Directory ( canonicalizePath , doesFileExist , getTemporaryDirectory diff --git a/cabal-install/src/Distribution/Client/Security/DNS.hs b/cabal-install/src/Distribution/Client/Security/DNS.hs index b989a852451..659f3db1242 100644 --- a/cabal-install/src/Distribution/Client/Security/DNS.hs +++ b/cabal-install/src/Distribution/Client/Security/DNS.hs @@ -44,6 +44,11 @@ import Distribution.Simple.Program -- constitute a significant new attack vector anyway. queryBootstrapMirrors :: Verbosity -> URI -> IO [URI] +#ifdef __MHS__ +-- Secure repositories are not supported in this build, so no mirrors +-- are ever returned. +queryBootstrapMirrors _ _ = return [] +#else #if defined(MIN_VERSION_resolv) || defined(MIN_VERSION_windns) -- use @resolv@ package for performing DNS queries queryBootstrapMirrors verbosity repoUri @@ -162,6 +167,7 @@ parseNsLookupTxt = go0 [] [] qstr acc (c:cs) = qstr (c:acc) cs qstr _ [] = Nothing +#endif #endif ---------------------------------------------------------------------------- diff --git a/cabal-install/src/Distribution/Client/Security/HTTP.hs b/cabal-install/src/Distribution/Client/Security/HTTP.hs index 316363f4830..f9149e98697 100644 --- a/cabal-install/src/Distribution/Client/Security/HTTP.hs +++ b/cabal-install/src/Distribution/Client/Security/HTTP.hs @@ -1,3 +1,31 @@ +{-# LANGUAGE CPP #-} +#ifdef __MHS__ +-- | Implementation of the HTTP hook used by secure repositories. +-- +-- Secure (@hackage-security@) repositories are not supported in this +-- build: every use of a secure repository fails with an error. This +-- module is retained as a stub so that existing import sites keep +-- resolving. +module Distribution.Client.Security.HTTP (transportAdapter) where + +import Distribution.Client.Compat.Prelude +import Prelude () + +import Distribution.Client.HttpUtils + ( HttpTransport + ) +import System.IO.Error (userError) + +-- | Translate from a secure repository's HTTP hook to cabal-install's +-- own 'HttpTransport'. +-- +-- Secure repositories are not supported in this build; this always fails. +transportAdapter :: Verbosity -> IO HttpTransport -> IO a +transportAdapter _ _ = + throwIO $ + userError + "Secure repositories are not supported in this build of cabal-install." +#else -- | Implementation of 'HttpLib' using cabal-install's own 'HttpTransport' module Distribution.Client.Security.HTTP (HttpLib, transportAdapter) where @@ -195,3 +223,4 @@ wrapCustomEx act = HC.handleChecked (\(ex :: IOException) -> go ex) act where go ex = HC.throwChecked (HC.SomeRemoteError ex) +#endif diff --git a/cabal-install/src/Distribution/Client/SetupWrapper.hs b/cabal-install/src/Distribution/Client/SetupWrapper.hs index 2645db4de3e..aa476c9163b 100644 --- a/cabal-install/src/Distribution/Client/SetupWrapper.hs +++ b/cabal-install/src/Distribution/Client/SetupWrapper.hs @@ -1,8 +1,6 @@ {-# LANGUAGE CPP #-} -{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -Wno-redundant-constraints #-} {- FOURMOLU_DISABLE -} @@ -26,8 +24,6 @@ module Distribution.Client.SetupWrapper ( SetupRunnerArgs(..) , SPostConfigurePhase(..) , InLibraryArgs(..) - , SetupRunnerRes - , RightFlagsForPhase , setupWrapper , SetupScriptOptions (..) , SetupDependencies (..) @@ -173,52 +169,47 @@ import Distribution.Client.SetupHooks.CallHooksExe import Control.Concurrent.STM (TVar, readTVarIO) import qualified Data.ByteString.Lazy as BS -import Data.Kind (Type, Constraint) import qualified Data.Map.Lazy as Map -import Data.Type.Equality ( type (==) ) -import Data.Type.Bool ( If ) -import System.Directory (doesFileExist) +import Distribution.Compat.Directory (doesFileExist) import System.FilePath ((<.>), ()) import Data.Functor ((<&>)) import System.IO (Handle, hPutStr) -import System.Process (StdStream (..)) -import qualified System.Process as Process +import Distribution.Compat.Process (StdStream (..)) +import qualified Distribution.Compat.Process as Process #ifdef mingw32_HOST_OS import Distribution.Simple.Utils ( withTempDirectory ) import Control.Exception ( bracket ) -import System.Directory ( doesDirectoryExist ) +import Distribution.Compat.Directory ( doesDirectoryExist ) import System.FilePath ( equalFilePath, takeDirectory, takeFileName ) import qualified System.Win32 as Win32 #endif -------------------------------------------------------------------------------- -data SPostConfigurePhase (flags :: Type) where - SBuildPhase :: SPostConfigurePhase BuildFlags - SHaddockPhase :: SPostConfigurePhase HaddockFlags - SReplPhase :: SPostConfigurePhase ReplFlags - SCopyPhase :: SPostConfigurePhase CopyFlags - SRegisterPhase :: SPostConfigurePhase RegisterFlags - STestPhase :: SPostConfigurePhase TestFlags - SBenchPhase :: SPostConfigurePhase BenchmarkFlags - -data SetupWrapperSpec - = TryInLibrary Type - | UseGeneralSetup - -type family RightFlagsForPhase (flags :: Type) (setupSpec :: SetupWrapperSpec) :: Constraint where - RightFlagsForPhase flags UseGeneralSetup = () - RightFlagsForPhase flags (TryInLibrary flags') = flags ~ flags' - -data SetupRunnerArgs (spec :: SetupWrapperSpec) where +-- | Singleton identifying the setup phase after configuration, indexed by +-- the command flags for the phase and the result produced by the phase. +data SPostConfigurePhase flags result where + SBuildPhase :: SPostConfigurePhase BuildFlags [MonitorFilePath] + SHaddockPhase :: SPostConfigurePhase HaddockFlags [MonitorFilePath] + SReplPhase :: SPostConfigurePhase ReplFlags [MonitorFilePath] + SCopyPhase :: SPostConfigurePhase CopyFlags () + SRegisterPhase :: SPostConfigurePhase RegisterFlags () + STestPhase :: SPostConfigurePhase TestFlags () + SBenchPhase :: SPostConfigurePhase BenchmarkFlags () + +-- | Arguments to 'setupWrapper', indexed by the command flags and the +-- result produced by running the phase. The constructors rule out +-- mismatched combinations (e.g. post-configure flags together with the +-- external setup method), so no separate constraint is needed. +data SetupRunnerArgs flags result where NotInLibrary - :: SetupRunnerArgs UseGeneralSetup + :: SetupRunnerArgs flags () InLibraryArgs - :: InLibraryArgs (Maybe LocalBuildInfo) flags - -> SetupRunnerArgs (TryInLibrary flags) + :: InLibraryArgs (Maybe LocalBuildInfo) flags result + -> SetupRunnerArgs flags result -- | What the in-library method needs for a phase. -- @@ -228,32 +219,21 @@ data SetupRunnerArgs (spec :: SetupWrapperSpec) where -- build type it depends on whether the Cabal version used by the package -- matches the one cabal-install was built against). Once the in-library method -- is chosen (see 'inLibraryMethod') it holds a 'LocalBuildInfo' outright. -data InLibraryArgs (lbi :: Type) (flags :: Type) where +data InLibraryArgs lbi flags result where InLibraryConfigureArgs :: ElaboratedSharedConfig -> ElaboratedReadyPackage -> TVar (PerMachine InstalledPackageIndex) - -> InLibraryArgs lbi ConfigFlags + -> InLibraryArgs lbi ConfigFlags (Maybe LocalBuildInfo) InLibraryPostConfigureArgs - :: SPostConfigurePhase flags + :: SPostConfigurePhase flags result -> lbi - -> InLibraryArgs lbi flags - -type family SetupRunnerRes (spec :: SetupWrapperSpec) where - SetupRunnerRes UseGeneralSetup = () - SetupRunnerRes (TryInLibrary phase) = InLibraryPhaseRes phase - -type family InLibraryPhaseRes flags where - InLibraryPhaseRes ConfigFlags = Maybe LocalBuildInfo - InLibraryPhaseRes BuildFlags = [MonitorFilePath] - InLibraryPhaseRes HaddockFlags = [MonitorFilePath] - InLibraryPhaseRes ReplFlags = [MonitorFilePath] - InLibraryPhaseRes _ = () + -> InLibraryArgs lbi flags result -- | @Setup@ encapsulates the outcome of configuring a setup method to build a -- particular package. -data Setup spec = Setup - { setupMethod :: SetupMethod spec +data Setup flags result = Setup + { setupMethod :: SetupMethod flags result , setupScriptOptions :: SetupScriptOptions , setupVersion :: Version , setupBuildType :: BuildType @@ -264,25 +244,25 @@ data Setup spec = Setup -- -- The in-library method can only be chosen when the 'SetupRunnerArgs' allow -- it, and it carries everything needed to run in-library. -data SetupMethod (spec :: SetupWrapperSpec) where +data SetupMethod flags result where -- | Directly use Cabal library functions, bypassing the Setup -- mechanism entirely. - LibraryMethod :: InLibraryArgs LocalBuildInfo flags -> SetupMethod (TryInLibrary flags) + LibraryMethod :: InLibraryArgs LocalBuildInfo flags result -> SetupMethod flags result -- | run Cabal commands through a custom \"Setup\" executable - ExternalMethod :: FilePath -> SetupMethod spec + ExternalMethod :: FilePath -> SetupMethod flags result -- | The in-library method for the given arguments, if they permit one. -- -- A post-configure phase without a 'LocalBuildInfo' means the package was -- configured by an external Setup, so later phases must use one too. -inLibraryMethod :: SetupRunnerArgs spec -> Maybe (SetupMethod spec) +inLibraryMethod :: SetupRunnerArgs flags result -> Maybe (SetupMethod flags result) inLibraryMethod NotInLibrary = Nothing inLibraryMethod (InLibraryArgs libArgs) = - LibraryMethod <$> case libArgs of + case libArgs of InLibraryConfigureArgs elabSharedConfig elabReadyPkg ipiTVar -> - Just (InLibraryConfigureArgs elabSharedConfig elabReadyPkg ipiTVar) + Just (LibraryMethod (InLibraryConfigureArgs elabSharedConfig elabReadyPkg ipiTVar)) InLibraryPostConfigureArgs sPhase mbLBI -> - InLibraryPostConfigureArgs sPhase <$> mbLBI + LibraryMethod . InLibraryPostConfigureArgs sPhase <$> mbLBI -- TODO: The 'setupWrapper' and 'SetupScriptOptions' should be split into two -- parts: one that has no policy and just does as it's told with all the @@ -429,13 +409,13 @@ workingDir options = case useWorkingDir options of _ -> "." -- | A @SetupRunner@ implements a 'SetupMethod'. -type SetupRunner kind = +type SetupRunner flags result = Verbosity -> SetupScriptOptions -> BuildType -> [String] - -> SetupRunnerArgs kind - -> IO (SetupRunnerRes kind) + -> SetupRunnerArgs flags result + -> IO result -- | Prepare to build a package by configuring a 'SetupMethod'. The returned -- 'Setup' object identifies the method. The 'SetupScriptOptions' may be changed @@ -445,9 +425,9 @@ getSetup :: Verbosity -> SetupScriptOptions -> Maybe PackageDescription - -> Maybe (SetupMethod spec) + -> Maybe (SetupMethod flags result) -- ^ the in-library method, if the arguments permit one - -> IO (Setup spec) + -> IO (Setup flags result) getSetup verbosity options mpkg mbLibraryMethod = do pkg <- maybe getPkg return mpkg let options' = @@ -480,6 +460,15 @@ getSetup verbosity options mpkg mbLibraryMethod = do (tryFindPackageDesc verbosity mbWorkDir >>= readGenericPackageDescription verbosity mbWorkDir . relativeSymbolicPath) <&> packageDescription +-- Note [MHS support] +-- ~~~~~~~~~~~~~~~~~~~ +-- When cabal-install itself is built with MHS (MicroHS), the in-library +-- setup method is unavailable: 'withSetupMethod' always selects the +-- external setup method and "Distribution.Client.InLibrary" only provides +-- stubs. This keeps this module free of the type-level machinery (closed +-- type families, promoted data kinds) that MHS cannot compile, while GHC +-- builds retain the full in-library path. +-- -- | Decide if we're going to be able to do a direct internal call to the -- entry point in the Cabal library or if we're going to have to compile -- and execute an external Setup.hs script. @@ -488,10 +477,15 @@ chooseSetupMethod -> SetupScriptOptions -> PackageDescription -> BuildType - -> Maybe (SetupMethod spec) + -> Maybe (SetupMethod flags result) -- ^ the in-library method, if the arguments permit one - -> IO (Version, SetupMethod spec, SetupScriptOptions) + -> IO (Version, SetupMethod flags result, SetupScriptOptions) chooseSetupMethod verbosity options pkg buildType' mbLibraryMethod = +#ifdef __MHS__ + -- MHS cannot use the in-library setup method, so always use the + -- external setup method ('chooseSetupMethod' below always selects it). + externalMethod +#else case mbLibraryMethod of Nothing -> externalMethod Just libraryMethod @@ -518,11 +512,14 @@ chooseSetupMethod verbosity options pkg buildType' mbLibraryMethod = | otherwise -> do debug verbosity $ "Using in-library setup method with build-type " ++ show buildType' return (cabalVersion, libraryMethod, options) +#endif where +#ifndef __MHS__ hasHooksMain = case cabalLibFromOptions options of Just (v, _) -> v >= mkVersion [3, 17] Nothing -> False +#endif externalMethod = do debug verbosity $ "Using external setup method with build-type " ++ show buildType' debug verbosity $ case useSetupDependencies options of @@ -536,17 +533,18 @@ chooseSetupMethod verbosity options pkg buildType' mbLibraryMethod = compileExternalExe verbosity options pkg buildType' WantSetup return (version, ExternalMethod path, options') -runSetupMethod :: WithCallStack (SetupMethod UseGeneralSetup -> SetupRunner UseGeneralSetup) +runSetupMethod :: WithCallStack (SetupMethod flags () -> SetupRunner flags ()) runSetupMethod (ExternalMethod path) = externalSetupMethod path - +runSetupMethod (LibraryMethod _) = + error "internal error: runSetupMethod called for the in-library setup method" -- | Run a configured 'Setup' with specific arguments. runSetup :: Verbosity - -> Setup UseGeneralSetup + -> Setup flags () -> [String] -- ^ command-line arguments - -> SetupRunnerArgs UseGeneralSetup - -> IO (SetupRunnerRes UseGeneralSetup) + -> SetupRunnerArgs flags () + -> IO () runSetup verbosity setup args0 setupArgs = do let method = setupMethod setup options = setupScriptOptions setup @@ -600,7 +598,7 @@ verbosityHack ver args0 -- | Run a command through a configured 'Setup'. runSetupCommand :: Verbosity - -> Setup UseGeneralSetup + -> Setup flags () -> CommandUI flags -- ^ command definition -> (flags -> CommonSetupFlags) @@ -608,8 +606,8 @@ runSetupCommand -- ^ command flags -> [String] -- ^ extra command-line arguments - -> SetupRunnerArgs UseGeneralSetup - -> IO (SetupRunnerRes UseGeneralSetup) + -> SetupRunnerArgs flags () + -> IO () runSetupCommand verbosity setup cmd getCommonFlags flags extraArgs setupArgs = -- The 'setupWorkingDir' flag corresponds to a global argument which needs to -- be passed before the individual command (e.g. 'configure' or 'build'). @@ -622,9 +620,7 @@ runSetupCommand verbosity setup cmd getCommonFlags flags extraArgs setupArgs = -- | Configure a 'Setup' and run a command in one step. The command flags -- may depend on the Cabal library version in use. setupWrapper - :: forall setupSpec flags - . RightFlagsForPhase flags setupSpec - => Verbosity + :: Verbosity -> SetupScriptOptions -> Maybe PackageDescription -> CommandUI flags @@ -632,8 +628,8 @@ setupWrapper -> (Version -> IO flags) -- ^ produce command flags given the Cabal library version -> (Version -> [String]) - -> SetupRunnerArgs setupSpec - -> IO (SetupRunnerRes setupSpec) + -> SetupRunnerArgs flags result + -> IO result setupWrapper verbosity options mpkg cmd getCommonFlags getFlags getExtraArgs wrapperArgs = do setup <- getSetup verbosity options mpkg (inLibraryMethod wrapperArgs) let version = setupVersion setup @@ -643,7 +639,14 @@ setupWrapper verbosity options mpkg cmd getCommonFlags getFlags getExtraArgs wra extraArgs = getExtraArgs version case setupMethod setup of ExternalMethod path -> do - runSetupCommand verbosity setup{setupMethod = ExternalMethod path} + let extSetup = Setup + { setupMethod = ExternalMethod path + , setupScriptOptions = setupScriptOptions setup + , setupVersion = setupVersion setup + , setupBuildType = setupBuildType setup + , setupPackage = setupPackage setup + } + runSetupCommand verbosity extSetup cmd getCommonFlags flags extraArgs NotInLibrary return $ case wrapperArgs of NotInLibrary -> () @@ -659,73 +662,75 @@ setupWrapper verbosity options mpkg cmd getCommonFlags getFlags getExtraArgs wra SRegisterPhase -> () STestPhase -> () SBenchPhase -> () - LibraryMethod (InLibraryConfigureArgs elabSharedConfig elabReadyPkg@(ReadyPackage elabPkg) ipiTVar) -> do - -- Start from the pre-configured compiler ProgramDb of the - -- package's own machine, augmented with all builtin programs - -- (restored as unconfigured). - -- This ensures: - -- (a) configureAllKnownPrograms inside configureFinal skips - -- compiler programs (already configured at project level), - -- (b) builtin preprocessors like alex and happy are present as - -- unconfigured programs, so configureFinal's - -- configureAllKnownPrograms can find them using the - -- per-package search path (respecting extra-prog-path). - -- See (1) in Note [Constructing the ProgramDb]. - - -- Apply per-package user-supplied program args/paths. - -- See (2)(a) in Note [Constructing the ProgramDb] - baseProgDb <- - -- Use 'mkProgramDb' to pass user-supplied per-package - -- program options (--PROG-options=...). - mkProgramDb verbHandles flags - (restoreProgramDb builtinPrograms $ - elabProgramDb elabSharedConfig elabPkg) - setupProgDb <- - prependProgramSearchPath verbosity - (useExtraPathEnv options) - (useExtraEnvOverrides options) - baseProgDb - -- Read the project InstalledPackageIndex of the package's machine to - -- avoid needing to query @ghc-pkg@ to obtain it. See (ProjIPI3) and - -- (ProjIPI4) in Note [Per-project InstalledPackageIndex] - -- in Distribution.Client.ProjectBuilding. - ipi <- (`onMachine` elabMachine elabPkg) <$> readTVarIO ipiTVar - lbi0 <- - InLibrary.configure - (InLibrary.libraryConfigureInputsFromElabPackage - verbHandles - (setupBuildType setup) - setupProgDb - elabSharedConfig - elabReadyPkg - ipi - extraArgs - ) - flags - let progs0 = LBI.withPrograms lbi0 - -- See (2)(b) in Note [Constructing the ProgramDb] - progs1 <- updatePathProgDb verbosity progs0 - let - lbi = - lbi0 - { LBI.withPrograms = progs1 - } - mbWorkDir = useWorkingDir options - distPref = useDistPref options - -- Write the LocalBuildInfo to disk. This is needed, for instance, if we - -- skip re-configuring; we retrieve the LocalBuildInfo stored on disk from - -- the previous invocation of 'configure' and pass it to 'build'. - writePersistBuildConfig mbWorkDir distPref lbi - return (Just lbi) - LibraryMethod (InLibraryPostConfigureArgs sPhase lbi) -> - case sPhase of - SBuildPhase -> InLibrary.build verbHandles flags lbi extraArgs - SHaddockPhase -> InLibrary.haddock verbHandles flags lbi extraArgs - SReplPhase -> InLibrary.repl verbHandles flags lbi extraArgs - SCopyPhase -> InLibrary.copy verbHandles flags lbi extraArgs - STestPhase -> InLibrary.test verbHandles flags lbi extraArgs - SBenchPhase -> InLibrary.bench verbHandles flags lbi extraArgs - SRegisterPhase -> InLibrary.register flags lbi extraArgs + LibraryMethod libArgs -> + case libArgs of + InLibraryConfigureArgs elabSharedConfig elabReadyPkg@(ReadyPackage elabPkg) ipiTVar -> do + -- Start from the pre-configured compiler ProgramDb of the + -- package's own machine, augmented with all builtin programs + -- (restored as unconfigured). + -- This ensures: + -- (a) configureAllKnownPrograms inside configureFinal skips + -- compiler programs (already configured at project level), + -- (b) builtin preprocessors like alex and happy are present as + -- unconfigured programs, so configureFinal's + -- configureAllKnownPrograms can find them using the + -- per-package search path (respecting extra-prog-path). + -- See (1) in Note [Constructing the ProgramDb]. + + -- Apply per-package user-supplied program args/paths. + -- See (2)(a) in Note [Constructing the ProgramDb] + baseProgDb <- + -- Use 'mkProgramDb' to pass user-supplied per-package + -- program options (--PROG-options=...). + mkProgramDb verbHandles flags + (restoreProgramDb builtinPrograms $ + elabProgramDb elabSharedConfig elabPkg) + setupProgDb <- + prependProgramSearchPath verbosity + (useExtraPathEnv options) + (useExtraEnvOverrides options) + baseProgDb + -- Read the project InstalledPackageIndex of the package's machine to + -- avoid needing to query @ghc-pkg@ to obtain it. See (ProjIPI3) and + -- (ProjIPI4) in Note [Per-project InstalledPackageIndex] + -- in Distribution.Client.ProjectBuilding. + ipi <- (`onMachine` elabMachine elabPkg) <$> readTVarIO ipiTVar + lbi0 <- + InLibrary.configure + (InLibrary.libraryConfigureInputsFromElabPackage + verbHandles + (setupBuildType setup) + setupProgDb + elabSharedConfig + elabReadyPkg + ipi + extraArgs + ) + flags + let progs0 = LBI.withPrograms lbi0 + -- See (2)(b) in Note [Constructing the ProgramDb] + progs1 <- updatePathProgDb verbosity progs0 + let + lbi = + lbi0 + { LBI.withPrograms = progs1 + } + mbWorkDir = useWorkingDir options + distPref = useDistPref options + -- Write the LocalBuildInfo to disk. This is needed, for instance, if we + -- skip re-configuring; we retrieve the LocalBuildInfo stored on disk from + -- the previous invocation of 'configure' and pass it to 'build'. + writePersistBuildConfig mbWorkDir distPref lbi + return (Just lbi) + InLibraryPostConfigureArgs sPhase lbi -> + case sPhase of + SBuildPhase -> InLibrary.build verbHandles flags lbi extraArgs + SHaddockPhase -> InLibrary.haddock verbHandles flags lbi extraArgs + SReplPhase -> InLibrary.repl verbHandles flags lbi extraArgs + SCopyPhase -> InLibrary.copy verbHandles flags lbi extraArgs + STestPhase -> InLibrary.test verbHandles flags lbi extraArgs + SBenchPhase -> InLibrary.bench verbHandles flags lbi extraArgs + SRegisterPhase -> InLibrary.register flags lbi extraArgs {- Note [Constructing the ProgramDb] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -807,7 +812,7 @@ invoke verbosity path args options = do -- ------------------------------------------------------------ -externalSetupMethod :: WithCallStack (FilePath -> SetupRunner UseGeneralSetup) +externalSetupMethod :: WithCallStack (FilePath -> SetupRunner flags ()) externalSetupMethod path verbosity options _ args NotInLibrary = #ifndef mingw32_HOST_OS invoke @@ -850,18 +855,17 @@ useCachedSetupExecutable :: BuildType -> Bool useCachedSetupExecutable bt = bt == Simple || bt == Configure -data ExternalExe = HooksExe | SetupExe -data WantedExternalExe (meth :: ExternalExe) where - WantHooks :: WantedExternalExe HooksExe - WantSetup :: WantedExternalExe SetupExe +data WantedExternalExe result where + WantHooks :: WantedExternalExe () + WantSetup :: WantedExternalExe (Version, FilePath, SetupScriptOptions) compileExternalExe :: Verbosity -> SetupScriptOptions -> PackageDescription -> BuildType - -> WantedExternalExe exe - -> IO (If (exe == HooksExe) () (Version, FilePath, SetupScriptOptions)) + -> WantedExternalExe result + -> IO result compileExternalExe verbosity options pkg bt wantedExe = do createDirectoryIfMissingVerbose verbosity True $ i (setupDir options) (cabalLibVersion, mCabalLibInstalledPkgId, options') <- diff --git a/cabal-install/src/Distribution/Client/Signal.hs b/cabal-install/src/Distribution/Client/Signal.hs index c009d805cd4..ca75004956f 100644 --- a/cabal-install/src/Distribution/Client/Signal.hs +++ b/cabal-install/src/Distribution/Client/Signal.hs @@ -8,7 +8,7 @@ where import qualified Control.Exception as Exception -#ifndef mingw32_HOST_OS +#if !defined(mingw32_HOST_OS) && !defined(__MHS__) import Control.Concurrent (myThreadId) import Control.Monad (void) import qualified System.Posix.Signals as Signals @@ -33,8 +33,10 @@ instance Show Terminated where -- It is a noop on Windows. installTerminationHandler :: IO () -#ifdef mingw32_HOST_OS +#if defined(mingw32_HOST_OS) || defined(__MHS__) +-- MicroHs has no 'System.Posix.Signals', so like on Windows there is +-- nothing to install. installTerminationHandler = return () #else diff --git a/cabal-install/src/Distribution/Client/SolverInstallPlan.hs b/cabal-install/src/Distribution/Client/SolverInstallPlan.hs index 33e96d74cf2..4e2c39fde7e 100644 --- a/cabal-install/src/Distribution/Client/SolverInstallPlan.hs +++ b/cabal-install/src/Distribution/Client/SolverInstallPlan.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} - -- | -- Module : Distribution.Client.SolverInstallPlan -- Copyright : (c) Duncan Coutts 2008 @@ -82,7 +80,7 @@ import qualified Distribution.Compat.Graph as Graph type SolverPlanPackage = ResolverPackage UnresolvedPkgLoc -type SolverPlanIndex = Graph SolverPlanPackage +type SolverPlanIndex = Graph SolverId SolverPlanPackage data SolverInstallPlan = SolverInstallPlan { planIndex :: !SolverPlanIndex @@ -285,7 +283,7 @@ nonSetupClosure -> SolverPlanIndex nonSetupClosure index pkgids0 = closure Graph.empty pkgids0 where - closure :: Graph SolverPlanPackage -> [SolverId] -> SolverPlanIndex + closure :: Graph SolverId SolverPlanPackage -> [SolverId] -> SolverPlanIndex closure completed [] = completed closure completed (pkgid : pkgids) = case Graph.lookup pkgid index of diff --git a/cabal-install/src/Distribution/Client/SourceFiles.hs b/cabal-install/src/Distribution/Client/SourceFiles.hs index bc046e329c1..0e14702a789 100644 --- a/cabal-install/src/Distribution/Client/SourceFiles.hs +++ b/cabal-install/src/Distribution/Client/SourceFiles.hs @@ -10,6 +10,7 @@ -- We can only use this code for non-Custom scripts; Custom scripts -- may have arbitrary extra dependencies (esp. new preprocessors) which -- we cannot "see" easily. +{-# LANGUAGE CPP #-} module Distribution.Client.SourceFiles (needElaboratedConfiguredPackage) where import Control.Monad ((>=>)) @@ -84,7 +85,9 @@ needComponent pkg_descr comp = needSetup :: Rebuild () needSetup = do void $ findFirstFileMonitored id ["Setup.hs", "Setup.lhs"] +#ifndef __MHS__ void $ findFirstFileMonitored id ["SetupHooks.hs", "SetupHooks.lhs"] +#endif needLibrary :: PackageDescription -> Library -> Rebuild () needLibrary diff --git a/cabal-install/src/Distribution/Client/SrcDist.hs b/cabal-install/src/Distribution/Client/SrcDist.hs index 6f6435ebfa6..782a99e0401 100644 --- a/cabal-install/src/Distribution/Client/SrcDist.hs +++ b/cabal-install/src/Distribution/Client/SrcDist.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} -- | Utilities to implement cabal @v2-sdist@. @@ -26,13 +27,22 @@ import Distribution.Utils.Path , makeSymbolicPath ) +#ifdef __MHS__ +import qualified Distribution.Client.Compat.Tar as Tar +import qualified Distribution.Client.GZipUtils as GZipUtils +#else import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Compression.GZip as GZip +#endif import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.Set as Set +#ifdef __MHS__ +import Distribution.Compat.Directory (canonicalizePath) +#else import System.Directory (canonicalizePath) +#endif import System.FilePath -- | List all source files of a given add-source dependency. Exits with error if @@ -108,4 +118,8 @@ packageDirToSdist verbosity gpd dir = do -- nicely. See #5596. setModTime :: Tar.Entry -> Tar.Entry setModTime entry = entry{Tar.entryTime = 1000000000} +#ifdef __MHS__ + normalize <$> GZipUtils.gzipCompress (Tar.write (fmap setModTime entries)) +#else return . normalize . GZip.compress . Tar.write $ fmap setModTime entries +#endif diff --git a/cabal-install/src/Distribution/Client/Store.hs b/cabal-install/src/Distribution/Client/Store.hs index ed5fdbf215f..a0c524e3f52 100644 --- a/cabal-install/src/Distribution/Client/Store.hs +++ b/cabal-install/src/Distribution/Client/Store.hs @@ -35,7 +35,7 @@ import Distribution.Simple.Utils ) import qualified Data.Set as Set -import System.Directory +import Distribution.Compat.Directory import System.FilePath -- $concurrency diff --git a/cabal-install/src/Distribution/Client/Tar.hs b/cabal-install/src/Distribution/Client/Tar.hs index 5675ac74743..66b15d6a0a5 100644 --- a/cabal-install/src/Distribution/Client/Tar.hs +++ b/cabal-install/src/Distribution/Client/Tar.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -Wno-orphans #-} ----------------------------------------------------------------------------- @@ -32,9 +33,16 @@ module Distribution.Client.Tar import Distribution.Client.Compat.Prelude import Prelude () +#ifdef __MHS__ +-- MicroHs has no @tar@ package: 'Distribution.Client.Compat.Tar' +-- is a full tar implementation there, so use it for everything. +import qualified Distribution.Client.Compat.Tar as Tar +import qualified Distribution.Client.Compat.Tar as TarComp +#else import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Distribution.Client.Compat.Tar as TarComp +#endif -- for foldEntries... import Control.Exception (throw) diff --git a/cabal-install/src/Distribution/Client/TargetProblem.hs b/cabal-install/src/Distribution/Client/TargetProblem.hs index 37df3fc753c..96ee75fe9fe 100644 --- a/cabal-install/src/Distribution/Client/TargetProblem.hs +++ b/cabal-install/src/Distribution/Client/TargetProblem.hs @@ -46,7 +46,21 @@ data TargetProblem a | TargetProblemNoSuchComponent PackageId ComponentName | -- | A custom target problem CustomTargetProblem a - deriving (Eq, Show, Functor) + deriving (Eq, Show) + +instance Functor TargetProblem where + fmap _ (TargetNotInProject pn) = TargetNotInProject pn + fmap _ (TargetAvailableInIndex pn) = TargetAvailableInIndex pn + fmap _ (TargetComponentNotProjectLocal pid cn sct) = TargetComponentNotProjectLocal pid cn sct + fmap _ (TargetComponentNotBuildable pid cn sct) = TargetComponentNotBuildable pid cn sct + fmap _ (TargetOptionalStanzaDisabledByUser pid cn sct) = TargetOptionalStanzaDisabledByUser pid cn sct + fmap _ (TargetOptionalStanzaDisabledBySolver pid cn sct) = TargetOptionalStanzaDisabledBySolver pid cn sct + fmap _ (TargetProblemUnknownComponent pn c) = TargetProblemUnknownComponent pn c + fmap _ (TargetProblemNoneEnabled ts ats) = TargetProblemNoneEnabled ts ats + fmap _ (TargetProblemNoTargets ts) = TargetProblemNoTargets ts + fmap _ (TargetProblemNoSuchPackage pid) = TargetProblemNoSuchPackage pid + fmap _ (TargetProblemNoSuchComponent pid cn) = TargetProblemNoSuchComponent pid cn + fmap f (CustomTargetProblem x) = CustomTargetProblem (f x) -- | Type alias for a 'TargetProblem' with no user-defined problems/errors. -- diff --git a/cabal-install/src/Distribution/Client/TargetSelector.hs b/cabal-install/src/Distribution/Client/TargetSelector.hs index 12e22e8c5b9..1a37947fea2 100644 --- a/cabal-install/src/Distribution/Client/TargetSelector.hs +++ b/cabal-install/src/Distribution/Client/TargetSelector.hs @@ -126,7 +126,7 @@ import Distribution.Simple.Utils import Distribution.Utils.Path ( getSymbolicPath ) -import qualified System.Directory as IO +import qualified Distribution.Compat.Directory as IO ( canonicalizePath , doesDirectoryExist , doesFileExist @@ -146,12 +146,44 @@ import qualified System.FilePath as FilePath , (<.>) , () ) +#ifndef __MHS__ import Text.EditDistance ( defaultEditCosts , restrictedDamerauLevenshteinDistance ) +#endif import qualified Prelude (foldr1) +#ifdef __MHS__ +-- | MHS fallback for the @edit-distance@ package: plain Levenshtein +-- distance (dynamic programming, quadratic in the input lengths, which +-- is fine for short target names). +defaultEditCosts :: () +defaultEditCosts = () + +restrictedDamerauLevenshteinDistance :: () -> String -> String -> Int +restrictedDamerauLevenshteinDistance _ = levDist + where + levDist :: String -> String -> Int + levDist xs ys = table !! lx !! ly + where + lx = length xs + ly = length ys + table = + [ [ dist i j | j <- [0 .. ly] ] + | i <- [0 .. lx] + ] + dist 0 j = j + dist i 0 = i + dist i j = + minimum + [ table !! (i - 1) !! j + 1 + , table !! i !! (j - 1) + 1 + , table !! (i - 1) !! (j - 1) + + if xs !! (i - 1) == ys !! (j - 1) then 0 else 1 + ] +#endif + -- ------------------------------------------------------------ -- * Target selector terms diff --git a/cabal-install/src/Distribution/Client/Targets.hs b/cabal-install/src/Distribution/Client/Targets.hs index e6d26dacb51..1bf8fdeda34 100644 --- a/cabal-install/src/Distribution/Client/Targets.hs +++ b/cabal-install/src/Distribution/Client/Targets.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE PatternSynonyms #-} -- | @@ -39,6 +40,7 @@ module Distribution.Client.Targets , userToPackageConstraint ) where +import Data.Foldable (Foldable) import Distribution.Client.Compat.Prelude import Prelude () @@ -63,13 +65,16 @@ import Distribution.Solver.Types.PackageIndex (PackageIndex) import qualified Distribution.Solver.Types.PackageIndex as PackageIndex import Distribution.Solver.Types.SourcePackage +#ifdef __MHS__ +import qualified Distribution.Client.Compat.Tar as Tar +#else import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar +#endif import Distribution.Client.FetchUtils import Distribution.Client.GlobalFlags ( RepoContext (..) ) -import qualified Distribution.Client.Tar as Tar import Distribution.Client.Utils (tryReadGenericPackageDesc) import Distribution.Types.PackageVersionConstraint ( PackageVersionConstraint (..) @@ -106,10 +111,11 @@ import Network.URI , URIAuth (..) , parseAbsoluteURI ) -import System.Directory +import Distribution.Compat.Directory ( doesDirectoryExist , doesFileExist ) +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import System.FilePath ( dropExtension , splitPath @@ -428,10 +434,10 @@ readPackageTarget verbosity = traverse modifyLocation either (dieWithException verbosity . ExtractTarballPackageErr . formatErr) return . check . accumEntryMap - . Tar.filterEntries isCabalFile + . Tar.foldEntries (\e es -> if isCabalFile e then Tar.Next e es else es) Tar.Done Tar.Fail . Tar.read . GZipUtils.maybeDecompress - =<< BS.readFile tarballFile + =<< readFileLBS tarballFile where formatErr msg = "Error reading " ++ tarballOriginalLoc ++ ": " ++ msg diff --git a/cabal-install/src/Distribution/Client/Types.hs b/cabal-install/src/Distribution/Client/Types.hs index 841a4dbc9d2..1c974469ce5 100644 --- a/cabal-install/src/Distribution/Client/Types.hs +++ b/cabal-install/src/Distribution/Client/Types.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} - ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- diff --git a/cabal-install/src/Distribution/Client/Types/ConfiguredPackage.hs b/cabal-install/src/Distribution/Client/Types/ConfiguredPackage.hs index d2673c0fc8e..fe360195529 100644 --- a/cabal-install/src/Distribution/Client/Types/ConfiguredPackage.hs +++ b/cabal-install/src/Distribution/Client/Types/ConfiguredPackage.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} - module Distribution.Client.Types.ConfiguredPackage ( ConfiguredPackage (..) ) where @@ -58,8 +56,7 @@ instance HasConfiguredId (ConfiguredPackage loc) where instance PackageFixedDeps (ConfiguredPackage loc) where depends = fmap (map (newSimpleUnitId . confInstId)) . confPkgDeps -instance IsNode (ConfiguredPackage loc) where - type Key (ConfiguredPackage loc) = UnitId +instance IsNode UnitId (ConfiguredPackage loc) where nodeKey = newSimpleUnitId . confPkgId -- TODO: if we update ConfiguredPackage to support order-only diff --git a/cabal-install/src/Distribution/Client/Types/ReadyPackage.hs b/cabal-install/src/Distribution/Client/Types/ReadyPackage.hs index ec9e89e1021..82d91603cde 100644 --- a/cabal-install/src/Distribution/Client/Types/ReadyPackage.hs +++ b/cabal-install/src/Distribution/Client/Types/ReadyPackage.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE UndecidableInstances #-} module Distribution.Client.Types.ReadyPackage ( GenericReadyPackage (..) @@ -31,8 +31,7 @@ newtype GenericReadyPackage srcpkg = ReadyPackage srcpkg -- see 'ConfiguredPacka ) -- Can't newtype derive this -instance IsNode srcpkg => IsNode (GenericReadyPackage srcpkg) where - type Key (GenericReadyPackage srcpkg) = Key srcpkg +instance IsNode k srcpkg => IsNode k (GenericReadyPackage srcpkg) where nodeKey (ReadyPackage spkg) = nodeKey spkg nodeNeighbors (ReadyPackage spkg) = nodeNeighbors spkg diff --git a/cabal-install/src/Distribution/Client/Types/SourceRepo.hs b/cabal-install/src/Distribution/Client/Types/SourceRepo.hs index a96b127db38..e5b12fac680 100644 --- a/cabal-install/src/Distribution/Client/Types/SourceRepo.hs +++ b/cabal-install/src/Distribution/Client/Types/SourceRepo.hs @@ -37,8 +37,8 @@ data SourceRepositoryPackage f = SourceRepositoryPackage deriving instance Eq (f FilePath) => Eq (SourceRepositoryPackage f) deriving instance Ord (f FilePath) => Ord (SourceRepositoryPackage f) deriving instance Show (f FilePath) => Show (SourceRepositoryPackage f) -deriving instance Binary (f FilePath) => Binary (SourceRepositoryPackage f) -deriving instance (Typeable f, Structured (f FilePath)) => Structured (SourceRepositoryPackage f) +instance Binary (f FilePath) => Binary (SourceRepositoryPackage f) +instance (Typeable f, Structured (f FilePath)) => Structured (SourceRepositoryPackage f) instance (Typeable f, NFData (f FilePath)) => NFData (SourceRepositoryPackage f) diff --git a/cabal-install/src/Distribution/Client/Upload.hs b/cabal-install/src/Distribution/Client/Upload.hs index 8e244e956ab..0e63217a854 100644 --- a/cabal-install/src/Distribution/Client/Upload.hs +++ b/cabal-install/src/Distribution/Client/Upload.hs @@ -1,12 +1,19 @@ +{-# LANGUAGE CPP #-} module Distribution.Client.Upload (upload, uploadDoc, report) where import Distribution.Client.Compat.Prelude +#ifndef __MHS__ import qualified Prelude as Unsafe (read) +#else +import Prelude () +#endif +#ifndef __MHS__ import Distribution.Client.HttpUtils ( HttpTransport (..) , remoteRepoTryUpgradeToHttps ) +#endif import Distribution.Client.Setup ( IsCandidate (..) , RepoContext (..) @@ -17,17 +24,22 @@ import Distribution.Client.Types.Credentials , Token (..) , Username (..) ) +#ifndef __MHS__ import Distribution.Client.Types.Repo (RemoteRepo (..), Repo, maybeRepoRemote) import Distribution.Client.Types.RepoName (unRepoName) import Distribution.Client.Config +#endif import Distribution.Simple.Utils (dieWithException, info, notice, toUTF8BS, warn) +#ifndef __MHS__ import Distribution.Utils.String (trim) import Distribution.Client.BuildReports.Anonymous (parseBuildReport) import qualified Distribution.Client.BuildReports.Anonymous as BuildReport import qualified Distribution.Client.BuildReports.Upload as BuildReport +#endif import Distribution.Client.Errors +#ifndef __MHS__ import Network.HTTP (Header (..), HeaderName (..)) import Network.URI (URI (uriAuthority, uriPath), URIAuth (uriRegName)) import System.Directory @@ -35,7 +47,9 @@ import System.FilePath (dropExtension, takeExtension, takeFileName, ()) import qualified System.FilePath.Posix as FilePath.Posix (()) import System.IO (hFlush, stdout) import System.IO.Echo (withoutInputEcho) +#endif +#ifndef __MHS__ -- > stripExtensions ["tar", "gz"] "foo.tar.gz" -- Just "foo" -- > stripExtensions ["tar", "gz"] "foo.gz.tar" @@ -46,6 +60,7 @@ stripExtensions exts path = foldM f path (reverse exts) f p e | takeExtension p == '.' : e = Just (dropExtension p) | otherwise = Nothing +#endif upload :: Verbosity @@ -56,6 +71,13 @@ upload -> IsCandidate -> [FilePath] -> IO () +#ifdef __MHS__ +-- | Upload packages to Hackage. +-- +-- Uploading is not supported in this build (there is no HTTP upload +-- transport); this always fails. +upload verbosity _ _ _ _ _ _ = dieWithException verbosity NoPostYet +#else upload verbosity repoCtxt mToken mUsername mPassword isCandidate paths = do let repos :: [Repo] repos = repoContextRepos repoCtxt @@ -106,6 +128,7 @@ upload verbosity repoCtxt mToken mUsername mPassword isCandidate paths = do -- This case shouldn't really happen, since we check in Main that we -- only pass tar.gz files to upload. Nothing -> dieWithException verbosity $ NotATarDotGzFile path +#endif uploadDoc :: Verbosity @@ -116,6 +139,13 @@ uploadDoc -> IsCandidate -> FilePath -> IO () +#ifdef __MHS__ +-- | Upload documentation to Hackage. +-- +-- Uploading is not supported in this build (there is no HTTP upload +-- transport); this always fails. +uploadDoc verbosity _ _ _ _ _ _ = dieWithException verbosity NoPostYet +#else uploadDoc verbosity repoCtxt mToken mUsername mPassword isCandidate path = do let repos = repoContextRepos repoCtxt transport <- repoContextGetTransport repoCtxt @@ -199,7 +229,9 @@ uploadDoc verbosity repoCtxt mToken mUsername mPassword isCandidate path = do "Package documentation successfully published. You can now view it at '" ++ show packageUri ++ "'." +#endif +#ifndef __MHS__ promptUsername :: String -> IO Username promptUsername domain = do putStr $ domain ++ " username: " @@ -214,8 +246,16 @@ promptPassword domain = do passwd <- withoutInputEcho $ fmap Password getLine putStrLn "" return passwd +#endif report :: Verbosity -> RepoContext -> Maybe Token -> Maybe Username -> Maybe Password -> IO () +#ifdef __MHS__ +-- | Upload build reports to Hackage. +-- +-- Uploading is not supported in this build (there is no HTTP upload +-- transport); this always fails. +report verbosity _ _ _ _ = dieWithException verbosity NoPostYet +#else report verbosity repoCtxt mToken mUsername mPassword = do let repos :: [Repo] repos = repoContextRepos repoCtxt @@ -251,7 +291,9 @@ report verbosity repoCtxt mToken mUsername mPassword = do (remoteRepoURI remoteRepo) [(report', Just buildLog)] return () +#endif +#ifndef __MHS__ handlePackage :: HttpTransport -> Verbosity @@ -308,3 +350,4 @@ createAuth domain mToken mUsername mPassword = case mToken of Username username <- maybe (promptUsername domain) return mUsername Password password <- maybe (promptPassword domain) return mPassword return $ Left (username, password) +#endif diff --git a/cabal-install/src/Distribution/Client/Utils.hs b/cabal-install/src/Distribution/Client/Utils.hs index 4298a823e8c..cc92040245a 100644 --- a/cabal-install/src/Distribution/Client/Utils.hs +++ b/cabal-install/src/Distribution/Client/Utils.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PatternSynonyms #-} @@ -40,6 +41,10 @@ module Distribution.Client.Utils , concatMapM , occursOnlyOrBefore , giveRTSWarning +#ifdef __MHS__ + , atomicModifyIORef + , getArgsWithResponseFiles +#endif ) where import Distribution.Client.Compat.Prelude @@ -48,9 +53,15 @@ import Prelude () import qualified Control.Exception as Exception ( finally ) +#ifdef __MHS__ +import qualified Control.Exception as Safe + ( bracket + ) +#else import qualified Control.Exception.Safe as Safe ( bracket ) +#endif import Control.Monad ( zipWithM_ ) @@ -71,6 +82,8 @@ import Distribution.Simple.Setup (Flag, pattern Flag, pattern NoFlag) import Distribution.Simple.Utils (dieWithException, findPackageDesc, noticeNoWrap, removeFileForcibly) import Distribution.Utils.Path ( CWD + , Dir + , File , FileOrDir (..) , Pkg , RelativePath @@ -83,21 +96,25 @@ import Distribution.Utils.Path ) import Distribution.Version -import System.Directory +import Distribution.Compat.Directory ( canonicalizePath , doesDirectoryExist , doesFileExist , listDirectory ) -import qualified System.Directory as Directory +import qualified Distribution.Compat.Directory as Directory import System.FilePath import System.IO ( Handle , hClose , hGetEncoding , hSetEncoding - , openTempFile ) +#ifdef __MHS__ +import Distribution.Compat.Internal.TempFile (openTempFile) +#else +import System.IO (openTempFile) +#endif import System.IO.Unsafe (unsafePerformIO) import qualified Data.Set as Set @@ -107,6 +124,13 @@ import Data.Time.Clock.POSIX (getCurrentTime) import Data.Time.LocalTime (getCurrentTimeZone, localDay) import Distribution.Simple.PackageDescription (readGenericPackageDescription) import Distribution.Types.GenericPackageDescription (GenericPackageDescription) +#ifdef __MHS__ +-- MicroHS provides 'System.Environment.getArgs' and 'Data.IORef', but +-- none of the GHC-only modules below. +import Data.IORef (IORef, readIORef, writeIORef) +import Distribution.Compat.ResponseFile (expandResponse) +import System.Environment (getArgs) +#else import GHC.Conc.Sync (getNumProcessors) import GHC.IO.Encoding ( TextEncoding (TextEncoding) @@ -116,7 +140,8 @@ import GHC.IO.Encoding.Failure ( CodingFailureMode (TransliterateCodingFailure) , recoverEncode ) -import qualified System.Directory as Dir +#endif +import qualified Distribution.Compat.Directory as Dir import qualified System.IO.Error as IOError -- | Generic merging utility. For sorted input lists this is a full outer join. @@ -224,8 +249,31 @@ logDirChange l (Just d) m = do -- The number of processors is not going to change during the duration of the -- program, so unsafePerformIO is safe here. numberOfProcessors :: Int +#ifdef __MHS__ +-- MicroHS provides no 'GHC.Conc.Sync.getNumProcessors' and its runtime is +-- single-threaded, so there is always exactly one processor. +numberOfProcessors = 1 +#else numberOfProcessors = unsafePerformIO getNumProcessors {-# NOINLINE numberOfProcessors #-} +#endif + +#ifdef __MHS__ +-- | Like 'GHC.ResponseFile.getArgsWithResponseFiles', which MicroHS does +-- not provide: the command line arguments with @\@file@ response files +-- expanded. See 'Distribution.Compat.ResponseFile.expandResponse'. +getArgsWithResponseFiles :: IO [String] +getArgsWithResponseFiles = expandResponse =<< getArgs + +-- | Single-threaded 'atomicModifyIORef' for MHS-ported modules: MicroHS has +-- no preemptive threads, so a read followed by a write is already atomic. +atomicModifyIORef :: IORef a -> (a -> (a, b)) -> IO b +atomicModifyIORef ref f = do + a <- readIORef ref + let (a', b) = f a + writeIORef ref a' + return b +#endif -- | Determine the number of jobs to use given the value of the '-j' flag. determineNumJobs :: Flag (Maybe Int) -> Int @@ -368,6 +416,11 @@ existsAndIsMoreRecentThan a b = do -- error. This function will ignore file handles that have a Unicode encoding -- set. It's a no-op for versions of `base` less than 4.4. relaxEncodingErrors :: Handle -> IO () +#ifdef __MHS__ +-- MicroHS provides no 'GHC.IO.Encoding' API; handles are always UTF-8, so +-- there is nothing to relax. +relaxEncodingErrors _ = return () +#else relaxEncodingErrors handle = do maybeEncoding <- hGetEncoding handle case maybeEncoding of @@ -377,6 +430,7 @@ relaxEncodingErrors handle = do in hSetEncoding handle (TextEncoding name decoder (fmap relax encoder)) _ -> return () +#endif -- | Like 'tryFindPackageDesc', but with error specific to add-source deps. tryReadAddSourcePackageDesc diff --git a/cabal-install/src/Distribution/Client/Utils/Json.hs b/cabal-install/src/Distribution/Client/Utils/Json.hs index ebbf2bb27fd..80c792f3cd8 100644 --- a/cabal-install/src/Distribution/Client/Utils/Json.hs +++ b/cabal-install/src/Distribution/Client/Utils/Json.hs @@ -18,6 +18,7 @@ module Distribution.Client.Utils.Json where import Distribution.Client.Compat.Prelude +import Prelude () import Data.Char (intToDigit) diff --git a/cabal-install/src/Distribution/Client/Utils/Newtypes.hs b/cabal-install/src/Distribution/Client/Utils/Newtypes.hs index 6bde1e986d1..66669faa2a7 100644 --- a/cabal-install/src/Distribution/Client/Utils/Newtypes.hs +++ b/cabal-install/src/Distribution/Client/Utils/Newtypes.hs @@ -13,6 +13,7 @@ module Distribution.Client.Utils.Newtypes where import Distribution.Client.Compat.Prelude +import Prelude () import Distribution.Client.Targets (UserConstraint) import Distribution.Client.Types.AllowNewer (AllowNewer (..), AllowOlder (..)) import Distribution.Compat.CharParsing diff --git a/cabal-install/src/Distribution/Client/VCS.hs b/cabal-install/src/Distribution/Client/VCS.hs index 08b1894f7c3..6138ac28d4b 100644 --- a/cabal-install/src/Distribution/Client/VCS.hs +++ b/cabal-install/src/Distribution/Client/VCS.hs @@ -90,7 +90,7 @@ import qualified Data.Char as Char import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Text as Text -import System.Directory +import Distribution.Compat.Directory ( doesDirectoryExist , doesFileExist , removePathForcibly @@ -103,7 +103,7 @@ import System.IO.Error ( isDoesNotExistError , isPermissionError ) -import qualified System.Process as Process +import qualified Distribution.Compat.Process as Process -- | A driver for a version control system, e.g. git, darcs etc. data VCS program = VCS diff --git a/cabal-install/src/Distribution/Client/Win32SelfUpgrade.hs b/cabal-install/src/Distribution/Client/Win32SelfUpgrade.hs index 4a5f839934f..ac241b6db4d 100644 --- a/cabal-install/src/Distribution/Client/Win32SelfUpgrade.hs +++ b/cabal-install/src/Distribution/Client/Win32SelfUpgrade.hs @@ -50,8 +50,8 @@ import Prelude () import qualified System.Win32 as Win32 import System.Win32 (DWORD, BOOL, HANDLE, LPCTSTR) import Foreign.Ptr (Ptr, nullPtr) -import System.Process (runProcess) -import System.Directory (canonicalizePath) +import Distribution.Compat.Process (runProcess) +import Distribution.Compat.Directory (canonicalizePath) import System.FilePath (takeBaseName, replaceBaseName, equalFilePath) import Distribution.Verbosity as Verbosity (showForCabal, verbosityFlags) diff --git a/cabal-install/src/Distribution/Deprecated/ParseUtils.hs b/cabal-install/src/Distribution/Deprecated/ParseUtils.hs index 65f80a73c24..4b3366740bf 100644 --- a/cabal-install/src/Distribution/Deprecated/ParseUtils.hs +++ b/cabal-install/src/Distribution/Deprecated/ParseUtils.hs @@ -58,6 +58,7 @@ module Distribution.Deprecated.ParseUtils , UnrecFieldParser ) where +import Data.Foldable (Foldable) import Distribution.Client.Compat.Prelude hiding (get) import Prelude () diff --git a/cabal-install/src/Distribution/Deprecated/ReadP.hs b/cabal-install/src/Distribution/Deprecated/ReadP.hs index 3670b565240..b832dd45803 100644 --- a/cabal-install/src/Distribution/Deprecated/ReadP.hs +++ b/cabal-install/src/Distribution/Deprecated/ReadP.hs @@ -61,6 +61,7 @@ module Distribution.Deprecated.ReadP where import Distribution.Client.Compat.Prelude +import Prelude () import Distribution.ReadE (ReadE (..)) import qualified Text.ParserCombinators.ReadP as T diff --git a/cabal-install/tests/IntegrationTests2.hs b/cabal-install/tests/IntegrationTests2.hs index d56f5b72f53..680a6d5ecc7 100644 --- a/cabal-install/tests/IntegrationTests2.hs +++ b/cabal-install/tests/IntegrationTests2.hs @@ -75,12 +75,12 @@ import qualified Data.Set as Set import Control.Concurrent (threadDelay) import Control.Exception hiding (assert) import Control.Monad -import System.Directory +import Distribution.Compat.Directory import System.Environment (setEnv) import System.FilePath import System.IO (hPutStrLn, stderr) import qualified System.Info -import System.Process (callProcess) +import Distribution.Compat.Process (callProcess) import Data.Tagged (Tagged (..)) import Test.Tasty diff --git a/cabal-install/tests/UnitTests/Distribution/Client/Configure.hs b/cabal-install/tests/UnitTests/Distribution/Client/Configure.hs index 21a6bcabb46..8ebe76ec215 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/Configure.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/Configure.hs @@ -13,7 +13,7 @@ import Distribution.Simple import Distribution.Simple.Flag import Distribution.Simple.Utils (removeFileForcibly) import Distribution.Verbosity -import System.Directory +import Distribution.Compat.Directory import System.FilePath import Test.Tasty import Test.Tasty.HUnit diff --git a/cabal-install/tests/UnitTests/Distribution/Client/FileMonitor.hs b/cabal-install/tests/UnitTests/Distribution/Client/FileMonitor.hs index f8f9b9c6d90..92382d6fc80 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/FileMonitor.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/FileMonitor.hs @@ -7,7 +7,7 @@ import Control.Exception import Control.Monad import Data.Proxy (Proxy (..)) import qualified Data.Set as Set -import qualified System.Directory as IO +import qualified Distribution.Compat.Directory as IO import System.FilePath import Prelude hiding (writeFile) import qualified Prelude as IO (writeFile) diff --git a/cabal-install/tests/UnitTests/Distribution/Client/GZipUtils.hs b/cabal-install/tests/UnitTests/Distribution/Client/GZipUtils.hs index 3680ffdbf7e..31a2456593d 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/GZipUtils.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/GZipUtils.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} module UnitTests.Distribution.Client.GZipUtils ( tests ) where @@ -5,6 +6,138 @@ module UnitTests.Distribution.Client.GZipUtils import Distribution.Client.Compat.Prelude import Prelude () +#ifdef __MHS__ +import Control.Exception (try) +import qualified Data.List as List +import Data.ByteString.Lazy as BSL (pack) +import Data.ByteString.Lazy.Char8 as BSLL (length, pack, take) +import Data.Either (isLeft) +import Distribution.Client.GZipUtils (maybeDecompress) + +import Test.Tasty +import Test.Tasty.HUnit +import Test.Tasty.QuickCheck + +tests :: [TestTree] +tests = + [ testCase "maybeDecompress" maybeDecompressUnitTest + , -- "decompress plain" property is non-trivial to state in general: + -- any input starting with the gzip magic bytes is handed to @gzip@, + -- so we only assert the passthrough for inputs without that prefix. + testProperty "passthrough plain" prop_maybeDecompress_plain + ] + +maybeDecompressUnitTest :: Assertion +maybeDecompressUnitTest = + assertBool "decompress plain" (maybeDecompress original == original) + >> assertBool "decompress gzip" (maybeDecompress compressedGZip == original) + >> assertBool "non-gzip input is returned untouched" (maybeDecompress compressedZlib == compressedZlib) + >> (runBrokenStream >>= assertBool "decompress broken stream" . isLeft) + where + original = BSLL.pack "original uncompressed input" + -- @gzip -n@ of "original uncompressed input". + compressedGZip = BSL.pack compressedGZipBytes + compressedGZipBytes = + [ 31 + , 139 + , 8 + , 0 + , 0 + , 0 + , 0 + , 0 + , 0 + , 3 + , 203 + , 47 + , 202 + , 76 + , 207 + , 204 + , 75 + , 204 + , 81 + , 40 + , 205 + , 75 + , 206 + , 207 + , 45 + , 40 + , 74 + , 45 + , 46 + , 78 + , 77 + , 81 + , 200 + , 204 + , 43 + , 40 + , 45 + , 1 + , 0 + , 175 + , 184 + , 107 + , 227 + , 27 + , 0 + , 0 + , 0 + ] + -- Raw zlib stream for the same input. Since proxy support was removed, + -- only gzip is decompressed, so this must come back untouched. + compressedZlib = + BSL.pack + [ 120 + , 156 + , 203 + , 47 + , 202 + , 76 + , 207 + , 204 + , 75 + , 204 + , 81 + , 40 + , 205 + , 75 + , 206 + , 207 + , 45 + , 40 + , 74 + , 45 + , 46 + , 78 + , 77 + , 81 + , 200 + , 204 + , 43 + , 40 + , 45 + , 1 + , 0 + , 152 + , 35 + , 10 + , 222 + ] + + -- A truncated gzip stream starts with the magic bytes, so it is handed + -- to @gzip@, which fails: the pure exception surfaces on evaluation. + runBrokenStream :: IO (Either SomeException ()) + runBrokenStream = try . void . evaluate . BSLL.length . BSL.pack $ List.take 20 compressedGZipBytes + +prop_maybeDecompress_plain :: [Word8] -> Property +prop_maybeDecompress_plain ws = + BSLL.take 2 bs /= BSL.pack [0x1f, 0x8b] ==> maybeDecompress bs === bs + where + bs = BSL.pack ws +#else import Codec.Compression.GZip as GZip import Codec.Compression.Zlib as Zlib import Control.Exception (try) @@ -56,3 +189,4 @@ prop_maybeDecompress_gzip ws = property $ maybeDecompress compressedGZip === ori where original = BSL.pack ws compressedGZip = GZip.compress original +#endif diff --git a/cabal-install/tests/UnitTests/Distribution/Client/Get.hs b/cabal-install/tests/UnitTests/Distribution/Client/Get.hs index f5d4bcc06ea..2be6737f6f6 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/Get.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/Get.hs @@ -13,7 +13,7 @@ import Control.Exception import Control.Monad import qualified Data.Text as T import Data.Typeable -import System.Directory +import Distribution.Compat.Directory import System.Exit import System.FilePath import System.IO.Error diff --git a/cabal-install/tests/UnitTests/Distribution/Client/InstallPlan.hs b/cabal-install/tests/UnitTests/Distribution/Client/InstallPlan.hs index 454e80c1d67..828a9b0be0a 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/InstallPlan.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/InstallPlan.hs @@ -1,5 +1,3 @@ -{-# LANGUAGE TypeFamilies #-} - module UnitTests.Distribution.Client.InstallPlan (tests) where import Distribution.Client.Compat.Prelude @@ -143,7 +141,7 @@ isReversePartialTopologicalOrder g vs = allConfiguredPackages :: HasUnitId srcpkg - => GenericInstallPlan ipkg srcpkg + => GenericInstallPlan k ipkg srcpkg -> Set UnitId allConfiguredPackages plan = Set.fromList @@ -157,7 +155,7 @@ allConfiguredPackages plan = data TestInstallPlan = TestInstallPlan - (GenericInstallPlan TestPkg TestPkg) + (GenericInstallPlan UnitId TestPkg TestPkg) Graph (UnitId -> Vertex) (Vertex -> UnitId) @@ -168,8 +166,7 @@ instance Show TestInstallPlan where data TestPkg = TestPkg PackageId UnitId [UnitId] deriving (Eq, Show) -instance IsNode TestPkg where - type Key TestPkg = UnitId +instance IsNode UnitId TestPkg where nodeKey (TestPkg _ ipkgid _) = ipkgid nodeNeighbors (TestPkg _ _ deps) = deps @@ -223,16 +220,16 @@ arbitraryTestInstallPlan = do -- It takes generators for installed and source packages and the chance that -- each package is installed (for those packages with no prerequisites). arbitraryInstallPlan - :: forall ipkg srcpkg - . ( IsGraph ipkg srcpkg - , Show (Key ipkg) - , Pretty (Key ipkg) + :: forall k ipkg srcpkg + . ( IsGraph k ipkg srcpkg + , Show k + , Pretty k ) => (Vertex -> [Vertex] -> Gen ipkg) -> (Vertex -> [Vertex] -> Gen srcpkg) -> Float -> Graph - -> Gen (InstallPlan.GenericInstallPlan ipkg srcpkg) + -> Gen (InstallPlan.GenericInstallPlan k ipkg srcpkg) arbitraryInstallPlan mkIPkg mkSrcPkg ipkgProportion graph = do (ipkgvs, srcpkgvs) <- bimap (map fst) (map fst) . partition snd diff --git a/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs b/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs index 6f462677a09..7a414515730 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs @@ -14,7 +14,7 @@ import qualified Data.Map as Map import Data.Maybe (fromMaybe) import qualified Data.Text as Text import Network.URI (URI) -import System.Directory (canonicalizePath, withCurrentDirectory) +import Distribution.Compat.Directory (canonicalizePath, withCurrentDirectory) import System.FilePath import System.IO.Unsafe (unsafePerformIO) diff --git a/cabal-install/tests/UnitTests/Distribution/Client/ProjectPlanning.hs b/cabal-install/tests/UnitTests/Distribution/Client/ProjectPlanning.hs index c786863be74..f29fbc7ed4b 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/ProjectPlanning.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/ProjectPlanning.hs @@ -14,6 +14,7 @@ import Distribution.System (Arch (..), OS (..), Platform (..)) import Distribution.Types.ComponentName import Distribution.Types.LibraryName import Distribution.Version (mkVersion) + import Test.Tasty import Test.Tasty.HUnit diff --git a/cabal-install/tests/UnitTests/Distribution/Client/Store.hs b/cabal-install/tests/UnitTests/Distribution/Client/Store.hs index 04f624c001a..6981ce25747 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/Store.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/Store.hs @@ -4,7 +4,7 @@ module UnitTests.Distribution.Client.Store (tests) where -- import Control.Concurrent (forkIO, threadDelay) -- import Control.Concurrent.MVar import qualified Data.Set as Set -import System.Directory +import Distribution.Compat.Directory import System.FilePath -- import System.Random diff --git a/cabal-install/tests/UnitTests/Distribution/Client/Tar.hs b/cabal-install/tests/UnitTests/Distribution/Client/Tar.hs index 4674e8aae09..ca80afd5779 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/Tar.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/Tar.hs @@ -1,5 +1,127 @@ +{-# LANGUAGE CPP #-} module UnitTests.Distribution.Client.Tar (tests) where +#ifdef __MHS__ +import Distribution.Client.Compat.Tar +import qualified Distribution.Client.Compat.Tar as Tar +import Distribution.Client.Tar (entriesToList, filterEntries, filterEntriesM) + +import Test.Tasty +import Test.Tasty.HUnit + +import Control.Monad.Writer.Lazy (WriterT, runWriterT, tell) +import qualified Data.ByteString.Lazy as BS +import qualified Data.ByteString.Lazy.Char8 as BS.Char8 + +tests :: [TestTree] +tests = + [ testCase "filterEntries" filterTest + , testCase "filterEntriesM" filterMTest + , testCase "writeReadRoundTrip" roundTripTest + , testCase "foldlEntries" foldlTest + , testCase "toTarPath" toTarPathTest + ] + +filterTest :: Assertion +filterTest = do + let e1 = getFileEntry "file1" "x" + e2 = getFileEntry "file2" "y" + assertEqual "Unexpected result for filter" "xz" $ + entriesToString $ + filterEntries unpackCheck $ + Next e1 $ + Next e2 Done + assertEqual "Unexpected result for filter" "z" $ + entriesToString $ + filterEntries unpackCheck Done + assertEqual "Unexpected result for filter" "xf" $ + entriesToString $ + filterEntries unpackCheck $ + Next e1 $ + Next e2 $ + Fail "f" + +filterMTest :: Assertion +filterMTest = do + let e1 = getFileEntry "file1" "x" + e2 = getFileEntry "file2" "y" + (r, w) <- runWriterT $ filterEntriesM unpackCheckM $ Next e1 $ Next e2 Done + assertEqual "Unexpected result for filterM" "xz" $ entriesToString r + assertEqual "Unexpected result for filterM w" "tt" w + + (r1, w1) <- runWriterT $ filterEntriesM unpackCheckM Done + assertEqual "Unexpected result for filterM" "z" $ entriesToString r1 + assertEqual "Unexpected result for filterM w" "" w1 + + (r2, w2) <- runWriterT $ filterEntriesM unpackCheckM $ Next e1 $ Next e2 $ Fail "f" + assertEqual "Unexpected result for filterM" "xf" $ entriesToString r2 + assertEqual "Unexpected result for filterM w" "tt" w2 + +getFileEntry :: FilePath -> [Char] -> Entry +getFileEntry pth dta = case toTarPath False pth of + Left err -> error ("getFileEntry: " ++ err) + Right tp -> fileEntry tp dta' + where + dta' = BS.Char8.pack dta + +roundTripTest :: Assertion +roundTripTest = do + dirTp <- case toTarPath True "pkg-1.0/sub" of + Left err -> assertFailure ("toTarPath: " ++ err) + Right tp -> return tp + let longName = "pkg-1.0/" ++ replicate 120 'l' ++ ".txt" + entries = + [ directoryEntry dirTp + , getFileEntry "pkg-1.0/sub/file.txt" "hello" + , getFileEntry "pkg-1.0/empty.txt" "" + , getFileEntry longName "long" + ] + decoded = entriesToList (Tar.read (write entries)) + -- Directory entries are stored with a trailing slash; the overlong + -- name round-trips through a GNU longname entry. + assertEqual "round trip preserves paths" ("pkg-1.0/sub/" : ["pkg-1.0/sub/file.txt", "pkg-1.0/empty.txt", longName]) (map entryPath decoded) + assertEqual "round trip preserves contents" ["", "hello", "", "long"] (map entryBytes decoded) + assertEqual "round trip preserves permissions" (map entryPermissions entries) (map entryPermissions decoded) + where + entryBytes e = case entryContent e of + NormalFile c _ -> BS.Char8.unpack c + Directory -> "" + OtherEntryType _ c _ -> BS.Char8.unpack c + +foldlTest :: Assertion +foldlTest = do + let e1 = getFileEntry "a" "x" + e2 = getFileEntry "b" "y" + entries = Next e1 (Next e2 Done) :: Entries String + assertEqual "foldlEntries collects paths" (Right ["a", "b"]) $ + foldlEntries (\acc e -> acc ++ [entryPath e]) [] entries + assertEqual "foldlEntries reports failure" (Left ("boom", ["a"])) $ + foldlEntries (\acc e -> acc ++ [entryPath e]) [] (Next e1 (Fail "boom" :: Entries String)) + +toTarPathTest :: Assertion +toTarPathTest = do + assertEqual "relative path accepted" (Right (TarPath "a/b")) (toTarPath False "a/b") + case toTarPath True "/abs" of + Left _ -> return () + Right _ -> assertFailure "absolute path must be rejected" + case toTarPath False "a/../../b" of + Left _ -> return () + Right _ -> assertFailure "escaping path must be rejected" + +unpackNormalFile :: Entry -> String +unpackNormalFile e = BS.Char8.unpack $ case entryContent e of + NormalFile dta _ -> dta + _ -> error "Invalid entryContent" + +unpackCheck :: Entry -> Bool +unpackCheck e = unpackNormalFile e /= "y" + +unpackCheckM :: Entry -> WriterT String IO Bool +unpackCheckM e = tell "t" >> return (unpackCheck e) + +entriesToString :: Entries String -> String +entriesToString = foldEntries (\e acc -> unpackNormalFile e ++ acc) "z" id +#else import Codec.Archive.Tar (GenEntry, foldEntries) import Codec.Archive.Tar.Entry (simpleEntry, toTarPath) import Distribution.Client.Tar (filterEntries, filterEntriesM) @@ -76,3 +198,4 @@ unpackCheckM e = tell "t" >> return (unpackCheck e) entriesToString :: Entries String -> String entriesToString = foldEntries (\e acc -> unpackNormalFile e ++ acc) "z" id +#endif diff --git a/cabal-install/tests/UnitTests/Distribution/Client/UserConfig.hs b/cabal-install/tests/UnitTests/Distribution/Client/UserConfig.hs index 07c95178bf3..58c652ba794 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/UserConfig.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/UserConfig.hs @@ -7,7 +7,7 @@ module UnitTests.Distribution.Client.UserConfig import Control.Exception (bracket) import Control.Monad (replicateM_) import Data.List (sort) -import System.Directory +import Distribution.Compat.Directory ( doesFileExist , getCurrentDirectory , getTemporaryDirectory diff --git a/cabal-install/tests/UnitTests/Distribution/Client/VCS.hs b/cabal-install/tests/UnitTests/Distribution/Client/VCS.hs index a2f1dc32814..fab3f4e3f8f 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/VCS.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/VCS.hs @@ -26,7 +26,7 @@ import Control.Exception import Control.Monad.State (StateT, execStateT, liftIO) import qualified Control.Monad.State as State -import System.Directory +import Distribution.Compat.Directory import System.FilePath import System.IO import System.Random diff --git a/cabal-testsuite/main/cabal-tests.hs b/cabal-testsuite/main/cabal-tests.hs index c2be5f9e118..5506be6b0a2 100644 --- a/cabal-testsuite/main/cabal-tests.hs +++ b/cabal-testsuite/main/cabal-tests.hs @@ -36,8 +36,8 @@ import qualified System.Clock as Clock import System.IO import System.FilePath import System.Exit -import System.Process (readProcessWithExitCode, showCommandForUser) -import System.Directory +import Distribution.Compat.Process (readProcessWithExitCode, showCommandForUser) +import Distribution.Compat.Directory import Distribution.Pretty import Data.Maybe diff --git a/cabal-testsuite/src/Test/Cabal/Monad.hs b/cabal-testsuite/src/Test/Cabal/Monad.hs index 67e14f84e9d..ac74ed0c06e 100644 --- a/cabal-testsuite/src/Test/Cabal/Monad.hs +++ b/cabal-testsuite/src/Test/Cabal/Monad.hs @@ -121,12 +121,12 @@ import Data.Monoid (mempty) import Distribution.Simple.Utils hiding (info) import GHC.Stack import Options.Applicative -import System.Directory +import Distribution.Compat.Directory import System.Exit import System.FilePath import System.IO import System.IO.Error (isDoesNotExistError) -import System.Process hiding (env) +import Distribution.Compat.Process hiding (env) import Test.Cabal.Run data CommonArgs = CommonArgs diff --git a/cabal-testsuite/src/Test/Cabal/Prelude.hs b/cabal-testsuite/src/Test/Cabal/Prelude.hs index 8fa5099226e..015d0baa74a 100644 --- a/cabal-testsuite/src/Test/Cabal/Prelude.hs +++ b/cabal-testsuite/src/Test/Cabal/Prelude.hs @@ -100,7 +100,7 @@ import Data.Char qualified as Char import Data.List (isPrefixOf, stripPrefix) import Data.Maybe (fromMaybe, isJust, mapMaybe) import Network.Wait (waitTcpVerbose) -import System.Directory +import Distribution.Compat.Directory import System.Environment import System.Exit (ExitCode (..)) import System.FilePath @@ -108,8 +108,8 @@ import System.FilePath.Glob qualified as Glob (compile, globDir1) import System.FilePath.Posix qualified as Posix import System.FilePath.Windows qualified as Windows import System.IO -import System.OsRelease qualified as OSR -import System.Process +import qualified System.OsRelease as OSR +import Distribution.Compat.Process #ifndef mingw32_HOST_OS import System.Posix.Resource @@ -805,7 +805,7 @@ withRemoteRepo repoDir m = do r <- runReaderT m (env{testHaveRepo = True}) -- Windows fails to kill the python server when the function above -- is complete, so we kill it directly via CMD. - when (buildOS == Windows) $ void $ createProcess_ "kill python" $ System.Process.shell "taskkill /F /IM python3.exe" + when (buildOS == Windows) $ void $ createProcess_ "kill python" $ Distribution.Compat.Process.shell "taskkill /F /IM python3.exe" pure r ) diff --git a/cabal-testsuite/src/Test/Cabal/Run.hs b/cabal-testsuite/src/Test/Cabal/Run.hs index 10e9d02cbbc..cf14a10807f 100644 --- a/cabal-testsuite/src/Test/Cabal/Run.hs +++ b/cabal-testsuite/src/Test/Cabal/Run.hs @@ -11,11 +11,11 @@ module Test.Cabal.Run import Distribution.Simple.Program.Run import Control.Concurrent.Async -import System.Directory +import Distribution.Compat.Directory import System.Exit import System.FilePath import System.IO -import System.Process +import Distribution.Compat.Process -- | The result of invoking the command line. data Result = Result diff --git a/cabal-testsuite/src/Test/Cabal/Server.hs b/cabal-testsuite/src/Test/Cabal/Server.hs index 1e3e01e59b3..f35f62a81b2 100644 --- a/cabal-testsuite/src/Test/Cabal/Server.hs +++ b/cabal-testsuite/src/Test/Cabal/Server.hs @@ -31,7 +31,7 @@ import Distribution.Simple.Program import Foreign.C.Error (Errno (..), ePIPE) import System.Exit import System.IO -import System.Process +import Distribution.Compat.Process import Text.Read (readMaybe) import Prelude hiding (log) diff --git a/cabal-testsuite/src/Test/Cabal/Workdir.hs b/cabal-testsuite/src/Test/Cabal/Workdir.hs index cdb7f1d85b6..b0a2f296d1a 100644 --- a/cabal-testsuite/src/Test/Cabal/Workdir.hs +++ b/cabal-testsuite/src/Test/Cabal/Workdir.hs @@ -7,6 +7,7 @@ import Distribution.Simple.Configure import Distribution.Simple.Setup import Distribution.Utils.Path ( Dist + , Dir , FileOrDir (..) , Pkg , SymbolicPath @@ -14,7 +15,7 @@ import Distribution.Utils.Path , makeSymbolicPath ) -import System.Directory +import Distribution.Compat.Directory import System.Environment (getExecutablePath) import System.FilePath diff --git a/cabal-validate/cabal-validate.cabal b/cabal-validate/cabal-validate.cabal index 84bc882779d..cba4dbe1a16 100644 --- a/cabal-validate/cabal-validate.cabal +++ b/cabal-validate/cabal-validate.cabal @@ -39,6 +39,7 @@ executable cabal-validate build-depends: , base >=4 && <5 , bytestring >=0.11 && <1 + , Cabal-syntax >=3.19 && <3.20 , containers >=0.6 && <1 , directory >=1.0 && <2 , filepath >=1 && <2 diff --git a/cabal-validate/src/Cli.hs b/cabal-validate/src/Cli.hs index d806e077943..7192d955750 100644 --- a/cabal-validate/src/Cli.hs +++ b/cabal-validate/src/Cli.hs @@ -46,7 +46,7 @@ import Options.Applicative , value ) import qualified Options.Applicative as Opt -import System.Directory (getCurrentDirectory) +import Distribution.Compat.Directory (getCurrentDirectory) import System.Exit (exitSuccess) import System.Info (arch, os) import System.Process.Typed (proc, readProcessStdout_) diff --git a/cabal-validate/src/ProcessUtil.hs b/cabal-validate/src/ProcessUtil.hs index 86c5c16e73f..a04369ca5b4 100644 --- a/cabal-validate/src/ProcessUtil.hs +++ b/cabal-validate/src/ProcessUtil.hs @@ -13,7 +13,7 @@ import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy as T (toStrict) import qualified Data.Text.Lazy.Encoding as T (decodeUtf8) -import System.Directory (withCurrentDirectory) +import Distribution.Compat.Directory (withCurrentDirectory) import System.Exit (ExitCode (ExitFailure, ExitSuccess)) import System.Process.Typed (ExitCodeException (..), proc, readProcess, runProcess) diff --git a/cabal.mhs.project b/cabal.mhs.project new file mode 100644 index 00000000000..a9af5f0210b --- /dev/null +++ b/cabal.mhs.project @@ -0,0 +1,46 @@ +-- Project file for building with the minimal/stable (mhs) toolchain. +-- +-- The mhs backend cannot use every dependency of the default build. +-- Sources that need such dependencies are adapted behind compatibility +-- seams or fallbacks instead: +-- +-- * @cabal list@ pattern matching uses a case-insensitive substring +-- fallback ('Distribution.Client.List') rather than regex-posix, and +-- the corresponding error carries a plain 'String' +-- ('Distribution.Client.Errors'); +-- * 'Distribution.Compat.Directory' stands in for "System.Directory"; +-- * opening a browser prints the URL instead of using open-browser; +-- * password prompts use @stty@ through the compatibility shim instead +-- of the echo package; +-- * @Distribution.Fields.Lexer@ is used from its pregenerated form +-- (regenerating it requires alex, and without GHC-specific extensions, +-- i.e. WITHOUT @alex -g@). +-- +-- The generated SPDX and Extension enumerations are intentionally left +-- unpruned. +-- +-- NOTE: the pregenerated lexer is checked in as +-- @Cabal-syntax/src/Distribution/Fields/Lexer.hs@ (alex 3.5.4.2, +-- WITHOUT @-g@), so the GHC side of this project builds end to end. +-- The @.x@ source remains authoritative; regenerate it from +-- @Cabal-syntax/@ with @alex src/Distribution/Fields/Lexer.x@ +-- @-o src/Distribution/Fields/Lexer.hs@ (without @-g@). +-- +-- CPP macro convention: MicroHs defines @__MHS__@ itself, so @__MHS__@ is +-- the canonical macro; a manual @-DMHS@ flag is accepted as a fallback. +-- Portability seams use @#if defined(__MHS__) || defined(MHS)@. +import: project-cabal/constraints.config + +packages: + Cabal + , Cabal-syntax + , Cabal-hooks + , cabal-install + , cabal-install-solver + , hooks-exe + +-- Don't include tests or benchmarks for the minimal-toolchain build +tests: False +benchmarks: False + +index-state: hackage.haskell.org 2026-07-02T14:25:01Z diff --git a/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs b/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs index a59799cce10..b7574561cd2 100644 --- a/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs +++ b/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE DuplicateRecordFields #-} @@ -18,6 +19,7 @@ module Distribution.Client.SetupHooks.CallHooksExe -- base import GHC.Stack +#ifndef __MHS__ -- bytestring import Data.ByteString.Lazy as LBS ( hGetContents @@ -26,9 +28,10 @@ import Data.ByteString.Lazy as LBS ) -- process -import qualified System.Process as P +import qualified Distribution.Compat.Process as P import System.Process.CommunicationHandle ( readCreateProcessWithExitCodeCommunicationHandle ) +#endif -- filepath import System.FilePath @@ -36,6 +39,7 @@ import System.FilePath -- Cabal import Distribution.Compat.Prelude +import Prelude () import qualified Distribution.Compat.Binary as Binary import Distribution.Simple ( autoconfSetupHooks ) @@ -56,7 +60,7 @@ import Distribution.Utils.Path , Dist , Pkg , SymbolicPath - , FileOrDir(..) + , FileOrDir(..), Dir , interpretSymbolicPath ) import Distribution.Verbosity @@ -84,6 +88,10 @@ callHooksExe -> String -- ^ name of the hook to run -> inputs -- ^ argument to the hook -> IO outputs +#ifdef __MHS__ +callHooksExe _ _ hookName _ = + error ("Distribution.Client.SetupHooks.CallHooksExe: build-type 'Hooks' (" ++ hookName ++ ") is not supported in this MHS build of Cabal.") +#else callHooksExe verb hooksExe hookName input = do (ex, output) <- -- The arguments to the external hooks executable are: @@ -116,6 +124,7 @@ callHooksExe verb hooksExe hookName input = do HookFailed hookName $ CouldNotDecodeOutput output offset err Right (_, _, res) -> return res +#endif -- | Construct a 'SetupHooks' that runs the hooks of the external hooks executable -- at the given path through the CLI. @@ -201,6 +210,10 @@ runExternalPreBuildRules -> FilePath -- ^ path to external hooks executable -> PreBuildComponentInputs -> IO [MonitorFilePath] +#ifdef __MHS__ +runExternalPreBuildRules _ _ _ = + error "Distribution.Client.SetupHooks.CallHooksExe: build-type 'Hooks' is not supported in this MHS build of Cabal." +#else runExternalPreBuildRules verbHandles hooksExe pbci@PreBuildComponentInputs { buildingWhat = what @@ -223,6 +236,7 @@ runExternalPreBuildRules verbHandles hooksExe ( \ rId cmd -> hook "runPreBuildRule" (rId, cmd) ) verbosity lbi tgt rulesMap return monitors +#endif -- | The path to the external hooks executable. hooksProgFilePath diff --git a/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe/Errors.hs b/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe/Errors.hs index 89b0954a2da..329d8e4a46d 100644 --- a/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe/Errors.hs +++ b/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe/Errors.hs @@ -15,7 +15,7 @@ import Distribution.Compat.Binary import Distribution.Simple.Utils -- base -import GHC.Exception +import Control.Exception (Exception (..)) import Data.Int ( Int64 ) import Data.Typeable diff --git a/solver-benchmarks/HackageBenchmark.hs b/solver-benchmarks/HackageBenchmark.hs index 12025b5246f..73de9b4043c 100644 --- a/solver-benchmarks/HackageBenchmark.hs +++ b/solver-benchmarks/HackageBenchmark.hs @@ -27,13 +27,13 @@ import Statistics.Test.MannWhitneyU ( PositionTest(..), TestResult(..) , mannWhitneyUCriticalValue , mannWhitneyUtest) import Statistics.Types (PValue, mkPValue) -import System.Directory (getTemporaryDirectory, createDirectoryIfMissing) +import Distribution.Compat.Directory (getTemporaryDirectory, createDirectoryIfMissing) import System.Environment (getEnvironment) import System.Exit (ExitCode(..), exitWith, exitFailure) import System.FilePath (()) import System.IO ( BufferMode(LineBuffering), hPutStrLn, hSetBuffering, stderr , stdout) -import System.Process ( StdStream(CreatePipe), CreateProcess(..), callProcess +import Distribution.Compat.Process ( StdStream(CreatePipe), CreateProcess(..), callProcess , createProcess, readProcess, shell, waitForProcess, proc, readCreateProcessWithExitCode ) import Text.Printf (printf) diff --git a/solver-benchmarks/solver-benchmarks.cabal b/solver-benchmarks/solver-benchmarks.cabal index 753c8773bf2..3e5741aa51b 100644 --- a/solver-benchmarks/solver-benchmarks.cabal +++ b/solver-benchmarks/solver-benchmarks.cabal @@ -31,6 +31,7 @@ library , base , bytestring , containers + , Cabal ^>= 3.19 , Cabal-syntax ^>= 3.19 , directory , filepath diff --git a/templates/SPDX.LicenseExceptionId.template.hs b/templates/SPDX.LicenseExceptionId.template.hs index 9cb7880a152..7b355aeac24 100644 --- a/templates/SPDX.LicenseExceptionId.template.hs +++ b/templates/SPDX.LicenseExceptionId.template.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {- FOURMOLU_DISABLE -} module Distribution.SPDX.LicenseExceptionId ( LicenseExceptionId (..), @@ -23,6 +24,10 @@ import qualified Data.Map.Strict as Map import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp +#ifdef __MHS__ +import Data.Data (Constr, Data (..), DataType, Fixity (Prefix), constrIndex, mkConstrTag, mkDataType) +#endif + ------------------------------------------------------------------------------- -- LicenseExceptionId ------------------------------------------------------------------------------- @@ -30,7 +35,16 @@ import qualified Text.PrettyPrint as Disp -- | SPDX License Exceptions identifiers list v3.28 data LicenseExceptionId {{ licenseIds }} - deriving (Eq, Ord, Enum, Bounded, Show, Read, Data, Generic) + deriving (Eq, +#ifdef __MHS__ + -- No derived Ord/Data: same per-constructor compile cost as + -- LicenseId at scale; hand-written instances below keep the + -- semantics and the Data instance downstream deriving requires. + Enum, Bounded, Show, Read, Generic +#else + Ord, Enum, Bounded, Show, Read, Data, Generic +#endif + ) instance Binary LicenseExceptionId where put = Binary.putWord8 . fromIntegral . fromEnum @@ -40,6 +54,37 @@ instance Binary LicenseExceptionId where then fail "Too large LicenseExceptionId tag" else return (toEnum (fromIntegral i)) +#ifdef __MHS__ +-- Hand-written Ord/Data mirror the derived instances (declaration-order +-- tags, constructor names as declared) without the measured +-- end-to-end compile cost of the derived versions at scale +-- (~10s user each at 150 constructors; root cause not isolated to a +-- compiler phase). Compare via the derived Enum tags; Data round-trips +-- via the tag index. Semantics match the derived instances; Binary +-- (which also uses fromEnum) and all constructors are unchanged. +instance Ord LicenseExceptionId where + compare a b = compare (fromEnum a) (fromEnum b) + +instance Data LicenseExceptionId where + gfoldl k z x = z x + gunfold _k z c = z (toEnum (constrIndex c - 1)) + toConstr x = licenseExceptionIdConstrs !! fromEnum x + dataTypeOf _ = tyLicenseExceptionId + +tyLicenseExceptionId :: DataType +tyLicenseExceptionId = mkDataType "Distribution.SPDX.LicenseExceptionId" licenseExceptionIdConstrs + +licenseExceptionIdConstrs :: [Constr] +licenseExceptionIdConstrs = + [ mkConstrTag tyLicenseExceptionId name i [] Prefix + | (i, name) <- zip [1 ..] licenseExceptionIdConstrNames + ] + +licenseExceptionIdConstrNames :: [String] +licenseExceptionIdConstrNames = +{{ licenseIdNames }} +#endif + -- note: remember to bump version each time the definition changes instance Structured LicenseExceptionId where structure p = set typeVersion 308 $ nominalStructure p diff --git a/templates/SPDX.LicenseId.template.hs b/templates/SPDX.LicenseId.template.hs index f22bd924cbe..d98426ac188 100644 --- a/templates/SPDX.LicenseId.template.hs +++ b/templates/SPDX.LicenseId.template.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {- FOURMOLU_DISABLE -} module Distribution.SPDX.LicenseId ( LicenseId (..), @@ -27,6 +28,10 @@ import qualified Data.Map.Strict as Map import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp +#ifdef __MHS__ +import Data.Data (Constr, Data (..), DataType, Fixity (Prefix), constrIndex, mkConstrTag, mkDataType) +#endif + ------------------------------------------------------------------------------- -- LicenseId ------------------------------------------------------------------------------- @@ -34,7 +39,20 @@ import qualified Text.PrettyPrint as Disp -- | SPDX License identifiers list v3.28 data LicenseId {{ licenseIds }} - deriving (Eq, Ord, Enum, Bounded, Show, Read, Data) + deriving (Eq, +#ifdef __MHS__ + -- No Ord: MicroHs compiles the derived Ord for this ~700-constructor + -- type pathologically slowly (see instance below). + -- No derived Data: costs as much as derived Ord at scale (~9s + -- user at 150 constructors); a hand-written instance below keeps + -- the Data LicenseId instance that downstream deriving + -- (LicenseExpression) requires. Nothing in the tree calls Data + -- methods on LicenseId. + Enum, Bounded, Show, Read +#else + Ord, Enum, Bounded, Show, Read, Data +#endif + ) instance Binary LicenseId where -- Word16 is encoded in big endianness @@ -46,6 +64,46 @@ instance Binary LicenseId where then fail "Too large LicenseId tag" else return (toEnum (fromIntegral i)) +#ifdef __MHS__ +-- MicroHs takes pathologically long to compile the derived Ord for +-- this ~700-constructor type (measured end to end: ~548s user for a +-- 700-constructor synthetic analogue vs ~0.4s with this instance; +-- root cause not isolated to a compiler phase). Compare via the +-- derived Enum tags instead. Semantics are identical to derived Ord +-- for a plain enumeration (declaration order); Binary (which also +-- uses fromEnum) and all constructors are unchanged. +instance Ord LicenseId where + compare a b = compare (fromEnum a) (fromEnum b) +#endif + +#ifdef __MHS__ +-- Hand-written Data mirrors the derived instance (declaration-order +-- tags, constructor names as declared) without the measured +-- end-to-end compile cost (~9s user at 150 constructors for derived +-- Data; root cause not isolated to a compiler phase). +-- toConstr/fromConstr round-trip via the tag index; gfoldl is trivial +-- for nullary constructors. Nothing in the tree calls Data methods +-- on LicenseId; the instance exists for downstream deriving. +instance Data LicenseId where + gfoldl k z x = z x + gunfold _k z c = z (toEnum (constrIndex c - 1)) + toConstr x = licenseIdConstrs !! fromEnum x + dataTypeOf _ = tyLicenseId + +tyLicenseId :: DataType +tyLicenseId = mkDataType "Distribution.SPDX.LicenseId" licenseIdConstrs + +licenseIdConstrs :: [Constr] +licenseIdConstrs = + [ mkConstrTag tyLicenseId name i [] Prefix + | (i, name) <- zip [1 ..] licenseIdConstrNames + ] + +licenseIdConstrNames :: [String] +licenseIdConstrNames = +{{ licenseIdNames }} +#endif + -- note: remember to bump version each time the definition changes instance Structured LicenseId where structure p = set typeVersion 308 $ nominalStructure p From b04f60210bff6fb149ea5a14a4e1329ab06e947d Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Thu, 12 Nov 2026 02:35:38 +0000 Subject: [PATCH 02/17] CI: add MicroHs (mhs 0.16.12.0) bootstrap job and artifact upload - Add bootstrap/mhs/build-cabal-mhs.sh, bootstrap/mhs/microhs-full.patch, and pure-Haskell shim packages (pretty-mhs, uri-mhs, binary-mhs, text-encoding-mhs) under bootstrap/mhs/shims/. - Add bootstrap-mhs job to .github/workflows/bootstrap.yml to build cabal-install (exe:cabal) with MicroHs 0.16.12.0, run smoke tests and ProcessCaptureTests, and upload cabal-ubuntu-latest-mhs-0.16.12.0-bootstrapped via actions/upload-artifact@v7. --- .github/workflows/bootstrap.yml | 58 +- .hlint.yaml | 19 + Cabal-syntax/Cabal-syntax.cabal | 20 +- .../src/Distribution/Compat/NonEmptySet.hs | 2 + .../src/Distribution/Compat/Prelude.hs | 44 +- .../src/Distribution/FieldGrammar/Pretty.hs | 1 + .../src/Distribution/Types/CondTree.hs | 4 + .../src/Distribution/Types/Condition.hs | 2 + Cabal-syntax/src/Distribution/Utils/Base62.hs | 1 + .../src/Distribution/Utils/Generic.hs | 5 +- Cabal-syntax/src/Distribution/Utils/Path.hs | 46 +- .../src/Distribution/Utils/Structured.hs | 8 + Cabal/Cabal.cabal | 22 +- .../Distribution/PackageDescription/Check.hs | 4 +- .../Simple/Build/PackageInfoModule/Z.hs | 1 + Cabal/src/Distribution/Simple/Compiler.hs | 19 +- Cabal/src/Distribution/Simple/Configure.hs | 16 +- Cabal/src/Distribution/Simple/Errors.hs | 2 + Cabal/src/Distribution/Simple/GHC/Internal.hs | 2 +- .../Distribution/Simple/PackageDescription.hs | 2 +- Cabal/src/Distribution/Simple/Program.hs | 1 + Cabal/src/Distribution/Simple/Program/Ar.hs | 2 + Cabal/src/Distribution/Simple/Program/GHC.hs | 2 +- .../src/Distribution/Simple/Program/HcPkg.hs | 2 +- Cabal/src/Distribution/Simple/Register.hs | 2 +- .../Distribution/Simple/Setup/Benchmark.hs | 2 + Cabal/src/Distribution/Simple/Setup/Build.hs | 2 + Cabal/src/Distribution/Simple/Setup/Clean.hs | 1 + Cabal/src/Distribution/Simple/Setup/Config.hs | 2 + Cabal/src/Distribution/Simple/Setup/Copy.hs | 2 + .../src/Distribution/Simple/Setup/Haddock.hs | 2 + .../src/Distribution/Simple/Setup/Hscolour.hs | 2 + .../src/Distribution/Simple/Setup/Install.hs | 2 + .../src/Distribution/Simple/Setup/Register.hs | 2 + Cabal/src/Distribution/Simple/Setup/Repl.hs | 2 + Cabal/src/Distribution/Simple/Setup/SDist.hs | 2 + Cabal/src/Distribution/Simple/Setup/Test.hs | 2 + .../Simple/SetupHooks/HooksMain.hs | 13 +- .../Simple/SetupHooks/Internal.hs | 4 + .../Distribution/Simple/SetupHooks/Rule.hs | 10 + Cabal/src/Distribution/Simple/Test.hs | 8 +- Cabal/src/Distribution/Simple/Test/ExeV10.hs | 5 +- Cabal/src/Distribution/Simple/Test/LibV09.hs | 5 +- Cabal/src/Distribution/Simple/Utils.hs | 8 +- .../src/Distribution/Types/LocalBuildInfo.hs | 2 + Cabal/src/Distribution/Utils/IOData.hs | 6 + Cabal/src/Distribution/Utils/LogProgress.hs | 4 +- Cabal/src/Distribution/Verbosity.hs | 1 + Cabal/tests/ProcessCaptureTests.hs | 71 ++- Makefile | 1 + bootstrap/mhs/build-cabal-mhs.sh | 288 +++++++++ bootstrap/mhs/microhs-full.patch | 286 +++++++++ cabal-dev-scripts/src/Capture.hs | 7 +- cabal-dev-scripts/src/GenCabalMacros.hs | 1 + cabal-dev-scripts/src/GenPathsModule.hs | 1 + .../cabal-install-solver.cabal | 9 +- cabal-install/cabal-install.cabal | 17 +- .../parser-tests/Tests/ParserTests.hs | 2 +- .../Client/BuildReports/Anonymous.hs | 2 +- .../src/Distribution/Client/Check.hs | 2 +- .../src/Distribution/Client/CmdClean.hs | 8 +- .../src/Distribution/Client/CmdInstall.hs | 8 +- .../src/Distribution/Client/CmdRepl.hs | 12 +- .../src/Distribution/Client/CmdUpdate.hs | 4 +- .../src/Distribution/Client/Config.hs | 20 +- .../src/Distribution/Client/Dependency.hs | 2 +- .../src/Distribution/Client/Errors.hs | 3 +- .../src/Distribution/Client/FetchUtils.hs | 2 + .../src/Distribution/Client/FileMonitor.hs | 2 +- .../src/Distribution/Client/GZipUtils.hs | 3 + cabal-install/src/Distribution/Client/Get.hs | 6 +- .../src/Distribution/Client/GlobalFlags.hs | 4 + .../src/Distribution/Client/Haddock.hs | 2 +- .../src/Distribution/Client/HttpUtils.hs | 10 + .../src/Distribution/Client/InLibrary.hs | 4 +- .../src/Distribution/Client/IndexUtils.hs | 38 +- .../Client/IndexUtils/IndexState.hs | 2 +- .../src/Distribution/Client/Init/Format.hs | 2 +- .../src/Distribution/Client/Init/Prompt.hs | 2 +- .../src/Distribution/Client/Init/Types.hs | 4 +- .../src/Distribution/Client/InstallPlan.hs | 2 + .../src/Distribution/Client/JobControl.hs | 3 + cabal-install/src/Distribution/Client/List.hs | 7 + cabal-install/src/Distribution/Client/Main.hs | 2 +- .../src/Distribution/Client/Manpage.hs | 5 +- .../src/Distribution/Client/PackageHash.hs | 1 - .../Distribution/Client/ProjectBuilding.hs | 2 +- .../src/Distribution/Client/ProjectConfig.hs | 12 +- .../Client/ProjectConfig/FieldGrammar.hs | 2 +- .../Client/ProjectConfig/Import.hs | 4 +- .../Client/ProjectConfig/Legacy.hs | 2 +- .../Distribution/Client/ProjectConfig/Lens.hs | 2 +- .../Client/ProjectConfig/Parsec.hs | 2 +- .../Distribution/Client/ProjectPlanning.hs | 8 +- .../Client/Sandbox/PackageEnvironment.hs | 2 +- .../src/Distribution/Client/ScriptUtils.hs | 6 +- .../src/Distribution/Client/SourceFiles.hs | 3 +- .../src/Distribution/Client/TargetSelector.hs | 12 +- .../src/Distribution/Client/Targets.hs | 10 +- .../src/Distribution/Client/Upload.hs | 1 + .../src/Distribution/Client/Utils.hs | 2 + .../src/Distribution/Client/Utils/Newtypes.hs | 2 +- cabal-install/src/Distribution/Client/VCS.hs | 2 +- .../src/Distribution/Deprecated/ReadP.hs | 2 +- cabal-install/tests/IntegrationTests2.hs | 2 +- .../Distribution/Client/Configure.hs | 2 +- .../Distribution/Client/GZipUtils.hs | 1 + .../Distribution/Client/ProjectConfig.hs | 2 +- .../UnitTests/Distribution/Client/Tar.hs | 1 + cabal-testsuite/src/Test/Cabal/Monad.hs | 6 +- cabal-testsuite/src/Test/Cabal/Prelude.hs | 6 +- cabal-testsuite/src/Test/Cabal/Run.hs | 2 +- cabal-testsuite/src/Test/Cabal/Server.hs | 2 +- cabal-testsuite/src/Test/Cabal/Workdir.hs | 4 +- cabal-validate/src/Cli.hs | 2 +- cabal.mhs.project | 1 + changelog.d/copyfile-cloexec.md | 1 + changelog.d/qualified-instances.md | 1 + changelog.d/store-per-stage.md | 2 +- changelog.d/wired-in-local-targets.md | 1 + mhs-compat-shims/ChangeLog.md | 7 + mhs-compat-shims/LICENSE | 34 ++ mhs-compat-shims/README.md | 26 + .../cbits/mhs_handle.c | 0 .../cbits/mhs_handle.h | 0 .../cbits/mhs_posix.c | 0 .../cbits/mhs_posix.h | 0 .../cbits/mhs_sha256.c | 0 .../cbits/mhs_sha256.h | 0 {Cabal => mhs-compat-shims}/cbits/mhs_spawn.c | 0 {Cabal => mhs-compat-shims}/cbits/mhs_spawn.h | 0 mhs-compat-shims/mhs-compat-shims.cabal | 83 +++ mhs-compat-shims/src/Data/Binary.hs | 369 ++++++++++++ mhs-compat-shims/src/Data/Binary/Get.hs | 294 +++++++++ mhs-compat-shims/src/Data/Binary/Put.hs | 202 +++++++ .../src/Data/Text/Encoding/Error.hs | 89 +++ .../src/Data/Text/Internal/Encoding/Utf8.hs | 79 +++ .../src/Data/Text/Lazy/Encoding.hs | 25 + .../src/Distribution/Client/Compat/Base16.hs | 1 + .../Distribution/Compat/Internal/MhsPosix.hs | 1 - .../Compat/Internal/MhsProcess.hs | 33 +- .../src/Distribution/Compat/MhsInstances.hs | 0 mhs-compat-shims/src/Network/URI.hs | 162 +++++ mhs-compat-shims/src/Text/PrettyPrint.hs | 570 ++++++++++++++++++ templates/SPDX.LicenseExceptionId.template.hs | 2 +- templates/SPDX.LicenseId.template.hs | 2 +- 146 files changed, 3027 insertions(+), 285 deletions(-) create mode 100755 bootstrap/mhs/build-cabal-mhs.sh create mode 100644 bootstrap/mhs/microhs-full.patch create mode 100644 mhs-compat-shims/ChangeLog.md create mode 100644 mhs-compat-shims/LICENSE create mode 100644 mhs-compat-shims/README.md rename {Cabal => mhs-compat-shims}/cbits/mhs_handle.c (100%) rename {Cabal => mhs-compat-shims}/cbits/mhs_handle.h (100%) rename {Cabal-syntax => mhs-compat-shims}/cbits/mhs_posix.c (100%) rename {Cabal-syntax => mhs-compat-shims}/cbits/mhs_posix.h (100%) rename {cabal-install => mhs-compat-shims}/cbits/mhs_sha256.c (100%) rename {cabal-install => mhs-compat-shims}/cbits/mhs_sha256.h (100%) rename {Cabal => mhs-compat-shims}/cbits/mhs_spawn.c (100%) rename {Cabal => mhs-compat-shims}/cbits/mhs_spawn.h (100%) create mode 100644 mhs-compat-shims/mhs-compat-shims.cabal create mode 100644 mhs-compat-shims/src/Data/Binary.hs create mode 100644 mhs-compat-shims/src/Data/Binary/Get.hs create mode 100644 mhs-compat-shims/src/Data/Binary/Put.hs create mode 100644 mhs-compat-shims/src/Data/Text/Encoding/Error.hs create mode 100644 mhs-compat-shims/src/Data/Text/Internal/Encoding/Utf8.hs create mode 100644 mhs-compat-shims/src/Data/Text/Lazy/Encoding.hs rename {cabal-install => mhs-compat-shims}/src/Distribution/Client/Compat/Base16.hs (99%) rename {Cabal-syntax => mhs-compat-shims}/src/Distribution/Compat/Internal/MhsPosix.hs (99%) rename {Cabal => mhs-compat-shims}/src/Distribution/Compat/Internal/MhsProcess.hs (94%) rename {Cabal-syntax => mhs-compat-shims}/src/Distribution/Compat/MhsInstances.hs (100%) create mode 100644 mhs-compat-shims/src/Network/URI.hs create mode 100644 mhs-compat-shims/src/Text/PrettyPrint.hs diff --git a/.github/workflows/bootstrap.yml b/.github/workflows/bootstrap.yml index f332af0501a..ca346f8654f 100644 --- a/.github/workflows/bootstrap.yml +++ b/.github/workflows/bootstrap.yml @@ -10,6 +10,7 @@ on: branches: - master pull_request: + workflow_dispatch: release: types: - created @@ -78,6 +79,61 @@ jobs: name: cabal-${{ matrix.os }}-${{ matrix.ghc }}-bootstrapped path: _build/artifacts/* + bootstrap-mhs: + name: Bootstrap ubuntu-latest mhs-0.16.12.0 + runs-on: ubuntu-latest + timeout-minutes: 180 + steps: + - uses: actions/checkout@v7 + + - name: Get runner OS/version for cache keys + id: get-osver + run: echo "osver=$ImageOS" >> "$GITHUB_OUTPUT" + + - uses: actions/cache/restore@v6 + name: Restore MicroHs toolchain and packages + id: cache-mhs-toolchain + with: + path: ~/.mcabal + key: mhs-toolchain-${{ steps.get-osver.outputs.osver }}-0.16.12.0-${{ hashFiles('bootstrap/mhs/microhs-full.patch', 'mhs-compat-shims/**') }} + restore-keys: | + mhs-toolchain-${{ steps.get-osver.outputs.osver }}-0.16.12.0- + + - uses: actions/cache/restore@v6 + name: Restore MicroHs stage checkpoints + id: cache-mhs-checkpoints + with: + path: _build/mhs-cache + key: mhs-cache-${{ steps.get-osver.outputs.osver }}-0.16.12.0-${{ hashFiles('bootstrap/mhs/**', 'mhs-compat-shims/**', 'Cabal-syntax/src/**', 'Cabal/src/**', 'hooks-exe/**', 'cabal-install-solver/src/**', 'cabal-install/src/**', 'cabal-install/main/**') }} + + - name: Build MicroHs 0.16.12.0 toolchain and packages + run: bash bootstrap/mhs/build-cabal-mhs.sh toolchain + + - uses: actions/cache/save@v6 + name: Save MicroHs toolchain and packages + if: always() && steps.cache-mhs-toolchain.outputs.cache-hit != 'true' + with: + path: ~/.mcabal + key: ${{ steps.cache-mhs-toolchain.outputs.cache-primary-key }} + + - name: Bootstrap cabal-install with MicroHs + run: bash bootstrap/mhs/build-cabal-mhs.sh build + + - uses: actions/cache/save@v6 + name: Save MicroHs stage checkpoints + if: always() && steps.cache-mhs-checkpoints.outputs.cache-hit != 'true' + with: + path: _build/mhs-cache + key: ${{ steps.cache-mhs-checkpoints.outputs.cache-primary-key }} + + - name: Smoke test MicroHs-built cabal + run: bash bootstrap/mhs/build-cabal-mhs.sh test + + - uses: actions/upload-artifact@v7 + with: + name: cabal-ubuntu-latest-mhs-0.16.12.0-bootstrapped + path: _build/artifacts/* + # We use this job as a summary of the workflow # It will fail if any of the previous jobs does it # This way we can use it exclusively in branch protection rules @@ -87,7 +143,7 @@ jobs: name: Bootstrap post job runs-on: ubuntu-latest # IMPORTANT! Any job added to the workflow should be added here too - needs: [bootstrap] + needs: [bootstrap, bootstrap-mhs] steps: - run: | diff --git a/.hlint.yaml b/.hlint.yaml index aa64ef2c710..fb84f80b35a 100644 --- a/.hlint.yaml +++ b/.hlint.yaml @@ -32,6 +32,24 @@ - ignore: {name: "Replace case with maybe", within: [Distribution.Client.InLibrary]} - ignore: {name: "Use fmap", within: [Distribution.Client.HttpUtils, Distribution.Simple.SrcDist]} - ignore: {name: "Use fold", within: [Test.Laws]} +- ignore: {name: "Use uncurry", within: [Distribution.Compat.Internal.MhsProcess]} +- ignore: {name: "Use catMaybes", within: [Distribution.Compat.Internal.MhsProcess]} +- ignore: {name: "Use <$>", within: [Distribution.Client.ProjectPlanning]} +- ignore: + name: "Unused LANGUAGE pragma" + within: + - Distribution.Compat.NonEmptySet + - Distribution.Types.CondTree + - Distribution.Types.Condition + - Distribution.Utils.Path + - Distribution.Client.Types.SourceRepo +- ignore: + name: "Use fewer imports" + within: + - Distribution.Client.FetchUtils + - Distribution.Client.ProjectPlanning + - Distribution.Client.SetupWrapper + - Distribution.Client.Utils # For lists in these rules we use single letter variables like x rather than xs, # because "hlint considers only single-letter identifiers as rules' variables. @@ -55,6 +73,7 @@ - Distribution.Simple.Utils from Cabal. - arguments: + - --ignore-glob=mhs-compat-shims/** - --ignore-glob=Cabal-syntax/src/Distribution/Fields/Lexer.hs - --ignore-glob=Cabal-tests/tests/custom-setup/CabalDoctestSetup.hs - --ignore-glob=Cabal-tests/tests/custom-setup/IdrisSetup.hs diff --git a/Cabal-syntax/Cabal-syntax.cabal b/Cabal-syntax/Cabal-syntax.cabal index 84f879e593d..a8942f0557b 100644 --- a/Cabal-syntax/Cabal-syntax.cabal +++ b/Cabal-syntax/Cabal-syntax.cabal @@ -18,9 +18,6 @@ build-type: Simple extra-doc-files: README.md ChangeLog.md -extra-source-files: - cbits/mhs_posix.h - source-repository head type: git location: https://github.com/haskell/cabal/ @@ -54,9 +51,8 @@ library if flag(mhs) build-depends: - array-mhs >= 0.5.8 && < 0.6, - binary-mhs >= 0.8.1 && < 0.9, - pretty-mhs >= 1.1.3.6 && < 1.2 + array-mhs >= 0.5.8 && < 0.6, + mhs-compat-shims ^>= 0.1 else build-depends: array >= 0.4.0.1 && < 0.6, @@ -91,7 +87,6 @@ library Distribution.Compat.Graph Distribution.Compat.Internal.LazyByteString Distribution.Compat.Lens - Distribution.Compat.MhsInstances Distribution.Compat.NonEmptySet Distribution.Compat.Parsing Distribution.Compat.Prelude @@ -222,17 +217,6 @@ library Distribution.Version Language.Haskell.Extension - other-modules: - Distribution.Compat.Internal.MhsPosix - - -- C helpers for the MHS (MicroHs) build of Distribution.Compat.Directory. - -- The POSIX bodies are used there; other platforms compile the stubs. - -- The matching header (cbits/mhs_posix.h, shipped in - -- extra-source-files) carries the prototypes (with platform types - -- from the standard headers) for MicroHs-generated FFI call sites. - c-sources: cbits/mhs_posix.c - include-dirs: cbits - other-extensions: BangPatterns CPP diff --git a/Cabal-syntax/src/Distribution/Compat/NonEmptySet.hs b/Cabal-syntax/src/Distribution/Compat/NonEmptySet.hs index 0bb0ead2324..ed64faa6749 100644 --- a/Cabal-syntax/src/Distribution/Compat/NonEmptySet.hs +++ b/Cabal-syntax/src/Distribution/Compat/NonEmptySet.hs @@ -46,12 +46,14 @@ import Distribution.Compat.Binary (Binary (..)) import Distribution.Utils.Structured -- | @since 3.4.0.0 +{- FOURMOLU_DISABLE -} newtype NonEmptySet a = NES (Set.Set a) deriving (Eq, Ord, Read #ifndef __MHS__ , Data #endif ) +{- FOURMOLU_ENABLE -} #ifdef __MHS__ -- MicroHs cannot derive 'Data' for parameterised types (it drops the diff --git a/Cabal-syntax/src/Distribution/Compat/Prelude.hs b/Cabal-syntax/src/Distribution/Compat/Prelude.hs index d705dce88c2..bced897cf04 100644 --- a/Cabal-syntax/src/Distribution/Compat/Prelude.hs +++ b/Cabal-syntax/src/Distribution/Compat/Prelude.hs @@ -6,6 +6,7 @@ -- * Acts as a compatibility layer, like @base-compat@. -- -- * Provides commonly used imports. +{- FOURMOLU_DISABLE -} module Distribution.Compat.Prelude ( -- * Prelude @@ -195,6 +196,7 @@ module Distribution.Compat.Prelude , traceM , traceShowM ) where +{- FOURMOLU_ENABLE -} -- We also could hide few partial function {- FOURMOLU_DISABLE -} @@ -226,34 +228,34 @@ import Prelude as BasePrelude hiding {- FOURMOLU_ENABLE -} -- AMP import Data.Foldable - -- NOTE: only the class methods are re-exported here (as plain - -- functions), never the class itself. MicroHs merges a re-exported - -- class method with a same-named local definition ('foldr1' - -- and 'foldl1' below) into an ambiguous export. Modules needing - -- the class (instances, deriving) import it directly. - ( foldMap + ( -- NOTE: only the class methods are re-exported here (as plain + -- functions), never the class itself. MicroHs merges a re-exported + -- class method with a same-named local definition ('foldr1' + -- and 'foldl1' below) into an ambiguous export. Modules needing + -- the class (instances, deriving) import it directly. + + all + , any + , elem + , find + , foldMap , foldMap' - , foldr - , foldr' , foldl , foldl' - , toList - , null + , foldr + , foldr' + , for_ , length - , elem , maximum , minimum - , sum + , null , product - , all - , any - , find - , for_ + , sum + , toList , traverse_ ) import Data.Traversable (Traversable (..), for) - -- Extra exports import Control.Applicative (Alternative (..), Const (..)) import Control.Arrow (first) @@ -330,6 +332,7 @@ trace :: String -> a -> a trace = Debug.Trace.trace {-# DEPRECATED trace "Don't leave me in the code" #-} +{- FOURMOLU_DISABLE -} traceShowId :: Show a => a -> a #ifdef __MHS__ -- MicroHs's 'Debug.Trace' has no 'traceShow'. @@ -337,16 +340,20 @@ traceShowId x = Debug.Trace.trace (show x) x #else traceShowId x = Debug.Trace.traceShow x x #endif +{- FOURMOLU_ENABLE -} {-# DEPRECATED traceShowId "Don't leave me in the code" #-} +{- FOURMOLU_DISABLE -} traceShow :: Show a => a -> b -> b #ifdef __MHS__ traceShow x y = Debug.Trace.trace (show x) y #else traceShow = Debug.Trace.traceShow #endif +{- FOURMOLU_ENABLE -} {-# DEPRECATED traceShow "Don't leave me in the code" #-} +{- FOURMOLU_DISABLE -} traceM :: Applicative f => String -> f () #ifdef __MHS__ -- MicroHs's 'Debug.Trace.traceM' needs 'Monad', so define the more @@ -355,8 +362,10 @@ traceM s = trace s (pure ()) #else traceM = Debug.Trace.traceM #endif +{- FOURMOLU_ENABLE -} {-# DEPRECATED traceM "Don't leave me in the code" #-} +{- FOURMOLU_DISABLE -} traceShowM :: (Show a, Applicative f) => a -> f () #ifdef __MHS__ -- MicroHs's 'Debug.Trace' has no 'traceShowM', and its 'traceM' @@ -365,4 +374,5 @@ traceShowM x = Debug.Trace.trace (show x) (pure ()) #else traceShowM = Debug.Trace.traceShowM #endif +{- FOURMOLU_ENABLE -} {-# DEPRECATED traceShowM "Don't leave me in the code" #-} diff --git a/Cabal-syntax/src/Distribution/FieldGrammar/Pretty.hs b/Cabal-syntax/src/Distribution/FieldGrammar/Pretty.hs index 87006234e51..65177b1b360 100644 --- a/Cabal-syntax/src/Distribution/FieldGrammar/Pretty.hs +++ b/Cabal-syntax/src/Distribution/FieldGrammar/Pretty.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + module Distribution.FieldGrammar.Pretty ( PrettyFieldGrammar , prettyFieldGrammar diff --git a/Cabal-syntax/src/Distribution/Types/CondTree.hs b/Cabal-syntax/src/Distribution/Types/CondTree.hs index b69538c2337..d7c1f33eb81 100644 --- a/Cabal-syntax/src/Distribution/Types/CondTree.hs +++ b/Cabal-syntax/src/Distribution/Types/CondTree.hs @@ -52,6 +52,7 @@ import qualified Distribution.Compat.Lens as L -- derived off of 'targetBuildInfo' (perhaps a good refactoring -- would be to convert this into an opaque type, with a smart -- constructor that pre-computes the dependencies.) +{- FOURMOLU_DISABLE -} data CondTree v a = CondNode { condTreeData :: a , condTreeComponents :: [CondBranch v a] @@ -61,6 +62,7 @@ data CondTree v a = CondNode , Data #endif ) +{- FOURMOLU_ENABLE -} #ifdef __MHS__ -- MicroHs cannot derive 'Data' for parameterised types (it drops the @@ -81,6 +83,7 @@ instance Monoid a => Monoid (CondTree v a) where -- | A 'CondBranch' represents a conditional branch, e.g., @if -- flag(foo)@ on some syntax @a@. It also has an optional false -- branch. +{- FOURMOLU_DISABLE -} data CondBranch v a = CondBranch { condBranchCondition :: Condition v , condBranchIfTrue :: CondTree v a @@ -91,6 +94,7 @@ data CondBranch v a = CondBranch , Data #endif ) +{- FOURMOLU_ENABLE -} #ifdef __MHS__ deriving instance (Data v, Data a) => Data (CondBranch v a) diff --git a/Cabal-syntax/src/Distribution/Types/Condition.hs b/Cabal-syntax/src/Distribution/Types/Condition.hs index 375c162a0ee..9964c0b092b 100644 --- a/Cabal-syntax/src/Distribution/Types/Condition.hs +++ b/Cabal-syntax/src/Distribution/Types/Condition.hs @@ -14,6 +14,7 @@ import Distribution.Compat.Prelude import Prelude () -- | A boolean expression parameterized over the variable type used. +{- FOURMOLU_DISABLE -} data Condition c = Var c | Lit Bool @@ -25,6 +26,7 @@ data Condition c , Data #endif ) +{- FOURMOLU_ENABLE -} #ifdef __MHS__ -- MicroHs cannot derive 'Data' for parameterised types (it drops the diff --git a/Cabal-syntax/src/Distribution/Utils/Base62.hs b/Cabal-syntax/src/Distribution/Utils/Base62.hs index 1cd8c2f6d5e..1bc39b26b44 100644 --- a/Cabal-syntax/src/Distribution/Utils/Base62.hs +++ b/Cabal-syntax/src/Distribution/Utils/Base62.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- | Implementation of base-62 encoding, which we use when computing hashes -- for fully instantiated unit ids. module Distribution.Utils.Base62 (hashToBase62) where diff --git a/Cabal-syntax/src/Distribution/Utils/Generic.hs b/Cabal-syntax/src/Distribution/Utils/Generic.hs index af46afb860f..88d8cdc0acd 100644 --- a/Cabal-syntax/src/Distribution/Utils/Generic.hs +++ b/Cabal-syntax/src/Distribution/Utils/Generic.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- | -- Module : Distribution.Utils.Generic -- Copyright : Isaac Jones, Simon Marlow 2003-2004 @@ -97,7 +98,6 @@ import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL -import GHC.IO.Exception (IOErrorType (UnsupportedOperation)) import Distribution.Compat.Directory ( copyFile , getTemporaryDirectory @@ -108,10 +108,12 @@ import Distribution.Compat.Internal.LazyByteString ( hGetContentsLBS , readFileLBS ) +import GHC.IO.Exception (IOErrorType (UnsupportedOperation)) import System.FilePath ( takeFileName , (<.>) ) +{- FOURMOLU_DISABLE -} import System.IO ( IOMode (ReadMode) , hClose @@ -126,6 +128,7 @@ import System.IO , withBinaryFile , withFile ) +{- FOURMOLU_ENABLE -} import System.IO.Error (ioeGetErrorType) -- ----------------------------------------------------------------------------- diff --git a/Cabal-syntax/src/Distribution/Utils/Path.hs b/Cabal-syntax/src/Distribution/Utils/Path.hs index 807f694389d..daf3ab30d9f 100644 --- a/Cabal-syntax/src/Distribution/Utils/Path.hs +++ b/Cabal-syntax/src/Distribution/Utils/Path.hs @@ -1,7 +1,7 @@ {-# LANGUAGE CPP #-} {-# LANGUAGE FunctionalDependencies #-} -{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE RoleAnnotations #-} +{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-} module Distribution.Utils.Path @@ -189,15 +189,17 @@ relative. -} -- | Phantom marker for 'SymbolicPathX': the path refers to a file. -data File deriving Data +data File deriving (Data) -- | Phantom marker for 'SymbolicPathX': the path refers to a -- directory or category of directories, e.g. the package directory -- or a source directory. The parameter names which directory. +{- FOURMOLU_DISABLE -} data Dir (dir :: Type) #ifndef __MHS__ deriving Data #endif +{- FOURMOLU_ENABLE -} #ifdef __MHS__ -- MicroHs cannot derive 'Data' for parameterised types (it drops the @@ -207,22 +209,23 @@ deriving instance Data dir => Data (Dir dir) -- | Phantom marker for 'SymbolicPathX': the path may be absolute, -- or it may be relative. -data AllowAbsolute deriving Data +data AllowAbsolute deriving (Data) -- | Phantom marker for 'SymbolicPathX': the path must be relative. -data OnlyRelative deriving Data +data OnlyRelative deriving (Data) -- | Compatibility shim: 'FileOrDir' used to be a datatype whose -- constructors were promoted to the type level with @DataKinds@. -- The markers are now the plain types above; this empty datatype is -- kept so that existing @FileOrDir (..)@ imports keep working. -data FileOrDir deriving Data +data FileOrDir deriving (Data) -- | A symbolic path, possibly relative to an abstract location specified -- by the @from@ type parameter. -- -- They are *symbolic*, which means we cannot perform any 'IO' -- until we interpret them (using e.g. 'interpretSymbolicPath'). +{- FOURMOLU_DISABLE -} newtype SymbolicPathX (allowAbsolute :: Type) (from :: Type) (to :: Type) = SymbolicPath FilePath deriving (Generic, Show, Read, Eq, Ord @@ -230,6 +233,7 @@ newtype SymbolicPathX (allowAbsolute :: Type) (from :: Type) (to :: Type) , Data #endif ) +{- FOURMOLU_ENABLE -} #ifdef __MHS__ -- MicroHs cannot derive 'Data' for parameterised types (it drops the @@ -507,79 +511,79 @@ instance -- | Abstract directory: current working directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data CWD deriving Data +data CWD deriving (Data) -- | Abstract directory: package directory (e.g. a directory containing the @.cabal@ file). -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Pkg deriving Data +data Pkg deriving (Data) -- | Abstract directory: dist directory (e.g. @dist-newstyle@). -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Dist deriving Data +data Dist deriving (Data) -- | Abstract directory: source directory (a search directory for source files). -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Source deriving Data +data Source deriving (Data) -- | Abstract directory: include directory (a search directory for CPP includes like header files, e.g. with @ghc -I@). -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Include deriving Data +data Include deriving (Data) -- | Abstract directory: search directory for extra libraries. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Lib deriving Data +data Lib deriving (Data) -- | Abstract directory: MacOS framework directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Framework deriving Data +data Framework deriving (Data) -- | Abstract directory: build directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Build deriving Data +data Build deriving (Data) -- | Abstract directory: directory for build artifacts, such as documentation or @.hie@ files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Artifacts deriving Data +data Artifacts deriving (Data) -- | Abstract directory: package database directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data PkgDB deriving Data +data PkgDB deriving (Data) -- | Abstract directory: data files directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data DataDir deriving Data +data DataDir deriving (Data) -- | Abstract directory: directory for HPC @.mix@ files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Mix deriving Data +data Mix deriving (Data) -- | Abstract directory: directory for HPC @.tix@ files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Tix deriving Data +data Tix deriving (Data) -- | Abstract directory: a temporary directory. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Tmp deriving Data +data Tmp deriving (Data) -- | Abstract directory: directory for response files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data Response deriving Data +data Response deriving (Data) -- | Abstract directory: directory for pkg-config files. -- -- See Note [Symbolic paths] in Distribution.Utils.Path. -data PkgConf deriving Data +data PkgConf deriving (Data) diff --git a/Cabal-syntax/src/Distribution/Utils/Structured.hs b/Cabal-syntax/src/Distribution/Utils/Structured.hs index e2fe7fd2e1b..6cef4daa180 100644 --- a/Cabal-syntax/src/Distribution/Utils/Structured.hs +++ b/Cabal-syntax/src/Distribution/Utils/Structured.hs @@ -32,6 +32,7 @@ -- -- Technically, 'Structured' is not related to 'Binary', and may -- be useful in other uses. +{- FOURMOLU_DISABLE -} module Distribution.Utils.Structured ( -- * Encoding and decoding @@ -66,6 +67,7 @@ module Distribution.Utils.Structured , typeVersion , typeName ) where +{- FOURMOLU_ENABLE -} import Data.Functor ((<&>)) import Data.Int (Int16, Int32, Int64, Int8) @@ -225,6 +227,7 @@ structureBuilder s0 = State.evalState (go s0) Map.empty -- @ -- -- @since 3.2.0.0 +{- FOURMOLU_DISABLE -} class Typeable a => Structured a where structure :: Proxy a -> Structure #ifdef __MHS__ @@ -242,11 +245,13 @@ class Typeable a => Structured a where structureHash' :: Tagged a MD5 structureHash' = Tagged (hashStructure (structure (Proxy :: Proxy a))) #endif +{- FOURMOLU_ENABLE -} -- private Tagged newtype Tagged a b = Tagged {untag :: b} -- | Semantically @'hashStructure' . 'structure'@. +{- FOURMOLU_DISABLE -} structureHash :: forall a. Structured a => Proxy a -> MD5 #ifdef __MHS__ -- MicroHs does not provide the class constraint to default method @@ -256,6 +261,7 @@ structureHash p = hashStructure (structure p) #else structureHash _ = untag (structureHash' :: Tagged a MD5) #endif +{- FOURMOLU_ENABLE -} ------------------------------------------------------------------------------- -- Functions @@ -301,6 +307,7 @@ structuredDecodeFileOrFail f = structuredDecodeOrFailIO =<< readFileLBS f data Tag a = Tag +{- FOURMOLU_DISABLE -} instance Structured a => Binary.Binary (Tag a) where get = do actual <- binaryGetMD5 @@ -328,6 +335,7 @@ instance Structured a => Binary.Binary (Tag a) where #else expected = untag (structureHash' :: Tagged a MD5) #endif +{- FOURMOLU_ENABLE -} ------------------------------------------------------------------------------- -- Smart constructors diff --git a/Cabal/Cabal.cabal b/Cabal/Cabal.cabal index c32f528a061..bea64e9c84f 100644 --- a/Cabal/Cabal.cabal +++ b/Cabal/Cabal.cabal @@ -24,10 +24,6 @@ build-type: Simple extra-doc-files: README.md ChangeLog.md -extra-source-files: - cbits/mhs_spawn.h - cbits/mhs_handle.h - source-repository head type: git location: https://github.com/haskell/cabal/ @@ -49,17 +45,6 @@ library default-extensions: NoImportQualifiedPost hs-source-dirs: src - -- C helpers for the MHS (MicroHs) build, which cannot use the - -- @process@ package. The POSIX bodies are used there; other - -- platforms compile the stubs. The matching headers - -- (cbits/mhs_spawn.h and cbits/mhs_handle.h, shipped in - -- extra-source-files) carry the prototypes for MicroHs-generated - -- FFI call sites. - c-sources: - cbits/mhs_spawn.c - cbits/mhs_handle.c - include-dirs: cbits - -- Common deps available as separate MHS packages with the same -- bounds on both backends (transformers/mtl/parsec stay in the -- unconditional block below; they exist as mtl-2.3.2, @@ -76,13 +61,11 @@ library -- those (plus unix, which has no MHS package) are GHC-only. if flag(mhs) build-depends: - array-mhs >= 0.5.8 && < 0.6, - binary-mhs >= 0.8.1 && < 0.9, - pretty-mhs >= 1.1.3.6 && < 1.2 + array-mhs >= 0.5.8 && < 0.6, + mhs-compat-shims ^>= 0.1 else build-depends: , array >= 0.4.0.1 && < 0.6 - , binary >= 0.8.1 && < 0.9 , bytestring >= 0.10.8 && < 0.13 , deepseq >= 1.4 && < 1.7 , directory >= 1.2.7 && < 1.4 @@ -385,7 +368,6 @@ library Distribution.Compat.Async Distribution.Compat.CopyFile Distribution.Compat.GetShortPathName - Distribution.Compat.Internal.MhsProcess Distribution.GetOpt Distribution.Lex Distribution.PackageDescription.Check.Common diff --git a/Cabal/src/Distribution/PackageDescription/Check.hs b/Cabal/src/Distribution/PackageDescription/Check.hs index 9cb082a6bd2..293c8426b76 100644 --- a/Cabal/src/Distribution/PackageDescription/Check.hs +++ b/Cabal/src/Distribution/PackageDescription/Check.hs @@ -47,9 +47,9 @@ import Data.List (group) import qualified Data.List as L import Data.Text (Text) import Distribution.CabalSpecVersion +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.Compat.Lens import Distribution.Compiler -import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.FieldGrammar.Parsec (freeTextIgnoreDotlineVers) import Distribution.License import Distribution.ModuleName (toFilePath) @@ -78,8 +78,8 @@ import Distribution.Version import System.FilePath (splitExtension, takeFileName) import qualified Data.ByteString.Lazy as BS -import qualified Distribution.SPDX as SPDX import qualified Distribution.Compat.Directory as System +import qualified Distribution.SPDX as SPDX import qualified Distribution.Compat.Directory (listDirectory) import qualified System.FilePath.Windows as FilePath.Windows (isValid) diff --git a/Cabal/src/Distribution/Simple/Build/PackageInfoModule/Z.hs b/Cabal/src/Distribution/Simple/Build/PackageInfoModule/Z.hs index f2a3a8cd3a4..dab5cf071a1 100644 --- a/Cabal/src/Distribution/Simple/Build/PackageInfoModule/Z.hs +++ b/Cabal/src/Distribution/Simple/Build/PackageInfoModule/Z.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + module Distribution.Simple.Build.PackageInfoModule.Z (render, Z (..)) where import Distribution.ZinzaPrelude (Generic, execWriter, tell) diff --git a/Cabal/src/Distribution/Simple/Compiler.hs b/Cabal/src/Distribution/Simple/Compiler.hs index da464cf89f0..ecf9ec8ecf9 100644 --- a/Cabal/src/Distribution/Simple/Compiler.hs +++ b/Cabal/src/Distribution/Simple/Compiler.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- | -- Module : Distribution.Simple.Compiler -- Copyright : Isaac Jones 2003-2004 @@ -91,8 +92,8 @@ module Distribution.Simple.Compiler , showProfDetailLevel ) where -import Distribution.Compat.CharParsing import Data.Foldable (Foldable) +import Distribution.Compat.CharParsing import Distribution.Compat.Prelude import Distribution.Parsec import Distribution.Pretty @@ -263,6 +264,7 @@ newtype TargetName = TargetName String renderTargetName :: TargetName -> String renderTargetName (TargetName name) = name +{- FOURMOLU_DISABLE -} parseTargetName :: String -> Either String TargetName parseTargetName name | null name = Left "target name is empty" @@ -292,6 +294,7 @@ parseTargetName name step c (x:xs) | [c] == sep = "" : x : xs step c (x:xs) = (c:x) : xs step _ [] = [] +{- FOURMOLU_ENABLE -} -- | Return the canonical target identity, validating new-protocol metadata. -- Older compilers retain their full Target platform string where available, @@ -305,11 +308,13 @@ compilerTargetName platform comp = let expected = machine ++ if abi == "profiling" then "-prof" else "" if abi `notElem` ["", "profiling"] then Left ("unsupported Target ABI: " ++ abi) - else if name /= expected - then Left "Target name contradicts Target platform and Target ABI" - else if length name + 1 + length (prettyShow (compilerVersion comp)) > 255 - then Left "target name plus compiler version exceeds the 255-character filesystem component limit" - else Right target + else + if name /= expected + then Left "Target name contradicts Target platform and Target ABI" + else + if length name + 1 + length (prettyShow (compilerVersion comp)) > 255 + then Left "target name plus compiler version exceeds the 255-character filesystem component limit" + else Right target (Just _, Nothing, _) -> Left "Target name requires Target platform" (Nothing, Just machine, abi) -> do _ <- parseTargetName machine @@ -723,6 +728,7 @@ profilingDynamicSupportedOrUnknown comp = profilingDynamicSupported comp `elem` [Just True, Nothing] -- | Whether the selected profiling target includes a debug RTS variant. +{- FOURMOLU_DISABLE -} profilingDebugSupported :: Compiler -> Maybe Bool profilingDebugSupported comp | compilerTargetsProfiling comp @@ -737,6 +743,7 @@ profilingDebugSupported comp Nothing -> Just False | compilerTargetsProfiling comp = Nothing | otherwise = Just False +{- FOURMOLU_ENABLE -} -- | Is the compiler distributed with dynamic libraries dynamicSupported :: Compiler -> Maybe Bool diff --git a/Cabal/src/Distribution/Simple/Configure.hs b/Cabal/src/Distribution/Simple/Configure.hs index 9b10c4017a6..f32f9a147cd 100644 --- a/Cabal/src/Distribution/Simple/Configure.hs +++ b/Cabal/src/Distribution/Simple/Configure.hs @@ -148,6 +148,13 @@ import Data.List import qualified Data.List.NonEmpty as NEL import qualified Data.Map as Map import qualified Data.Text as Text +import Distribution.Compat.Directory + ( canonicalizePath + , createDirectoryIfMissing + , doesFileExist + , doesPathExist + , listDirectory + ) import Distribution.Compat.Environment (lookupEnv) import Distribution.Parsec ( simpleParsec @@ -161,13 +168,6 @@ import Distribution.Simple.Errors import Distribution.Types.AnnotatedId import Distribution.Utils.Path import Distribution.Utils.Structured (structuredDecodeOrFailIO, structuredEncode) -import Distribution.Compat.Directory - ( canonicalizePath - , createDirectoryIfMissing - , doesFileExist - , doesPathExist - , listDirectory - ) import System.FilePath ( isAbsolute ) @@ -1434,6 +1434,7 @@ finalCheckPackage dieWithException verbosity $ CantFindForeignLibraries unsupportedFLibs +{- FOURMOLU_DISABLE -} configureComponents :: VerbosityHandles -> LBC.LocalBuildConfig @@ -1611,6 +1612,7 @@ configureComponents ] return lbi +{- FOURMOLU_ENABLE -} mkPromisedDepsSet :: [PromisedComponent] -> Map (PackageName, ComponentName) PromisedComponent mkPromisedDepsSet comps = Map.fromList [((packageName pn, CLibName ln), p) | p@(PromisedComponent pn ln _) <- comps] diff --git a/Cabal/src/Distribution/Simple/Errors.hs b/Cabal/src/Distribution/Simple/Errors.hs index be0df4512ba..781d927b0cf 100644 --- a/Cabal/src/Distribution/Simple/Errors.hs +++ b/Cabal/src/Distribution/Simple/Errors.hs @@ -313,6 +313,7 @@ versionRequirement range | isAnyVersion range = "" | otherwise = " version " ++ prettyShow range +{- FOURMOLU_DISABLE -} exceptionMessage :: CabalException -> String exceptionMessage e = case e of NoBenchMarkProgram cmd -> "Could not find benchmark program \"" ++ cmd ++ "\". Did you build the package first?" @@ -803,3 +804,4 @@ exceptionMessage e = case e of [ "The ecosystem doesn't support building packages with just bytecode libraries yet." , "If you have run into this error, please comment on issue #" ] +{- FOURMOLU_ENABLE -} diff --git a/Cabal/src/Distribution/Simple/GHC/Internal.hs b/Cabal/src/Distribution/Simple/GHC/Internal.hs index fce34799b26..becf1ec1e4d 100644 --- a/Cabal/src/Distribution/Simple/GHC/Internal.hs +++ b/Cabal/src/Distribution/Simple/GHC/Internal.hs @@ -53,6 +53,7 @@ import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Text as Text import Distribution.Backpack +import Distribution.Compat.Directory (listDirectory) import Distribution.Compat.Stack import Distribution.Lex import qualified Distribution.ModuleName as ModuleName @@ -84,7 +85,6 @@ import Distribution.Utils.NubList (NubListR, toNubListR) import Distribution.Utils.Path import Distribution.Verbosity import Language.Haskell.Extension -import Distribution.Compat.Directory (listDirectory) import System.Environment (getEnv) import System.FilePath ( takeDirectory diff --git a/Cabal/src/Distribution/Simple/PackageDescription.hs b/Cabal/src/Distribution/Simple/PackageDescription.hs index 532b333a9d1..fc117addf2b 100644 --- a/Cabal/src/Distribution/Simple/PackageDescription.hs +++ b/Cabal/src/Distribution/Simple/PackageDescription.hs @@ -25,6 +25,7 @@ import Prelude () import qualified Data.ByteString as BS import Data.List (groupBy) +import Distribution.Compat.Directory (doesFileExist) import Distribution.Fields.ParseResult import Distribution.PackageDescription import Distribution.PackageDescription.Parsec @@ -43,7 +44,6 @@ import Distribution.Simple.Errors import Distribution.Simple.Utils (dieWithException, equating, warn) import Distribution.Utils.Path import Distribution.Verbosity (Verbosity, VerbosityLevel (..), verbosityLevel) -import Distribution.Compat.Directory (doesFileExist) import Text.Printf (printf) readGenericPackageDescription diff --git a/Cabal/src/Distribution/Simple/Program.hs b/Cabal/src/Distribution/Simple/Program.hs index 4fe2d4eb79c..ba4804eb8d2 100644 --- a/Cabal/src/Distribution/Simple/Program.hs +++ b/Cabal/src/Distribution/Simple/Program.hs @@ -5,6 +5,7 @@ - Ideally, a set of unit tests that check whether certain - flags trigger recompilation should be added. - -} + -- | -- Module : Distribution.Simple.Program -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 diff --git a/Cabal/src/Distribution/Simple/Program/Ar.hs b/Cabal/src/Distribution/Simple/Program/Ar.hs index 231edf339b6..821825a81a7 100644 --- a/Cabal/src/Distribution/Simple/Program/Ar.hs +++ b/Cabal/src/Distribution/Simple/Program/Ar.hs @@ -61,6 +61,7 @@ import Distribution.Verbosity import Distribution.Compat.Directory (doesFileExist, renameFile) import System.FilePath (splitFileName) +{- FOURMOLU_DISABLE -} import System.IO ( Handle , IOMode (ReadWriteMode) @@ -71,6 +72,7 @@ import System.IO #endif , withBinaryFile ) +{- FOURMOLU_ENABLE -} #ifdef __MHS__ import Data.Int (Int64) import Foreign.C.Error (throwErrnoIfMinus1_) diff --git a/Cabal/src/Distribution/Simple/Program/GHC.hs b/Cabal/src/Distribution/Simple/Program/GHC.hs index 4bee995589a..9bf5cbeea1c 100644 --- a/Cabal/src/Distribution/Simple/Program/GHC.hs +++ b/Cabal/src/Distribution/Simple/Program/GHC.hs @@ -47,8 +47,8 @@ import Distribution.Utils.Path import Distribution.Verbosity import Distribution.Version -import System.IO (TextEncoding) import Language.Haskell.Extension +import System.IO (TextEncoding) import Data.List (stripPrefix) import qualified Data.Map as Map diff --git a/Cabal/src/Distribution/Simple/Program/HcPkg.hs b/Cabal/src/Distribution/Simple/Program/HcPkg.hs index 9dc3e23db25..c7f3bba6255 100644 --- a/Cabal/src/Distribution/Simple/Program/HcPkg.hs +++ b/Cabal/src/Distribution/Simple/Program/HcPkg.hs @@ -70,8 +70,8 @@ import Distribution.Types.PackageId (PackageId) import Distribution.Types.UnitId (mkLegacyUnitId, unUnitId) import Distribution.Utils.Path ( CWD - , FileLike ((<.>)) , Dir + , FileLike ((<.>)) , PathLike (()) , Pkg , PkgDB diff --git a/Cabal/src/Distribution/Simple/Register.hs b/Cabal/src/Distribution/Simple/Register.hs index 3661d062124..3b4befc8d97 100644 --- a/Cabal/src/Distribution/Simple/Register.hs +++ b/Cabal/src/Distribution/Simple/Register.hs @@ -58,6 +58,7 @@ import qualified Distribution.Simple.PackageIndex as Index import qualified Distribution.Simple.UHC as UHC import Distribution.Backpack.DescribeUnitId +import Distribution.Compat.Directory import Distribution.Compat.Graph (IsNode (nodeKey)) import Distribution.InstalledPackageInfo (InstalledPackageInfo) import qualified Distribution.InstalledPackageInfo as IPI @@ -79,7 +80,6 @@ import Distribution.System import Distribution.Utils.Path import Distribution.Verbosity as Verbosity import Distribution.Version -import Distribution.Compat.Directory import System.FilePath (isAbsolute) import System.IO (hPutStrLn) diff --git a/Cabal/src/Distribution/Simple/Setup/Benchmark.hs b/Cabal/src/Distribution/Simple/Setup/Benchmark.hs index 8237b11bb81..2858cd5cfd0 100644 --- a/Cabal/src/Distribution/Simple/Setup/Benchmark.hs +++ b/Cabal/src/Distribution/Simple/Setup/Benchmark.hs @@ -14,6 +14,7 @@ -- -- Definition of the benchmarking command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Benchmark #ifdef __MHS__ ( BenchmarkFlags (..) @@ -33,6 +34,7 @@ module Distribution.Simple.Setup.Benchmark , benchmarkCommand , benchmarkOptions' ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Build.hs b/Cabal/src/Distribution/Simple/Setup/Build.hs index 5cc5a58ec15..93725d3cda0 100644 --- a/Cabal/src/Distribution/Simple/Setup/Build.hs +++ b/Cabal/src/Distribution/Simple/Setup/Build.hs @@ -14,6 +14,7 @@ -- -- Definition of the build command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Build #ifdef __MHS__ ( BuildFlags (..) @@ -34,6 +35,7 @@ module Distribution.Simple.Setup.Build , DumpBuildInfo (..) , buildOptions ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Clean.hs b/Cabal/src/Distribution/Simple/Setup/Clean.hs index d93933c38a7..c2f9f6fffc7 100644 --- a/Cabal/src/Distribution/Simple/Setup/Clean.hs +++ b/Cabal/src/Distribution/Simple/Setup/Clean.hs @@ -14,6 +14,7 @@ -- -- Definition of the clean command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Clean #ifdef __MHS__ ( CleanFlags (..) diff --git a/Cabal/src/Distribution/Simple/Setup/Config.hs b/Cabal/src/Distribution/Simple/Setup/Config.hs index 2b9967aaad0..162e1d52ab4 100644 --- a/Cabal/src/Distribution/Simple/Setup/Config.hs +++ b/Cabal/src/Distribution/Simple/Setup/Config.hs @@ -15,6 +15,7 @@ -- -- Definition of the configure command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Config #ifdef __MHS__ ( ConfigFlags (..) @@ -41,6 +42,7 @@ module Distribution.Simple.Setup.Config , configureOptions , installDirsOptions ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Copy.hs b/Cabal/src/Distribution/Simple/Setup/Copy.hs index 68169208fea..b39fcaf95eb 100644 --- a/Cabal/src/Distribution/Simple/Setup/Copy.hs +++ b/Cabal/src/Distribution/Simple/Setup/Copy.hs @@ -15,6 +15,7 @@ -- -- Definition of the copy command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Copy #ifdef __MHS__ ( CopyFlags (..) @@ -33,6 +34,7 @@ module Distribution.Simple.Setup.Copy , defaultCopyFlags , copyCommand ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Haddock.hs b/Cabal/src/Distribution/Simple/Setup/Haddock.hs index df992dcdad3..d00ce13d4e5 100644 --- a/Cabal/src/Distribution/Simple/Setup/Haddock.hs +++ b/Cabal/src/Distribution/Simple/Setup/Haddock.hs @@ -14,6 +14,7 @@ -- -- Definition of the haddock command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Haddock ( HaddockTarget (..) #ifdef __MHS__ @@ -40,6 +41,7 @@ module Distribution.Simple.Setup.Haddock , haddockOptions , haddockProjectOptions ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Hscolour.hs b/Cabal/src/Distribution/Simple/Setup/Hscolour.hs index 8c889628929..07c5f776b4c 100644 --- a/Cabal/src/Distribution/Simple/Setup/Hscolour.hs +++ b/Cabal/src/Distribution/Simple/Setup/Hscolour.hs @@ -14,6 +14,7 @@ -- -- Definition of the hscolour command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Hscolour #ifdef __MHS__ ( HscolourFlags (..) @@ -32,6 +33,7 @@ module Distribution.Simple.Setup.Hscolour , defaultHscolourFlags , hscolourCommand ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Install.hs b/Cabal/src/Distribution/Simple/Setup/Install.hs index 3533d4008b6..e92f137055a 100644 --- a/Cabal/src/Distribution/Simple/Setup/Install.hs +++ b/Cabal/src/Distribution/Simple/Setup/Install.hs @@ -15,6 +15,7 @@ -- -- Definition of the install command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Install #ifdef __MHS__ ( InstallFlags (..) @@ -33,6 +34,7 @@ module Distribution.Simple.Setup.Install , defaultInstallFlags , installCommand ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Register.hs b/Cabal/src/Distribution/Simple/Setup/Register.hs index a90d3b23054..e4c3386c723 100644 --- a/Cabal/src/Distribution/Simple/Setup/Register.hs +++ b/Cabal/src/Distribution/Simple/Setup/Register.hs @@ -14,6 +14,7 @@ -- -- Definition of the register command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Register #ifdef __MHS__ ( RegisterFlags (..) @@ -33,6 +34,7 @@ module Distribution.Simple.Setup.Register , registerCommand , unregisterCommand ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Repl.hs b/Cabal/src/Distribution/Simple/Setup/Repl.hs index a30dbd26af2..7efd34cc21a 100644 --- a/Cabal/src/Distribution/Simple/Setup/Repl.hs +++ b/Cabal/src/Distribution/Simple/Setup/Repl.hs @@ -14,6 +14,7 @@ -- -- Definition of the repl command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Repl #ifdef __MHS__ ( ReplFlags (..) @@ -33,6 +34,7 @@ module Distribution.Simple.Setup.Repl , ReplOptions (..) , replOptions ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/SDist.hs b/Cabal/src/Distribution/Simple/Setup/SDist.hs index ec3c456a298..d873170c37a 100644 --- a/Cabal/src/Distribution/Simple/Setup/SDist.hs +++ b/Cabal/src/Distribution/Simple/Setup/SDist.hs @@ -14,6 +14,7 @@ -- -- Definition of the sdist command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.SDist #ifdef __MHS__ ( SDistFlags (..) @@ -32,6 +33,7 @@ module Distribution.Simple.Setup.SDist , defaultSDistFlags , sdistCommand ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/Setup/Test.hs b/Cabal/src/Distribution/Simple/Setup/Test.hs index eaa736e0017..41ae3a1a890 100644 --- a/Cabal/src/Distribution/Simple/Setup/Test.hs +++ b/Cabal/src/Distribution/Simple/Setup/Test.hs @@ -14,6 +14,7 @@ -- -- Definition of the testing command-line options. -- See: @Distribution.Simple.Setup@ +{- FOURMOLU_DISABLE -} module Distribution.Simple.Setup.Test #ifdef __MHS__ ( TestFlags (..) @@ -34,6 +35,7 @@ module Distribution.Simple.Setup.Test , TestShowDetails (..) , testOptions' ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude hiding (get) import Prelude () diff --git a/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs b/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs index 193fcfb8228..33827275917 100644 --- a/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs +++ b/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs @@ -28,15 +28,16 @@ module Distribution.Simple.SetupHooks.HooksMain ) where -- base + +import Control.Exception + ( Exception (..) + ) import Control.Monad ( (>=>) ) import Control.Monad.IO.Class ( liftIO ) -import Control.Exception - ( Exception (..) - ) import System.Environment ( getArgs ) @@ -93,7 +94,6 @@ instance Show MD5 where -- Cabal import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS) import Distribution.Compat.Prelude -import Prelude () import Distribution.Simple.SetupHooks.Internal import Distribution.Simple.SetupHooks.Rule import Distribution.Simple.Utils @@ -118,6 +118,7 @@ import Distribution.Verbosity import qualified Distribution.Verbosity as Verbosity ( normal ) +import Prelude () -------------------------------------------------------------------------------- -- Hooks version @@ -136,6 +137,7 @@ data HooksVersion = HooksVersion -- | The version of the Hooks API built into this version of the Cabal library. -- -- Used for handshake before beginning inter-process communication. +{- FOURMOLU_DISABLE -} hooksVersion :: HooksVersion hooksVersion = HooksVersion @@ -147,6 +149,7 @@ hooksVersion = , hooksABIHash = structureHash (Proxy :: Proxy CabalABI) #endif } +{- FOURMOLU_ENABLE -} -- | Tracks the parts of the Cabal API relevant to its binary interface. data CabalABI = CabalABI @@ -307,6 +310,7 @@ hooksMain setupHooks = runHooksM $ do where allHookHandlers = [(hookName h, hookHandler h) | h <- hookHandlers] +{- FOURMOLU_DISABLE -} -- Get the communication handles and the name of the hook to run getHooksMainArgs :: HooksM ((Handle, Handle), String) #ifdef __MHS__ @@ -327,6 +331,7 @@ hooksMain setupHooks = runHooksM $ do throwE $ NoHandle (Just $ "hook output communication handle '" ++ outputFdRef ++ "'") _ -> throwE $ NoHandle Nothing #endif +{- FOURMOLU_ENABLE -} type HooksM = ExceptT SetupHooksExeException IO diff --git a/Cabal/src/Distribution/Simple/SetupHooks/Internal.hs b/Cabal/src/Distribution/Simple/SetupHooks/Internal.hs index d2c4be599da..e02b800f62e 100644 --- a/Cabal/src/Distribution/Simple/SetupHooks/Internal.hs +++ b/Cabal/src/Distribution/Simple/SetupHooks/Internal.hs @@ -865,6 +865,7 @@ executeRules = -- | Like 'executeRules', except it can be used when communicating with -- an external hooks executable. +{- FOURMOLU_DISABLE -} executeRulesUserOrSystem :: forall userOrSystem . ( Binary (RuleData userOrSystem) @@ -881,6 +882,8 @@ executeRulesUserOrSystem -> TargetInfo -> Map RuleId (RuleData userOrSystem) -> IO () +{- FOURMOLU_ENABLE -} +{- FOURMOLU_DISABLE -} #ifndef __MHS__ executeRulesUserOrSystem scope runDepsCmdData runCmdData verbosity lbi tgtInfo allRules = do -- Load the rule cache from the previous build. @@ -1143,6 +1146,7 @@ pprNotDemandedRuleReasons -- DataKinds promotion: the scope index is erased). executeRulesUserOrSystem _ _ _ _ _ _ _ = error "Distribution.Simple.SetupHooks.Internal: build-type 'Hooks' is not supported in this MHS build of Cabal." #endif +{- FOURMOLU_ENABLE -} directRuleDependencyMaybe :: Rule.Dependency -> Maybe RuleId directRuleDependencyMaybe (RuleDependency dep) = Just $ outputOfRule dep diff --git a/Cabal/src/Distribution/Simple/SetupHooks/Rule.hs b/Cabal/src/Distribution/Simple/SetupHooks/Rule.hs index ab1cb8376fc..e38389c8674 100644 --- a/Cabal/src/Distribution/Simple/SetupHooks/Rule.hs +++ b/Cabal/src/Distribution/Simple/SetupHooks/Rule.hs @@ -260,6 +260,7 @@ type RuleBinary = RuleData () -- -- Use 'staticRule' or 'dynamicRule' to construct a rule, overriding specific -- fields, rather than directly using the 'Rule' constructor. +{- FOURMOLU_DISABLE -} #ifndef __MHS__ data RuleData (scope :: Scope) #else @@ -302,6 +303,7 @@ instance Binary (RuleData scope) where put _ = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." get = error "Distribution.Simple.SetupHooks.Rule: build-type 'Hooks' is not supported in this MHS build of Cabal." #endif +{- FOURMOLU_ENABLE -} -- | Trimmed down 'Show' instance, mostly for error messages. instance Show RuleBinary where @@ -742,6 +744,7 @@ type Command arg res = CommandData () arg res -- | Internal datatype used for commands, both for the Hooks API ('Command') -- and for the build system. +{- FOURMOLU_DISABLE -} #ifndef __MHS__ data CommandData (scope :: Scope) (arg :: Hs.Type) (res :: Hs.Type) = Command #else @@ -754,6 +757,7 @@ data CommandData scope arg res = Command , cmdInstances :: !(Static scope (Dict (Binary arg, Show arg))) -- ^ Static evidence that the argument can be serialised and deserialised. } +{- FOURMOLU_ENABLE -} -- | Construct a command. -- @@ -919,12 +923,14 @@ includes the length. We use this newtype: - in the definition of 'DepsRes', for the result of dynamic dependency computations. -} +{- FOURMOLU_DISABLE -} #ifndef __MHS__ newtype ScopedArgument (scope :: Scope) arg = ScopedArgument {getArg :: arg} #else newtype ScopedArgument scope arg = ScopedArgument {getArg :: arg} #endif deriving newtype (Eq, Ord, Show) +{- FOURMOLU_ENABLE -} #ifndef __MHS__ -- | Serialise/deserialise, always including the length of the payload. @@ -953,6 +959,7 @@ instance Binary arg => Binary (ScopedArgument scope arg) where -- | A placeholder for a command that has been omitted, e.g. when we don't -- care about serialising/deserialising one particular command in a datatype. +{- FOURMOLU_DISABLE -} #ifndef __MHS__ data NoCmd (scope :: Scope) arg res = CmdOmitted #else @@ -960,6 +967,7 @@ data NoCmd scope arg res = CmdOmitted #endif deriving stock (Generic, Eq, Ord, Show) deriving anyclass (Binary) +{- FOURMOLU_ENABLE -} -- | A dynamic dependency command. newtype DynDepsCmd scope depsArg depsRes = DynDepsCmd @@ -984,6 +992,7 @@ deriving newtype instance Eq (DynDepsCmd scope depsArg depsRes) deriving newtype instance Binary (DynDepsCmd scope depsArg depsRes) #endif +{- FOURMOLU_DISABLE -} -- | The result of a dynamic dependency computation. #ifndef __MHS__ newtype DepsRes (scope :: Scope) depsArg depsRes = DepsRes @@ -994,6 +1003,7 @@ newtype DepsRes scope depsArg depsRes = DepsRes :: ScopedArgument scope depsRes -- See Note [Hooks Binary instances] } deriving newtype (Show, Eq, Ord) +{- FOURMOLU_ENABLE -} deriving newtype instance Binary (ScopedArgument scope depsRes) diff --git a/Cabal/src/Distribution/Simple/Test.hs b/Cabal/src/Distribution/Simple/Test.hs index 752f0f2aee2..ba230bc23f5 100644 --- a/Cabal/src/Distribution/Simple/Test.hs +++ b/Cabal/src/Distribution/Simple/Test.hs @@ -38,6 +38,10 @@ import Distribution.Types.UnqualComponentName import Distribution.Utils.Path import Distribution.Verbosity +import Distribution.Compat.Directory + ( createDirectoryIfMissing + , listDirectory + ) import Distribution.Simple.Configure (getInstalledPackagesById) import Distribution.Simple.Errors import Distribution.Simple.Register (internalPackageDBPath) @@ -46,10 +50,6 @@ import Distribution.Simple.Setup.Config import Distribution.Types.ExposedModule import Distribution.Types.InstalledPackageInfo (InstalledPackageInfo (libraryDirs), exposedModules) import Distribution.Types.LocalBuildInfo (LocalBuildInfo (..)) -import Distribution.Compat.Directory - ( createDirectoryIfMissing - , listDirectory - ) -- | Perform the \"@.\/setup test@\" action. test diff --git a/Cabal/src/Distribution/Simple/Test/ExeV10.hs b/Cabal/src/Distribution/Simple/Test/ExeV10.hs index 26553f2bb86..29b1cbc49a7 100644 --- a/Cabal/src/Distribution/Simple/Test/ExeV10.hs +++ b/Cabal/src/Distribution/Simple/Test/ExeV10.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + module Distribution.Simple.Test.ExeV10 ( runTest ) where @@ -39,12 +40,12 @@ import Distribution.Verbosity import Distribution.Utils.Path import qualified Data.ByteString.Lazy as LBS -import Distribution.Simple.LocalBuildInfo (interpretSymbolicPathLBI, packageRoot) import Distribution.Compat.Directory ( createDirectoryIfMissing , doesFileExist , removePathForcibly ) +import Distribution.Simple.LocalBuildInfo (interpretSymbolicPathLBI, packageRoot) #ifdef __MHS__ import Distribution.Compat.Internal.LazyByteString (readFileLBS) #endif @@ -54,6 +55,7 @@ import Distribution.Compat.Process (createPipe) import qualified Distribution.Compat.Process as Process #endif +{- FOURMOLU_DISABLE -} runTest :: VerbosityHandles -> PD.PackageDescription @@ -263,6 +265,7 @@ runTest verbHandles pkg_descr lbi clbi hpcMarkupInfo flags suite = do testName' l } +{- FOURMOLU_ENABLE -} -- TODO: This is abusing the notion of a 'PathTemplate'. The result isn't -- necessarily a path. diff --git a/Cabal/src/Distribution/Simple/Test/LibV09.hs b/Cabal/src/Distribution/Simple/Test/LibV09.hs index a4d9455513d..25ca4430642 100644 --- a/Cabal/src/Distribution/Simple/Test/LibV09.hs +++ b/Cabal/src/Distribution/Simple/Test/LibV09.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + module Distribution.Simple.Test.LibV09 ( runTest -- Test stub @@ -51,9 +52,10 @@ import Distribution.Compat.Directory #ifdef __MHS__ import Distribution.Compat.Internal.LazyByteString (readFileLBS) #endif -import System.IO (hClose, hPutStr) import qualified Distribution.Compat.Process as Process +import System.IO (hClose, hPutStr) +{- FOURMOLU_DISABLE -} runTest :: VerbosityHandles -> PD.PackageDescription @@ -230,6 +232,7 @@ runTest verbHandles pkg_descr lbi clbi hpcMarkupInfo flags suite = do distPref = fromFlag $ setupDistPref common verbosity = mkVerbosity verbHandles (fromFlag $ setupVerbosity common) +{- FOURMOLU_ENABLE -} -- TODO: This is abusing the notion of a 'PathTemplate'. The result isn't -- necessarily a path. diff --git a/Cabal/src/Distribution/Simple/Utils.hs b/Cabal/src/Distribution/Simple/Utils.hs index 75437b0028d..061b582ed3b 100644 --- a/Cabal/src/Distribution/Simple/Utils.hs +++ b/Cabal/src/Distribution/Simple/Utils.hs @@ -267,7 +267,6 @@ hTryLock _ _ = pure True hUnlock :: Handle -> IO () hUnlock _ = pure () #endif -import Numeric (showFFloat) import Distribution.Compat.Directory ( Permissions (executable) , createDirectory @@ -280,6 +279,7 @@ import Distribution.Compat.Directory , removeFile , removePathForcibly ) +import Numeric (showFFloat) import System.Environment ( getProgName ) @@ -295,6 +295,7 @@ import System.FilePath as FilePath , stripExtension , takeDirectory ) +{- FOURMOLU_DISABLE -} import System.IO ( BufferMode (..) , Handle @@ -313,17 +314,18 @@ import System.IO , stdin , stdout ) +{- FOURMOLU_ENABLE -} #ifdef __MHS__ -- MicroHs System.IO has no binary/text mode distinction. hSetBinaryMode :: Handle -> Bool -> IO () hSetBinaryMode _ _ = pure () #endif +import qualified Distribution.Compat.Process as Process import System.IO.Error import System.IO.Unsafe ( unsafeInterleaveIO ) import qualified System.Info as SI -import qualified Distribution.Compat.Process as Process import qualified Text.PrettyPrint as Disp #ifdef GIT_REV @@ -1229,6 +1231,7 @@ rawSystemStdInOut -- ^ iodata mode, acts as proxy -> IO (mode, String, ExitCode) -- ^ output, errors, exit +{- FOURMOLU_DISABLE -} #ifdef __MHS__ rawSystemStdInOut verbosity path args mcwd menv input iomode = withFrozenCallStack $ do -- MHS: temporary files cannot emulate blocking pipes, so capture @@ -1341,6 +1344,7 @@ rawSystemStdInOut verbosity path args mcwd menv input _ = withFrozenCallStack $ Just ioe -> throwIO (ioeSetFileName ioe ("output of " ++ path)) Nothing -> throwIO exc #endif +{- FOURMOLU_ENABLE -} -- | Ignore SIGPIPE in a subcomputation. ignoreSigPipe :: IO () -> IO () diff --git a/Cabal/src/Distribution/Types/LocalBuildInfo.hs b/Cabal/src/Distribution/Types/LocalBuildInfo.hs index 7a06a4486c5..afecaa001a8 100644 --- a/Cabal/src/Distribution/Types/LocalBuildInfo.hs +++ b/Cabal/src/Distribution/Types/LocalBuildInfo.hs @@ -2,6 +2,7 @@ {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE PatternSynonyms #-} +{- FOURMOLU_DISABLE -} module Distribution.Types.LocalBuildInfo ( -- * The types LocalBuildInfo @@ -99,6 +100,7 @@ module Distribution.Types.LocalBuildInfo , neededTargetsInBuildOrder , withNeededTargetsInBuildOrder ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude import Prelude () diff --git a/Cabal/src/Distribution/Utils/IOData.hs b/Cabal/src/Distribution/Utils/IOData.hs index 67727245277..fb539d1283d 100644 --- a/Cabal/src/Distribution/Utils/IOData.hs +++ b/Cabal/src/Distribution/Utils/IOData.hs @@ -62,6 +62,7 @@ data IODataMode mode where IODataModeText :: IODataMode String IODataModeBinary :: IODataMode LBS.ByteString +{- FOURMOLU_DISABLE -} instance a ~ Char => KnownIODataMode [a] where hGetIODataContents h = do #ifdef __MHS__ @@ -74,7 +75,9 @@ instance a ~ Char => KnownIODataMode [a] where toIOData = IODataText iodataMode = IODataModeText +{- FOURMOLU_ENABLE -} +{- FOURMOLU_DISABLE -} instance KnownIODataMode LBS.ByteString where hGetIODataContents h = do #ifndef __MHS__ @@ -87,6 +90,7 @@ instance KnownIODataMode LBS.ByteString where toIOData = IODataBinary iodataMode = IODataModeBinary +{- FOURMOLU_ENABLE -} -- | 'IOData' Wrapper for 'System.IO.hPutStr' and 'System.IO.hClose' -- @@ -96,6 +100,7 @@ instance KnownIODataMode LBS.ByteString where -- /Note:/ this performs lazy-IO. -- -- @since 2.2 +{- FOURMOLU_DISABLE -} hPutContents :: System.IO.Handle -> IOData -> Prelude.IO () hPutContents h (IODataText c) = do #ifdef __MHS__ @@ -115,3 +120,4 @@ hPutContents h (IODataBinary c) = do LBS.hPutStr h c #endif System.IO.hClose h +{- FOURMOLU_ENABLE -} diff --git a/Cabal/src/Distribution/Utils/LogProgress.hs b/Cabal/src/Distribution/Utils/LogProgress.hs index c2c70b48f49..125a4bc5995 100644 --- a/Cabal/src/Distribution/Utils/LogProgress.hs +++ b/Cabal/src/Distribution/Utils/LogProgress.hs @@ -1,5 +1,6 @@ {-# LANGUAGE CPP #-} +{- FOURMOLU_DISABLE -} module Distribution.Utils.LogProgress ( LogProgress , runLogProgress @@ -11,14 +12,15 @@ module Distribution.Utils.LogProgress , hang #endif ) where +{- FOURMOLU_ENABLE -} import Distribution.Compat.Prelude import Prelude () +import Distribution.Compat.Stack (HasCallStack, callStack, prettyCallStack) import Distribution.Simple.Utils import Distribution.Utils.Progress import Distribution.Verbosity -import Distribution.Compat.Stack (HasCallStack, callStack, prettyCallStack) import System.IO (hFlush, hPutStr, hPutStrLn) import Text.PrettyPrint diff --git a/Cabal/src/Distribution/Verbosity.hs b/Cabal/src/Distribution/Verbosity.hs index a2bb275c06c..f29f0d0ecfc 100644 --- a/Cabal/src/Distribution/Verbosity.hs +++ b/Cabal/src/Distribution/Verbosity.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- Verbosity for Cabal functions. -- | diff --git a/Cabal/tests/ProcessCaptureTests.hs b/Cabal/tests/ProcessCaptureTests.hs index e421586b477..abc9f4c5146 100644 --- a/Cabal/tests/ProcessCaptureTests.hs +++ b/Cabal/tests/ProcessCaptureTests.hs @@ -23,18 +23,18 @@ -- * T7 failing output handle surfaces an error (no silent success) module Main where -import qualified Distribution.Compat.Process as Process import Distribution.Compat.Directory (getTemporaryDirectory, removeFile) +import Distribution.Compat.Process qualified as Process -import qualified Data.ByteString as BS import Control.Exception (SomeException, evaluate, try) -import Control.Monad (when) +import Control.Monad (unless) +import Data.ByteString qualified as BS import Data.List (isInfixOf) +import Data.Maybe (catMaybes) import System.Environment (getEnvironment, lookupEnv, setEnv, unsetEnv) import System.Exit (ExitCode (..), exitFailure, exitSuccess) import System.IO (IOMode (..), hClose, hFlush, hGetContents, hPutStr, openBinaryFile, openFile, openTempFile, stdout) - backend :: String #ifdef __MHS__ backend = "mhs" @@ -87,8 +87,8 @@ tEnvRemoval = do (exit, captured) <- Process.captureProcess (Process.proc "env" []) - { Process.env = Just [("MHS_TEST_ONLY", "present")] - } + { Process.env = Just [("MHS_TEST_ONLY", "present")] + } Process.NoInput out <- readFile (Process.capturedOutPath captured) _ <- evaluate (length out) @@ -145,20 +145,20 @@ tEmptyEnvLookup = do Process.capturedRelease cap2 check "T3c empty env + parent-PATH lookup" (exit1 == ExitSuccess && out1 == "hi\n" && exit2 == ExitSuccess && out2 == "") --- T3d: malformed entries pass through to the child unchanged (matching --- System.Process.createProcess, which does not validate), rather --- than being rejected or silently rewritten. +-- T3d: values containing '=' and empty values pass through to the +-- child unchanged (matching System.Process.createProcess). tMalformedEnv :: IO (Maybe Failure) tMalformedEnv = do - (exit, captured) <- Process.captureProcess - (Process.proc "env" []) - { Process.env = Just [("BAD=KEY", "v"), ("", "w")] - } - Process.NoInput + (exit, captured) <- + Process.captureProcess + (Process.proc "env" []) + { Process.env = Just [("MHS_K1", "a=b"), ("MHS_K2", "")] + } + Process.NoInput out <- readFile (Process.capturedOutPath captured) _ <- evaluate (length out) Process.capturedRelease captured - check "T3d malformed entries pass through" (exit == ExitSuccess && "BAD=KEY=v\n" `isInfixOf` out && "=w\n" `isInfixOf` out) + check "T3d special env values pass through" (exit == ExitSuccess && "MHS_K1=a=b\n" `isInfixOf` out && "MHS_K2=\n" `isInfixOf` out) -- T4: regular files as UseHandle stdin and stdout. tFileHandles :: IO (Maybe Failure) @@ -204,10 +204,30 @@ tUtf8FileHandles = do tmpDir <- getTemporaryDirectory let want = BS.pack - [ 0x63, 0x61, 0x66, 0xC3, 0xA9, 0x20 - , 0xE2, 0x80, 0x9C, 0x71, 0x75, 0x6F, 0x74, 0x65, 0xE2, 0x80, 0x9D - , 0x20, 0xE2, 0x82, 0xAC, 0x0A - ] :: BS.ByteString + [ 0x63 + , 0x61 + , 0x66 + , 0xC3 + , 0xA9 + , 0x20 + , 0xE2 + , 0x80 + , 0x9C + , 0x71 + , 0x75 + , 0x6F + , 0x74 + , 0x65 + , 0xE2 + , 0x80 + , 0x9D + , 0x20 + , 0xE2 + , 0x82 + , 0xAC + , 0x0A + ] + :: BS.ByteString (inTmp, inH0) <- openTempFile tmpDir "t4b-in" hClose inH0 BS.writeFile inTmp want @@ -269,9 +289,12 @@ tUtf8FileHandles = do Right (exit1, gotText, exit2, gotBin, exit3, gotEcho) -> check "T4b UTF-8 file handles round-trip" - ( exit1 == ExitSuccess && gotText == want - && exit2 == ExitSuccess && gotBin == want - && exit3 == ExitSuccess && gotEcho == want + ( exit1 == ExitSuccess + && gotText == want + && exit2 == ExitSuccess + && gotBin == want + && exit3 == ExitSuccess + && gotEcho == want ) -- T5: exit codes and stream separation. @@ -362,8 +385,8 @@ main = do , tCreatePipe , tFailingHandle ] - let failures = [f | Just f <- results] - when (not (null failures)) $ do + let failures = catMaybes results + unless (null failures) $ do mark ("failures: " ++ show failures) exitFailure mark "all green" diff --git a/Makefile b/Makefile index e2d1b78b8b0..138028ac1bb 100644 --- a/Makefile +++ b/Makefile @@ -63,6 +63,7 @@ check: @cd Cabal-hooks && cabal check | grep -q "No errors or warnings could be found in the package." @cd hooks-exe && cabal check | grep -q "No errors or warnings could be found in the package." @cd cabal-install-solver && cabal check | grep -q "No errors or warnings could be found in the package." + @cd mhs-compat-shims && cabal check | grep -q "No errors or warnings could be found in the package." .PHONY: style-todo style-todo: ## Configured for fourmolu, avoiding GHC parser failures. diff --git a/bootstrap/mhs/build-cabal-mhs.sh b/bootstrap/mhs/build-cabal-mhs.sh new file mode 100755 index 00000000000..18131e71a55 --- /dev/null +++ b/bootstrap/mhs/build-cabal-mhs.sh @@ -0,0 +1,288 @@ +#!/usr/bin/env bash +# Bootstrap cabal-install (exe:cabal) using MicroHs (mhs 0.16.12.0). +# +# Usage: +# bootstrap/mhs/build-cabal-mhs.sh [toolchain|build|test|all] +# +# Environment variables: +# MHS_PREFIX Installation directory for MicroHs + packages (default: $HOME/.mcabal) +# MHS_SRC_DIR Checkout directory for augustss/MicroHs (default: _build/mhs-src) +# MHS_CACHE_DIR Directory for staged .mhscache checkpoints (default: _build/mhs-cache) +# ARTIFACT_DIR Output directory for the linked cabal binary (default: _build/artifacts) + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$REPO_ROOT" + +MHS_COMMIT="9e1cd08" +MHS_VERSION="0.16.12.0" +MHS_PREFIX="${MHS_PREFIX:-$HOME/.mcabal}" +MHS_SRC_DIR="${MHS_SRC_DIR:-$REPO_ROOT/_build/mhs-src}" +MHS_CACHE_DIR="${MHS_CACHE_DIR:-$REPO_ROOT/_build/mhs-cache}" +MHS_AUTOGEN_DIR="${MHS_AUTOGEN_DIR:-$REPO_ROOT/_build/mhs-autogen}" +MHS_WORK_DIR="${MHS_WORK_DIR:-$REPO_ROOT/_build/mhs-work}" +ARTIFACT_DIR="${ARTIFACT_DIR:-$REPO_ROOT/_build/artifacts}" + +MHS_BIN="$MHS_PREFIX/bin/mhs" +MCABAL_BIN="$MHS_PREFIX/bin/mcabal" +MHS_PKG_DIR="$MHS_PREFIX/mhs-$MHS_VERSION/packages" +TOOLCHAIN_STAMP="$MHS_PKG_DIR/.cabal-mhs-toolchain-v2.stamp" + +export PATH="$MHS_PREFIX/bin:/usr/bin:/bin:$HOME/.mcabal/bin:$PATH" + +build_toolchain() { + if [ -x "$MHS_BIN" ] && [ -f "$TOOLCHAIN_STAMP" ]; then + echo "=== [toolchain] Reusing cached MicroHs $MHS_VERSION toolchain in $MHS_PREFIX ===" + "$MHS_BIN" --version + else + echo "=== [toolchain] Building patched MicroHs $MHS_VERSION ($MHS_COMMIT) ===" + rm -rf "$MHS_SRC_DIR" + mkdir -p "$(dirname "$MHS_SRC_DIR")" + git clone https://github.com/augustss/MicroHs.git "$MHS_SRC_DIR" + git -C "$MHS_SRC_DIR" checkout "$MHS_COMMIT" + git -C "$MHS_SRC_DIR" apply "$REPO_ROOT/bootstrap/mhs/microhs-full.patch" + + # 1. Build and install stage-0 mhs, cpphs, mcabal, runtime, and base from upstream C sources + make -C "$MHS_SRC_DIR" MCABAL="$MHS_PREFIX" install + + # 2. Self-compile the patched MicroHs compiler (src/*/*.hs) into C using stage-0 bin/mhs + echo "=== [toolchain] Self-compiling patched MicroHs.Main ===" + ( + cd "$MHS_SRC_DIR" + ./bin/mhs -z -i -imhs -isrc -ilib MicroHs.Main -ogenerated/mhs-patched.c + cc -Wall -O3 -DHEAP_CELLS=350000000 -DSTACK_SIZE=32000000 \ + -Isrc/runtime -Isrc/runtime/unix \ + src/runtime/main.c src/runtime/eval.c generated/mhs-patched.c \ + -lm -o "$MHS_BIN" + ) + "$MHS_BIN" --version + + # 3. Rebuild base-0.16.12.0.pkg uncompressed with patched mhs + echo "=== [toolchain] Building uncompressed base-$MHS_VERSION.pkg ===" + ( + cd "$MHS_SRC_DIR/lib" + CABALDIR="$MHS_PREFIX" "$MCABAL_BIN" install + ) + + # 4. Fetch Stackage snapshot and install standard pure-Haskell dependencies via mcabal + echo "=== [toolchain] Installing standard dependencies via mcabal ===" + mkdir -p "$MHS_WORK_DIR" + ( + cd "$MHS_WORK_DIR" + CABALDIR="$MHS_PREFIX" "$MCABAL_BIN" update + for pkg in containers parsec filepath time async random; do + echo "--- Installing $pkg ---" + CABALDIR="$MHS_PREFIX" "$MCABAL_BIN" -r install "$pkg" + done + ) + touch "$TOOLCHAIN_STAMP" + fi + + # 5. Build and install mhs-compat-shims-0.1.0.0.pkg from mhs-compat-shims/ + echo "=== [toolchain] Building and installing mhs-compat-shims-0.1.0.0.pkg ===" + mkdir -p "$MHS_WORK_DIR" + local mhs_dir="$MHS_PREFIX/mhs-$MHS_VERSION" + rm -f "$MHS_PKG_DIR"/pretty-mhs-*.pkg \ + "$MHS_PKG_DIR"/uri-mhs-*.pkg \ + "$MHS_PKG_DIR"/binary-mhs-*.pkg \ + "$MHS_PKG_DIR"/text-encoding-mhs-*.pkg + "$MHS_BIN" +RTS -H350M -K32M -RTS -Pmhs-compat-shims-0.1.0.0 \ + -i"$REPO_ROOT/mhs-compat-shims/src" \ + -I"$REPO_ROOT/mhs-compat-shims/cbits" \ + Data.Binary Data.Binary.Get Data.Binary.Put \ + Text.PrettyPrint \ + Network.URI \ + Data.Text.Encoding.Error Data.Text.Internal.Encoding.Utf8 Data.Text.Lazy.Encoding \ + Distribution.Compat.MhsInstances \ + Distribution.Compat.Internal.MhsPosix \ + Distribution.Compat.Internal.MhsProcess \ + Distribution.Client.Compat.Base16 \ + -o "$MHS_WORK_DIR/mhs-compat-shims-0.1.0.0.pkg" + "$MHS_BIN" -Q "$MHS_WORK_DIR/mhs-compat-shims-0.1.0.0.pkg" "$mhs_dir" + + ls -lh "$MHS_PKG_DIR"/*.pkg +} + +generate_autogen() { + mkdir -p "$MHS_AUTOGEN_DIR" + cat > "$MHS_AUTOGEN_DIR/Paths_Cabal.hs" <<'EOF' +module Paths_Cabal (version, getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir) where +import Data.Version (Version(..)) +version :: Version +version = Version [3,19,0,0] [] +getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath +getBinDir = return "/private/tmp/mhs-lane-c/bin" +getLibDir = return "/private/tmp/mhs-lane-c/lib" +getDynLibDir = return "/private/tmp/mhs-lane-c/lib" +getDataDir = return "/private/tmp/mhs-lane-c/data" +getLibexecDir = return "/private/tmp/mhs-lane-c/libexec" +getSysconfDir = return "/private/tmp/mhs-lane-c/etc" +EOF + + cat > "$MHS_AUTOGEN_DIR/Paths_cabal_install.hs" <<'EOF' +module Paths_cabal_install (version, getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir) where +import Data.Version (Version(..)) +version :: Version +version = Version [3,19,0,0] [] +getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath +getBinDir = return "/private/tmp/mhs-lane-e/bin" +getLibDir = return "/private/tmp/mhs-lane-e/lib" +getDynLibDir = return "/private/tmp/mhs-lane-e/lib" +getDataDir = return "/private/tmp/mhs-lane-e/data" +getLibexecDir = return "/private/tmp/mhs-lane-e/libexec" +getSysconfDir = return "/private/tmp/mhs-lane-e/etc" +EOF +} + +build_cabal_mhs() { + generate_autogen + mkdir -p "$MHS_CACHE_DIR" "$MHS_WORK_DIR" "$ARTIFACT_DIR" + + local active_cache="$MHS_CACHE_DIR/active.mhscache" + local last_good="$MHS_CACHE_DIR/last-good.mhscache" + + local flags=( + -v + "-C$active_cache" + -iCabal-syntax/src -iCabal/src -ihooks-exe/cli -ihooks-exe/src + -icabal-install-solver/src -icabal-install-solver/src-assertion + -icabal-install/src -icabal-install/main + "-i$MHS_AUTOGEN_DIR" + -ICabal-syntax/src -ICabal/src -Icabal-install/src + -Imhs-compat-shims/cbits + -DBOOTSTRAPPED_CABAL=1 + ) + + local flags_ro=( + -v + "-CR$active_cache" + -iCabal-syntax/src -iCabal/src -ihooks-exe/cli -ihooks-exe/src + -icabal-install-solver/src -icabal-install-solver/src-assertion + -icabal-install/src -icabal-install/main + "-i$MHS_AUTOGEN_DIR" + -ICabal-syntax/src -ICabal/src -Icabal-install/src + -Imhs-compat-shims/cbits + -DBOOTSTRAPPED_CABAL=1 + ) + + step_mhs() { + local name="$1" + local mod="$2" + local done_stamp="$MHS_CACHE_DIR/${name}.done" + if [ -f "$done_stamp" ] && [ -s "$last_good" ]; then + echo "=== [$name] Reusing completed checkpoint ($mod) ===" + return 0 + fi + echo "=== [$name] Compiling $mod ($(date '+%H:%M:%S')) ===" + if [ -s "$last_good" ]; then + cp "$last_good" "$active_cache" + else + rm -f "$active_cache" + fi + "$MHS_BIN" +RTS -H350M -K32M -RTS "${flags[@]}" -c -o "$MHS_WORK_DIR/${name}.c" "$mod" + if [ -s "$active_cache" ]; then + mv "$active_cache" "$last_good" + touch "$done_stamp" + rm -f "$MHS_WORK_DIR/${name}.c" + ls -lh "$last_good" + else + echo "ERROR: cache empty after $name ($mod)" + exit 1 + fi + } + + # Stage 1: Cabal-syntax (127 modules) + step_mhs stage1 Distribution.PackageDescription.Parsec + + # Stage 2: Cabal + hooks-exe (167 modules) + step_mhs stage2a Distribution.Simple.Configure + step_mhs stage2c Distribution.Simple + step_mhs stage2d Distribution.Simple.SetupHooks.HooksMain + + # Stage 3: cabal-install-solver (53 modules) + step_mhs stage3 Distribution.Solver.Modular + + # Stage 4: cabal-install (181 modules) + step_mhs stage4_ciflags Distribution.Client.CmdInstall.ClientInstallFlags + step_mhs stage4_pflags Distribution.Client.ProjectFlags + step_mhs stage4_pkghash Distribution.Client.PackageHash + step_mhs stage4_inlib Distribution.Client.InLibrary + step_mhs stage4_spol Distribution.Client.ProjectPlanning.SetupPolicy + step_mhs stage4_pplan Distribution.Client.ProjectPlanning + step_mhs stage4_cmain Distribution.Client.Main + + echo "=== [link] Linking $ARTIFACT_DIR/cabal ($(date '+%H:%M:%S')) ===" + if [ ! -s "$active_cache" ] && [ -s "$last_good" ]; then + cp "$last_good" "$active_cache" + fi + + local link_opts=(-optl -lz) + if [ "$(uname -s)" = "Darwin" ]; then + link_opts+=(-optl -Wl,-stack_size,0x10000000) + else + link_opts+=(-optl -lcrypto) + fi + + "$MHS_BIN" +RTS -H350M -K32M -RTS "${flags_ro[@]}" \ + mhs-compat-shims/cbits/mhs_posix.c \ + mhs-compat-shims/cbits/mhs_spawn.c \ + mhs-compat-shims/cbits/mhs_handle.c \ + mhs-compat-shims/cbits/mhs_sha256.c \ + "${link_opts[@]}" \ + -o "$ARTIFACT_DIR/cabal" \ + Main + + rm -f "$active_cache" + ls -lh "$ARTIFACT_DIR/cabal" +} + +run_smoke_tests() { + local cabal_bin="$ARTIFACT_DIR/cabal" + echo "=== [test] Smoke-testing $cabal_bin ===" + "$cabal_bin" --version + "$cabal_bin" --numeric-version + "$cabal_bin" build --help | grep -E "build-compiler|with-compiler" + (cd "$REPO_ROOT/Cabal-syntax" && "$cabal_bin" check) + + echo "=== [test] Compiling and running Cabal/tests/ProcessCaptureTests.hs with mhs ===" + mkdir -p "$MHS_WORK_DIR" + local active_cache="$MHS_CACHE_DIR/active.mhscache" + local last_good="$MHS_CACHE_DIR/last-good.mhscache" + if [ -s "$last_good" ]; then + cp "$last_good" "$active_cache" + fi + "$MHS_BIN" +RTS -H350M -K32M -RTS \ + "-CR$active_cache" \ + -iCabal-syntax/src -iCabal/src -iCabal/tests \ + -ICabal-syntax/src -ICabal/src -Imhs-compat-shims/cbits \ + mhs-compat-shims/cbits/mhs_posix.c \ + mhs-compat-shims/cbits/mhs_spawn.c \ + mhs-compat-shims/cbits/mhs_handle.c \ + -o "$MHS_WORK_DIR/ProcessCaptureTests" \ + Cabal/tests/ProcessCaptureTests.hs + rm -f "$active_cache" + "$MHS_WORK_DIR/ProcessCaptureTests" +} + +cmd="${1:-all}" +case "$cmd" in + toolchain) + build_toolchain + ;; + build) + build_cabal_mhs + ;; + test) + run_smoke_tests + ;; + all) + build_toolchain + build_cabal_mhs + run_smoke_tests + ;; + *) + echo "Usage: $0 [toolchain|build|test|all]" >&2 + exit 1 + ;; +esac diff --git a/bootstrap/mhs/microhs-full.patch b/bootstrap/mhs/microhs-full.patch new file mode 100644 index 00000000000..bb9fa15e8d1 --- /dev/null +++ b/bootstrap/mhs/microhs-full.patch @@ -0,0 +1,286 @@ +diff --git a/lib/System/IO/Serialize.hs b/lib/System/IO/Serialize.hs +index 75683cf..d0bb25d 100644 +--- a/lib/System/IO/Serialize.hs ++++ b/lib/System/IO/Serialize.hs +@@ -39,12 +39,7 @@ foreign import ccall "add_lzma_compressor" c_add_lzma_compressor :: Ptr BFIL + foreign import ccall "add_lzma_decompressor" c_add_lzma_decompressor :: Ptr BFILE -> IO (Ptr BFILE) + + writeSerializedCompressed :: forall a . FilePath -> a -> IO () +-writeSerializedCompressed p s = do +- h <- openBinaryFile p WriteMode +- hPutChar h 'q' -- indicate compressed +- h' <- addTransducer c_add_lzma_compressor h +- hSerialize h' s +- hFlush h' ++writeSerializedCompressed p s = writeSerialized p s + + -- Read compressed or uncompressed + readSerialized :: FilePath -> IO a +diff --git a/src/MicroHs/CompileCache.hs b/src/MicroHs/CompileCache.hs +index ed6ad28..6535070 100644 +--- a/src/MicroHs/CompileCache.hs ++++ b/src/MicroHs/CompileCache.hs +@@ -134,7 +134,7 @@ addPackage mf p c = c{ + where ins t = M.insert (tModuleName t) (PkgMdl t) + + saveCache :: FilePath -> Cache -> IO () +-saveCache fn cash = writeSerializedCompressed fn (forceCache cash) ++saveCache fn cash = writeSerialized fn (forceCache cash) + + loadCached :: FilePath -> IO (Maybe Cache) + loadCached fn = do +diff --git a/src/MicroHs/Deriving.hs b/src/MicroHs/Deriving.hs +index 92b8210..6c3dca6 100644 +--- a/src/MicroHs/Deriving.hs ++++ b/src/MicroHs/Deriving.hs +@@ -38,6 +38,7 @@ deriveStrat mctx newt lhs cs strat (narg, acls) = -- narg is the number of argu + DerNewtype | newt -> newtypeDer mctx narg lhs c acls =<< getVia narg lhs c + DerAnyClass -> anyclassDer mctx narg lhs cls + DerVia via | newt -> newtypeDer mctx narg lhs c acls via ++ | otherwise -> deriveNoHdr mctx narg lhs cs cls + _ -> cannotDerive lhs cls + where useNewt d = unIdent (getAppCon d) `notElem` + ["Data.Data_Class.Data", "Data.Typeable.Typeable", "GHC.Generics.Generic", "GHC.Generics.Generic1", +@@ -59,6 +60,8 @@ derivers = + ,("Data.Foldable.Foldable", derFoldable) + ,("Data.Functor.Functor", derFunctor) + ,("Data.Ix.Ix", derIx) ++ ,("Data.Monoid.Internal.Monoid", derMonoid) ++ ,("Data.Monoid.Internal.Semigroup", derSemigroup) + ,("Data.Ord.Ord", derOrd) + ,("Data.Traversable.Traversable", derTraversable) + ,("Data.Typeable.Typeable", derTypeable) +@@ -309,6 +312,33 @@ derEq _ _ lhs _ e = cannotDerive lhs e + + -------------------------------------------- + ++derSemigroup :: Deriver ++derSemigroup mctx 0 lhs cs@[c@(Constr _ _ con _ _)] esem = do ++ hdr <- mkHdr mctx lhs cs esem ++ let loc = getSLoc esem ++ (xp, xs) = mkPat c "x$" ++ (yp, ys) = mkPat c "y$" ++ eAppend = eAppI2 (mkBuiltin loc "<>") ++ rhs = tApps con (zipWith eAppend xs ys) ++ iAppend = mkIdentSLoc loc "<>" ++ inst = Instance hdr [Fcn iAppend [eEqn [xp, yp] rhs]] [] ++ return [inst] ++derSemigroup _ _ lhs _ e = cannotDerive lhs e ++ ++derMonoid :: Deriver ++derMonoid mctx 0 lhs cs@[c@(Constr _ _ con _ _)] emon = do ++ hdr <- mkHdr mctx lhs cs emon ++ let loc = getSLoc emon ++ (_, xs) = mkPat c "x$" ++ eMempty = EVar (mkIdentSLoc loc "mempty") ++ rhs = tApps con (map (const eMempty) xs) ++ iMempty = mkIdentSLoc loc "mempty" ++ inst = Instance hdr [Fcn iMempty [eEqn [] rhs]] [] ++ return [inst] ++derMonoid _ _ lhs _ e = cannotDerive lhs e ++ ++-------------------------------------------- ++ + derOrd :: Deriver + derOrd mctx 0 lhs cs eord = do + hdr <- mkHdr mctx lhs cs eord +diff --git a/src/MicroHs/Main.hs b/src/MicroHs/Main.hs +index 8b1f581..07be22a 100644 +--- a/src/MicroHs/Main.hs ++++ b/src/MicroHs/Main.hs +@@ -264,7 +264,7 @@ mainBuildPkg flags namever amns = do + t1 <- getTimeMilli + when (verbose flags > 0) $ + putStrLn $ "Writing package " ++ namever ++ " to " ++ output flags +- writeSerializedCompressed (output flags) (forcePackage pkg) ++ writeSerialized (output flags) (forcePackage pkg) + t2 <- getTimeMilli + when (verbose flags > 0) $ + putStrLn $ "Compression time " ++ show (t2 - t1) ++ " ms" +diff --git a/src/MicroHs/Parse.hs b/src/MicroHs/Parse.hs +index 8163077..096bd9d 100644 +--- a/src/MicroHs/Parse.hs ++++ b/src/MicroHs/Parse.hs +@@ -682,7 +682,7 @@ pAPat = + i <- pLIdentSym + (pSpec '@' *> (EAt i <$> pAPat)) <|> pure (EVar i) + ) +- <|> (evar <$> pUQIdentSym <*> optional pUpdate) ++ <|> (evar <$> pUQIdentSym <*> optional pPatUpdate) + <|> pLit + <|> (lpar *> (eTuple <$> sepBy pPatV comma <* rpar)) + <|> (lbra *> (EListish . LList <$> sepBy1 pPat comma <* rbra)) +@@ -888,11 +888,17 @@ pAExpr = do + pure $ post ee ps + + pUpdate :: P [EField] +-pUpdate = pSpec '{' *> sepSEBy pEField comma <* pSpec '}' ++pUpdate = pUpdateWith pExpr ++ ++pPatUpdate :: P [EField] ++pPatUpdate = pUpdateWith pPat ++ ++pUpdateWith :: P Expr -> P [EField] ++pUpdateWith pe = pSpec '{' *> sepSEBy pEField comma <* pSpec '}' + where + pEField = do + fs <- (:) . unQualIdent <$> pLQIdentSym <*> many pSelect +- EField fs <$> (equal *> pExpr) <|> pure (EFieldPun fs) ++ EField fs <$> (equal *> pe) <|> pure (EFieldPun fs) + <|> + (EFieldWild <$ pSymbol "..") + +diff --git a/src/MicroHs/TypeCheck.hs b/src/MicroHs/TypeCheck.hs +index 8ce89f1..a80424e 100644 +--- a/src/MicroHs/TypeCheck.hs ++++ b/src/MicroHs/TypeCheck.hs +@@ -2067,6 +2067,7 @@ tcExprR mt ae = + munify loc mt ttup + return (ETuple ees) + EParen e -> tcExpr mt e ++ EDo Nothing ass | Just appDo <- dsApplicativeDo loc ass -> tcExpr mt appDo + EDo mmn ass -> do + case ass of + [] -> impossible +@@ -2279,6 +2280,35 @@ dsSRec mmn imfix iret ss = + let vs = eTuple $ map EVar $ concatMap getStmtBound ss + in SBind vs $ eAppI imfix $ eLam [ELazy True vs] $ EDo mmn (ss ++ [SThen $ eAppI iret vs]) + ++-- Desugar an ApplicativeDo-compatible 'do' block (ending in @pure body@ where ++-- none of the '<-'-bound variables appear in the statement actions or let-bindings) ++-- into @let ... in fmap (\x1 ... xn -> body) e1 <*> ... <*> en@. ++dsApplicativeDo :: SLoc -> [EStmt] -> Maybe Expr ++dsApplicativeDo loc ass ++ | length ass >= 2 ++ , SThen lastExpr <- last ass ++ , Just body <- unPure lastExpr ++ , Just steps <- mapM toStep (init ass) ++ , let lets = [ bs | Left bs <- steps ] ++ binds = [ xe | Right xe <- steps ] ++ boundVars = [ x | (x, _) <- binds, not (isDummyIdent x) ] ++ rhsVars = concatMap (allVarsExpr . snd) binds ++ concatMap (concatMap allVarsBind) lets ++ , ((_, e1) : rest) <- binds ++ , all (`notElem` rhsVars) boundVars = ++ let lam = eLam [ EVar x | (x, _) <- binds ] body ++ app0 = EApp (EApp (EVar (mkBuiltin loc "fmap")) lam) e1 ++ appAll = foldl (\acc (_, ei) -> EApp (EApp (EVar (mkBuiltin loc "<*>")) acc) ei) app0 rest ++ in Just (foldr ELet appAll lets) ++ | otherwise = Nothing ++ where ++ unPure (EApp (EVar p) b) | unIdent (unQualIdent p) == "pure" = Just b ++ unPure (EOper (EVar p) [(op, b)]) | unIdent (unQualIdent p) == "pure", unIdent (unQualIdent op) == "$" = Just b ++ unPure _ = Nothing ++ toStep (SBind (EVar x) e) | not (isConIdent x) = Just (Right (x, e)) ++ toStep (SThen e) = Just (Right (dummyIdent, e)) ++ toStep (SLet bs) = Just (Left bs) ++ toStep _ = Nothing ++ + -- XXX Maybe allow singleton tuples + eTuple :: [Expr] -> Expr + eTuple [e] = e +@@ -2556,7 +2586,9 @@ dsEFields apat = + EViewPat e p -> EViewPat e <$> dsEFields p + ELazy z p -> ELazy z <$> dsEFields p + ECon _ -> return apat +- EUpdate c fs -> EUpdate c . concat <$> mapM (dsEField fs c) fs ++ EUpdate c fs -> do ++ fs' <- concat <$> mapM (dsEField fs c) fs ++ EUpdate c <$> mapM (\ f -> case f of EField is p -> EField is <$> dsEFields p; _ -> impossible) fs' + EParen p -> dsEFields p + ENegApp _ -> return apat + EOr ps -> EOr <$> mapM dsEFields ps +@@ -3136,7 +3168,12 @@ tcBindGrp' bs = do + -- find constraints involving the local tyvars + let ctx = nubBy eqEType $ + filter (\ c -> not $ null $ intersect qvs' (metaTvs [c])) cs +- let multiParam ct = length (snd (getApp ct)) /= 1 ++ let multiParam ct = ++ case getAppM ct of ++ Just (_, as) -> length as /= 1 ++ -- Unknown head (e.g. flexible class variable): ++ -- stay monomorphic rather than fail. ++ Nothing -> True + if any multiParam ctx || -- temporary workaround for + -- Overloaded bind: fallback to monomorphic behavior + not (null ctx) && not (all isSynFcn bs') then +@@ -3680,7 +3717,10 @@ getSuperClasses ais = do + loop done (i:is) | i `elem` done = loop done is + | otherwise = i : + case M.lookup i ct of +- Nothing -> error $ "getSuperClasses: " ++ show i ++ -- Unknown class (e.g. a class variable from a ++ -- variable-headed constraint): it has no known ++ -- superclasses, but keep it in the result. ++ Nothing -> loop (i:done) is + Just (ClassInfo _ supers _ _ _) -> + loop (i:done) (concatMap flatten supers ++ is) + flatten a = +@@ -3766,8 +3806,6 @@ solveMany ((di, ct) : cnss) uns sol imp | Just (_, (dd, _)) <- find (eqEType ct + solveMany (cns@(di, ct) : cnss) uns sol imp = do + -- tcTrace ("solveMany: trying " ++ showEType ct) + let loc = getSLoc di +- (iCls, cts) = getApp ct +- solver = head [ s | (p, s) <- solvers, p iCls ] + ads <- gets argDicts + -- Check if we have an exact match among the arguments dictionaries. + -- This is important to find tupled dictionaries in recursive calls. +@@ -3776,11 +3814,54 @@ solveMany (cns@(di, ct) : cnss) uns sol imp = do + -- tcTrace $ "solve with arg " ++ show ct + solveMany cnss uns ((ct, (di, EVar ai)) : sol) imp + [] -> do +- msol <- solver loc iCls cts +--- tcTrace ("solveMany msol=" ++ show msol) +- case msol of +- Nothing -> solveMany cnss (cns : uns) sol imp +- Just (de, gs, is) -> solveMany (gs ++ cnss) uns ((ct, (di, de)) : sol) (is ++ imp) ++ case getAppM ct of ++ -- The head of the goal is not (yet) known. This happens with ++ -- variable-headed constraints, e.g. goal (_c (Maybe _a)) from ++ -- instantiating (c (Maybe a)). Try to match a local given up ++ -- to substitution; if none matches, leave the goal unsolved in ++ -- hope that the head gets resolved later. Either way, do not fail here. ++ Nothing -> ++ case matchFlexGoal loc ct ads of ++ Just (ai, is) -> solveMany cnss uns ((ct, (di, EVar ai)) : sol) (is ++ imp) ++ Nothing -> solveMany cnss (cns : uns) sol imp ++ Just (iCls, cts) -> do ++ let solver = head [ s | (p, s) <- solvers, p iCls ] ++ msol <- solver loc iCls cts ++-- tcTrace ("solveMany msol=" ++ show msol) ++ case msol of ++ Nothing -> solveMany cnss (cns : uns) sol imp ++ Just (de, gs, is) -> solveMany (gs ++ cnss) uns ((ct, (di, de)) : sol) (is ++ imp) ++ ++-- Match a goal whose head is a unification variable (from a ++-- variable-headed constraint like (c t)) against the local givens. ++-- Succeeds when some given matches the goal up to substitution of the ++-- goal's unification variables, e.g. goal (_c (Maybe _a)) against ++-- given (C (Maybe b)) with [_c := C, _a := b]. ++-- Returns the given dictionary and the improving substitution. ++-- If several givens match, the first one wins (same policy as the ++-- exact match in solveMany; duplicates typically come from ++-- superclass diamonds). ++matchFlexGoal :: SLoc -> EConstraint -> [(Ident, EConstraint)] -> Maybe (Ident, [Improve]) ++matchFlexGoal loc ct ads = ++ case [ (ai, mkImp s) ++ | (ai, act) <- ads ++ , let (wh, was) = splitApp ct ++ (gh, gas) = splitApp act ++ , length was == length gas ++ , Just (s, _) <- [matchTypes loc (wh : was) (gh : gas) []] ++ ] of ++ (ai, is) : _ -> Just (ai, is) ++ _ -> Nothing ++ where mkImp s = [ (loc, EUVar i, t) | (i, t) <- s ] ++ ++-- Split a type application into head and arguments, mirroring getAppM ++-- but keeping a flexible head instead of failing on it. ++splitApp :: EType -> (EType, [EType]) ++splitApp = loop [] ++ where loop as (EApp f a) = loop (a : as) f ++ loop as (EParen e) = loop as e ++ loop as (EOper e1 [(op, e2)]) = loop as $ EApp (EApp (EVar op) e1) e2 ++ loop as t = (t, as) + + solveInst :: SolveOne + solveInst loc iCls cts = do diff --git a/cabal-dev-scripts/src/Capture.hs b/cabal-dev-scripts/src/Capture.hs index f2fc4cce83d..2f5d91b3ee7 100644 --- a/cabal-dev-scripts/src/Capture.hs +++ b/cabal-dev-scripts/src/Capture.hs @@ -4,6 +4,7 @@ import Language.Haskell.TH import Language.Haskell.TH.Syntax (NameFlavour (..), Name (..)) import Data.Generics as SYB +import Data.List (intercalate) -- | Capture the source code of declarations in the variable capture @@ -15,7 +16,7 @@ capture name decls = do -- mangle all names to drop unique suffixes and module prefixes let decls2 = SYB.everywhere (SYB.mkT mangleName) decls1 - let declsStr = pprint decls2 + let declsStr = intercalate "\n" . map guardDerivingGeneric . lines $ pprint decls2 -- liftIO (putStrLn declsStr) let nameTyDecl :: Dec @@ -28,3 +29,7 @@ capture name decls = do where mangleName :: Name -> Name mangleName (Name occ _) = Name occ NameS + + guardDerivingGeneric :: String -> String + guardDerivingGeneric " deriving Generic" = "#ifndef __MHS__\n deriving Generic\n#endif" + guardDerivingGeneric line = line diff --git a/cabal-dev-scripts/src/GenCabalMacros.hs b/cabal-dev-scripts/src/GenCabalMacros.hs index 9a02370792d..0d55a0823a1 100644 --- a/cabal-dev-scripts/src/GenCabalMacros.hs +++ b/cabal-dev-scripts/src/GenCabalMacros.hs @@ -76,6 +76,7 @@ config = ModuleConfig { mcRender = "render" , mcHeader = [ "{- FOURMOLU_DISABLE -}" + , "{-# LANGUAGE CPP #-}" , "{-# LANGUAGE DeriveGeneric #-}" , "module Distribution.Simple.Build.Macros.Z (render, Z(..), ZPackage (..), ZTool (..)) where" , "import Distribution.ZinzaPrelude" diff --git a/cabal-dev-scripts/src/GenPathsModule.hs b/cabal-dev-scripts/src/GenPathsModule.hs index 260f1e9cde8..d48c9dd567b 100644 --- a/cabal-dev-scripts/src/GenPathsModule.hs +++ b/cabal-dev-scripts/src/GenPathsModule.hs @@ -69,6 +69,7 @@ config = ModuleConfig { mcRender = "render" , mcHeader = [ "{- FOURMOLU_DISABLE -}" + , "{-# LANGUAGE CPP #-}" , "{-# LANGUAGE DeriveGeneric #-}" , "module Distribution.Simple.Build.PathsModule.Z (render, Z(..)) where" , "import Distribution.ZinzaPrelude" diff --git a/cabal-install-solver/cabal-install-solver.cabal b/cabal-install-solver/cabal-install-solver.cabal index 97caf91a28f..e6d91931757 100644 --- a/cabal-install-solver/cabal-install-solver.cabal +++ b/cabal-install-solver/cabal-install-solver.cabal @@ -117,14 +117,9 @@ library , text (>= 1.2.3.0 && < 1.3) || (>= 2.0 && < 2.2) if flag(mhs) - -- MicroHs build: use -mhs package variants. Binary instances come via - -- Distribution.Compat.Binary in Cabal-syntax (which already swaps to - -- binary-mhs); list binary-mhs here for completeness. build-depends: - , array-mhs >=0.5.8 && <0.6 - , binary-mhs >=0.8.1 && <0.9 - , pretty-mhs >=1.1.3.6 && <1.2 - , uri-mhs >=0.1 && <0.2 + , array-mhs >=0.5.8 && <0.6 + , mhs-compat-shims ^>= 0.1 else build-depends: , array >=0.4 && <0.6 diff --git a/cabal-install/cabal-install.cabal b/cabal-install/cabal-install.cabal index a6d9f23a780..839ffc0aa08 100644 --- a/cabal-install/cabal-install.cabal +++ b/cabal-install/cabal-install.cabal @@ -18,8 +18,6 @@ Category: Distribution Build-type: Simple Extra-Source-Files: bash-completion/cabal - cbits/mhs_sha256.c - cbits/mhs_sha256.h extra-doc-files: README.md ChangeLog.md @@ -130,7 +128,6 @@ library Distribution.Client.CmdTarget Distribution.Client.CmdTest Distribution.Client.CmdUpdate - Distribution.Client.Compat.Base16 Distribution.Client.CmdGenBounds Distribution.Client.Compat.Orphans Distribution.Client.Compat.Prelude @@ -265,18 +262,10 @@ library , parsec >= 3.1.13.0 && < 3.2 if flag(mhs) - -- MicroHs build: -mhs package variants (same APIs, ported to mhs). build-depends: - , array-mhs >= 0.5.8 && < 0.6 - , binary-mhs >= 0.8.1 && < 0.9 - , pretty-mhs >= 1.1.3.6 && < 1.2 - , random-mhs >= 1.2 && < 1.4 - , uri-mhs >= 0.1 && < 0.2 - -- SHA256 helper (CommonCrypto on Apple, OpenSSL elsewhere). - c-sources: cbits/mhs_sha256.c - include-dirs: cbits - if !os(darwin) - extra-libraries: crypto + , array-mhs >= 0.5.8 && < 0.6 + , mhs-compat-shims ^>= 0.1 + , random-mhs >= 1.2 && < 1.4 else build-depends: , array >= 0.4 && < 0.6 diff --git a/cabal-install/parser-tests/Tests/ParserTests.hs b/cabal-install/parser-tests/Tests/ParserTests.hs index f869529e58b..9bf01c30a95 100644 --- a/cabal-install/parser-tests/Tests/ParserTests.hs +++ b/cabal-install/parser-tests/Tests/ParserTests.hs @@ -28,6 +28,7 @@ import Distribution.Client.Types.Repo (LocalRepo (..), RemoteRepo (..), asPosixP import Distribution.Client.Types.RepoName (RepoName (..)) import Distribution.Client.Types.SourceRepo import Distribution.Client.Types.WriteGhcEnvironmentFilesPolicy (WriteGhcEnvironmentFilesPolicy (..)) +import Distribution.Compat.Directory (canonicalizePath, doesFileExist) import Distribution.Compat.Prelude import Distribution.Compiler (CompilerFlavor (..)) import Distribution.Parsec (simpleParsec) @@ -62,7 +63,6 @@ import Distribution.Utils.NubList import Distribution.Verbosity import GHC.Stack (HasCallStack) import Network.URI (parseURI) -import Distribution.Compat.Directory (canonicalizePath, doesFileExist) import System.FilePath (()) import Prelude () diff --git a/cabal-install/src/Distribution/Client/BuildReports/Anonymous.hs b/cabal-install/src/Distribution/Client/BuildReports/Anonymous.hs index 9fe49e4c6cf..5d8c228210e 100644 --- a/cabal-install/src/Distribution/Client/BuildReports/Anonymous.hs +++ b/cabal-install/src/Distribution/Client/BuildReports/Anonymous.hs @@ -1,5 +1,5 @@ -{-# LANGUAGE CPP #-} {-# LANGUAGE ApplicativeDo #-} +{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} diff --git a/cabal-install/src/Distribution/Client/Check.hs b/cabal-install/src/Distribution/Client/Check.hs index 4c4b54693f6..99d7afab3f2 100644 --- a/cabal-install/src/Distribution/Client/Check.hs +++ b/cabal-install/src/Distribution/Client/Check.hs @@ -26,8 +26,8 @@ import Distribution.Parsec import Distribution.Simple.Utils (defaultPackageDescCwd, dieWithException, notice, warn, warnError) import Distribution.Utils.Path (getSymbolicPath) -import qualified Data.Foldable as CM import qualified Data.ByteString as BS +import qualified Data.Foldable as CM import qualified Data.Function as F import qualified Data.List as L import qualified Data.List.NonEmpty as NE diff --git a/cabal-install/src/Distribution/Client/CmdClean.hs b/cabal-install/src/Distribution/Client/CmdClean.hs index ef8c6f9f3d9..5ff92752a59 100644 --- a/cabal-install/src/Distribution/Client/CmdClean.hs +++ b/cabal-install/src/Distribution/Client/CmdClean.hs @@ -1,6 +1,6 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PatternSynonyms #-} -{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} module Distribution.Client.CmdClean (cleanCommand, cleanAction) where @@ -78,8 +78,8 @@ import Control.Exception ( throw ) import Data.Foldable (forM_) -import Data.Traversable (forM) import qualified Data.Set as Set +import Data.Traversable (forM) #ifndef __MHS__ import qualified GHC.IO.Exception as GHC #endif @@ -93,6 +93,7 @@ import Distribution.Compat.Directory import System.FilePath ( () ) +{- FOURMOLU_DISABLE -} import System.IO.Error ( #ifndef __MHS__ @@ -100,6 +101,7 @@ import System.IO.Error #endif isPermissionError ) +{- FOURMOLU_ENABLE -} import qualified Distribution.Compat.Process as Process data CleanFlags = CleanFlags @@ -155,6 +157,7 @@ cleanOptions showOrParseArgs = falseArg ] +{- FOURMOLU_DISABLE -} cleanAction :: (ProjectFlags, CleanFlags) -> [String] -> GlobalFlags -> IO () cleanAction (ProjectFlags{..}, CleanFlags{..}) extraArgs _ = do let verbosity = mkVerbosity defaultVerbosityHandles $ fromFlagOrDefault normal cleanVerbosity @@ -229,6 +232,7 @@ cleanAction (ProjectFlags{..}, CleanFlags{..}) extraArgs _ = do when (not exists || script `Set.member` toClean) $ do info verbosity ("Deleting cache (" ++ cache ++ ") for script (" ++ script ++ ")") removePathForcibly cache +{- FOURMOLU_ENABLE -} removeEnvFiles :: FilePath -> IO () removeEnvFiles dir = diff --git a/cabal-install/src/Distribution/Client/CmdInstall.hs b/cabal-install/src/Distribution/Client/CmdInstall.hs index 8ef9374f094..dd559b28ebc 100644 --- a/cabal-install/src/Distribution/Client/CmdInstall.hs +++ b/cabal-install/src/Distribution/Client/CmdInstall.hs @@ -227,10 +227,6 @@ import Data.Ord ) import qualified Data.Set as S import Distribution.Client.Errors -import Distribution.Utils.NubList - ( fromNubList - ) -import Network.URI (URI) import Distribution.Compat.Directory ( copyFile , createDirectoryIfMissing @@ -241,6 +237,10 @@ import Distribution.Compat.Directory , makeAbsolute , removePathForcibly ) +import Distribution.Utils.NubList + ( fromNubList + ) +import Network.URI (URI) import System.FilePath ( takeBaseName , takeDirectory diff --git a/cabal-install/src/Distribution/Client/CmdRepl.hs b/cabal-install/src/Distribution/Client/CmdRepl.hs index 8c6fd007b01..ae94c771144 100644 --- a/cabal-install/src/Distribution/Client/CmdRepl.hs +++ b/cabal-install/src/Distribution/Client/CmdRepl.hs @@ -187,6 +187,12 @@ import Distribution.Client.ReplFlags ) import Distribution.Client.Toolchain (Machine (..)) import Distribution.Compat.Binary (decode) +import Distribution.Compat.Directory + ( doesFileExist + , getCurrentDirectory + , listDirectory + , makeAbsolute + ) import qualified Distribution.Compat.Graph as Graph import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.Simple.Flag (flagToMaybe, fromFlagOrDefault, pattern Flag) @@ -194,12 +200,6 @@ import Distribution.Simple.Program.Builtin (ghcProgram) import Distribution.Simple.Program.Db (requireProgram) import Distribution.Simple.Program.Types import Distribution.Types.PackageName.Magic (fakePackageId) -import Distribution.Compat.Directory - ( doesFileExist - , getCurrentDirectory - , listDirectory - , makeAbsolute - ) import System.FilePath ( searchPathSeparator , splitSearchPath diff --git a/cabal-install/src/Distribution/Client/CmdUpdate.hs b/cabal-install/src/Distribution/Client/CmdUpdate.hs index 2390266eb9f..65b84a8a389 100644 --- a/cabal-install/src/Distribution/Client/CmdUpdate.hs +++ b/cabal-install/src/Distribution/Client/CmdUpdate.hs @@ -87,8 +87,8 @@ import qualified Distribution.Compat.CharParsing as P import qualified Text.PrettyPrint as Disp import Data.Time (getCurrentTime) -import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.Client.GZipUtils (maybeDecompress) +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.Simple.Command ( CommandUI (..) , usageAlternatives @@ -247,6 +247,7 @@ updateRepo verbosity repoCtxt (repo, indexState) = do writeFileAtomic (dropExtension indexPath) . maybeDecompress =<< readFileLBS indexPath updateRepoIndexCache verbosity (RepoIndex repoCtxt repo) +{- FOURMOLU_DISABLE -} RepoSecure{} -> #ifdef __MHS__ -- Secure repositories are not supported in this build. @@ -306,3 +307,4 @@ updateRepo verbosity repoCtxt (repo, indexState) = do ++ prettyShow (UpdateRequest rname (IndexStateTime current_ts)) ++ "'\n" #endif +{- FOURMOLU_ENABLE -} diff --git a/cabal-install/src/Distribution/Client/Config.hs b/cabal-install/src/Distribution/Client/Config.hs index 0af2f2d4f2f..419d8f9cec1 100644 --- a/cabal-install/src/Distribution/Client/Config.hs +++ b/cabal-install/src/Distribution/Client/Config.hs @@ -129,6 +129,16 @@ import Distribution.Client.Version ( cabalInstallVersion ) import qualified Distribution.Compat.CharParsing as P +import Distribution.Compat.Directory + ( XdgDirectory (XdgCache, XdgConfig, XdgState) + , createDirectoryIfMissing + , doesDirectoryExist + , doesFileExist + , getAppUserDataDirectory + , getHomeDirectory + , getXdgDirectory + , renameFile + ) import Distribution.Compiler ( CompilerFlavor (..) , defaultCompilerFlavor @@ -219,16 +229,6 @@ import Network.URI , URIAuth (..) , parseURI ) -import Distribution.Compat.Directory - ( XdgDirectory (XdgCache, XdgConfig, XdgState) - , createDirectoryIfMissing - , doesDirectoryExist - , doesFileExist - , getAppUserDataDirectory - , getHomeDirectory - , getXdgDirectory - , renameFile - ) import System.FilePath ( normalise , takeDirectory diff --git a/cabal-install/src/Distribution/Client/Dependency.hs b/cabal-install/src/Distribution/Client/Dependency.hs index 4eb6912771f..e0a6cc5b644 100644 --- a/cabal-install/src/Distribution/Client/Dependency.hs +++ b/cabal-install/src/Distribution/Client/Dependency.hs @@ -1,6 +1,6 @@ ----------------------------------------------------------------------------- - {-# LANGUAGE CPP #-} + -- | -- Module : Distribution.Client.Dependency -- Copyright : (c) David Himmelstrup 2005, diff --git a/cabal-install/src/Distribution/Client/Errors.hs b/cabal-install/src/Distribution/Client/Errors.hs index 382e91e93ed..48b26f70d79 100644 --- a/cabal-install/src/Distribution/Client/Errors.hs +++ b/cabal-install/src/Distribution/Client/Errors.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- Module : Distribution.Client.Errors -- Copyright : Suganya Arun -- License : BSD3 @@ -25,7 +26,6 @@ import Distribution.Client.IndexUtils.Timestamp import qualified Distribution.Client.Types.Repo as Repo import qualified Distribution.Client.Types.RepoName as RepoName import Distribution.Compat.Prelude -import Prelude () import Distribution.Deprecated.ParseUtils (PWarning, showPWarning) import Distribution.Package import Distribution.Pretty @@ -34,6 +34,7 @@ import Distribution.Simple.Utils import Network.URI import Text.PrettyPrint hiding (render, (<>)) import qualified Text.PrettyPrint as PP +import Prelude () import Distribution.Client.Errors.Parser diff --git a/cabal-install/src/Distribution/Client/FetchUtils.hs b/cabal-install/src/Distribution/Client/FetchUtils.hs index 979bfa2893c..3a8e351fafd 100644 --- a/cabal-install/src/Distribution/Client/FetchUtils.hs +++ b/cabal-install/src/Distribution/Client/FetchUtils.hs @@ -325,6 +325,7 @@ fetchRepoTarball verbosity' repoCtxt repo pkgid = do createDirectoryIfMissing True dir _ <- downloadURI transport verbosity uri path return path +{- FOURMOLU_DISABLE -} RepoSecure{} -> #ifdef __MHS__ -- Secure repositories are not supported in this build. @@ -340,6 +341,7 @@ fetchRepoTarball verbosity' repoCtxt repo pkgid = do Sec.downloadPackage' rep pkgid path return path #endif +{- FOURMOLU_ENABLE -} -- | Downloads an index file to [config-dir/packages/serv-id] without -- hackage-security. You probably don't want to call this directly; diff --git a/cabal-install/src/Distribution/Client/FileMonitor.hs b/cabal-install/src/Distribution/Client/FileMonitor.hs index a5b2157bc3e..d692581db98 100644 --- a/cabal-install/src/Distribution/Client/FileMonitor.hs +++ b/cabal-install/src/Distribution/Client/FileMonitor.hs @@ -33,7 +33,6 @@ import qualified Data.Map.Strict as Map import Control.Exception import Control.Monad hiding (forM_, mapM, mapM_, sequence, sequence_) -import Data.Foldable (forM_, mapM_) import Control.Monad.Except ( ExceptT , runExceptT @@ -43,6 +42,7 @@ import Control.Monad.Except import Control.Monad.State (StateT, mapStateT) import qualified Control.Monad.State as State import Control.Monad.Trans (MonadIO, liftIO) +import Data.Foldable (forM_, mapM_) import Distribution.Client.Glob import Distribution.Client.HashValue diff --git a/cabal-install/src/Distribution/Client/GZipUtils.hs b/cabal-install/src/Distribution/Client/GZipUtils.hs index 112ae24c0c8..b26f8b3b9c6 100644 --- a/cabal-install/src/Distribution/Client/GZipUtils.hs +++ b/cabal-install/src/Distribution/Client/GZipUtils.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- | -- Module : Distribution.Client.GZipUtils -- Copyright : (c) Dmitry Astapov 2010 @@ -10,12 +11,14 @@ -- -- Provides a convenience functions for working with files that may or may not -- be zipped. +{- FOURMOLU_DISABLE -} module Distribution.Client.GZipUtils ( maybeDecompress #ifdef __MHS__ , gzipCompress #endif ) where +{- FOURMOLU_ENABLE -} import Distribution.Client.Compat.Prelude import Prelude () diff --git a/cabal-install/src/Distribution/Client/Get.hs b/cabal-install/src/Distribution/Client/Get.hs index 43b460f0c3b..bea10537668 100644 --- a/cabal-install/src/Distribution/Client/Get.hs +++ b/cabal-install/src/Distribution/Client/Get.hs @@ -75,15 +75,15 @@ import Data.Foldable (mapM_) import qualified Data.Map as Map import qualified Data.Text as Text import Distribution.Client.Errors -import Distribution.Utils.NubList - ( fromNubList - ) import Distribution.Compat.Directory ( createDirectoryIfMissing , doesDirectoryExist , doesFileExist , listDirectory ) +import Distribution.Utils.NubList + ( fromNubList + ) import System.FilePath ( addTrailingPathSeparator , (<.>) diff --git a/cabal-install/src/Distribution/Client/GlobalFlags.hs b/cabal-install/src/Distribution/Client/GlobalFlags.hs index af3f0790c56..ded5405327c 100644 --- a/cabal-install/src/Distribution/Client/GlobalFlags.hs +++ b/cabal-install/src/Distribution/Client/GlobalFlags.hs @@ -130,6 +130,7 @@ defaultGlobalFlags = -- ------------------------------------------------------------ -- | Access to repositories +{- FOURMOLU_DISABLE -} data RepoContext = RepoContext { repoContextRepos :: [Repo] -- ^ All user-specified repositories @@ -164,6 +165,7 @@ data RepoContext = RepoContext , repoContextIgnoreExpiry :: Bool -- ^ Should we ignore expiry times (when checking security)? } +{- FOURMOLU_ENABLE -} #ifdef __MHS__ -- | A secure repository handle. @@ -192,6 +194,7 @@ withRepoContext verbosity globalFlags = (flagToMaybe (globalIgnoreExpiry globalFlags)) (fromNubList (globalProgPathExtra globalFlags)) +{- FOURMOLU_DISABLE -} withRepoContext' :: Verbosity -> [RemoteRepo] @@ -287,6 +290,7 @@ withRepoContext' Just (SecureRepo secureRepo) -> callback secureRepo Nothing -> throwIO $ userError "repoContextWithSecureRepo: unknown repo" #endif +{- FOURMOLU_ENABLE -} #ifndef __MHS__ -- | Initialize the provided secure repositories diff --git a/cabal-install/src/Distribution/Client/Haddock.hs b/cabal-install/src/Distribution/Client/Haddock.hs index 1052f9aafa0..f8854f7d2fe 100644 --- a/cabal-install/src/Distribution/Client/Haddock.hs +++ b/cabal-install/src/Distribution/Client/Haddock.hs @@ -20,6 +20,7 @@ import Distribution.Client.Compat.Prelude import Prelude () import Data.List (maximumBy) +import Distribution.Compat.Directory (createDirectoryIfMissing, renameFile) import Distribution.InstalledPackageInfo as InstalledPackageInfo ( InstalledPackageInfo (exposed) ) @@ -43,7 +44,6 @@ import Distribution.Simple.Utils , withTempDirectory ) import Distribution.Version (mkVersion, orLaterVersion) -import Distribution.Compat.Directory (createDirectoryIfMissing, renameFile) import System.FilePath (splitFileName, ()) regenerateHaddockIndex diff --git a/cabal-install/src/Distribution/Client/HttpUtils.hs b/cabal-install/src/Distribution/Client/HttpUtils.hs index b541cc7a22b..112a3b0f85d 100644 --- a/cabal-install/src/Distribution/Client/HttpUtils.hs +++ b/cabal-install/src/Distribution/Client/HttpUtils.hs @@ -1,5 +1,7 @@ {-# LANGUAGE CPP #-} + -- | Separate module for HTTP actions, using a proxy server if one exists. +{- FOURMOLU_DISABLE -} module Distribution.Client.HttpUtils ( DownloadResult (..) , configureTransport @@ -16,6 +18,7 @@ module Distribution.Client.HttpUtils , remoteRepoTryUpgradeToHttps , isOldHackageURI ) where +{- FOURMOLU_ENABLE -} #ifdef __MHS__ import Distribution.Client.Compat.Prelude @@ -253,9 +256,11 @@ downloadURI downloadURI _transport verbosity uri path | uriScheme uri == "file:" = do copyFileVerbose verbosity (uriPath uri) path return (FileDownloaded path) + -- Can we store the hash of the file so we can safely return path when the -- hash matches to avoid unnecessary computation? +{- FOURMOLU_DISABLE -} downloadURI transport verbosity uri path = do targetExists <- doesFileExist path @@ -352,6 +357,7 @@ downloadURI transport verbosity uri path = do str <- some P.hexDigit let bs = Base16.decode (BS8.pack str) either fail return bs +{- FOURMOLU_ENABLE -} ------------------------------------------------------------------------------ -- Utilities for repo url management @@ -488,6 +494,7 @@ noPostYet -> IO (Int, String) noPostYet verbosity _ _ _ = dieWithException verbosity NoPostYet +{- FOURMOLU_DISABLE -} supportedTransports :: [ ( String , Maybe Program @@ -523,7 +530,9 @@ supportedTransports = ) #endif ] +{- FOURMOLU_ENABLE -} +{- FOURMOLU_DISABLE -} configureTransport :: Verbosity -> [FilePath] -> Maybe String -> IO HttpTransport configureTransport verbosity extraPath (Just name) = -- the user specifically selected a transport by name so we'll try and @@ -574,6 +583,7 @@ configureTransport verbosity extraPath Nothing = do debug verbosity $ "Selected http transport implementation: " ++ name return transport{transportManuallySelected = False} +{- FOURMOLU_ENABLE -} ------------------------------------------------------------------------------ -- The HttpTransports based on external programs diff --git a/cabal-install/src/Distribution/Client/InLibrary.hs b/cabal-install/src/Distribution/Client/InLibrary.hs index 3f44475198e..14ae83eaad0 100644 --- a/cabal-install/src/Distribution/Client/InLibrary.hs +++ b/cabal-install/src/Distribution/Client/InLibrary.hs @@ -53,8 +53,8 @@ import Distribution.Verbosity , mkVerbosity ) -import Distribution.Types.HookedBuildInfo (emptyHookedBuildInfo) import Distribution.Compat.Directory (canonicalizePath) +import Distribution.Types.HookedBuildInfo (emptyHookedBuildInfo) -- Note [MHS support] -- ~~~~~~~~~~~~~~~~~~ @@ -372,6 +372,7 @@ bench -> LocalBuildInfo -> [String] -> IO () +{- FOURMOLU_DISABLE -} bench verb flags lbi args = #ifdef __MHS__ error "Distribution.Client.InLibrary.bench: in-library setup is not supported under MHS" @@ -394,3 +395,4 @@ register flags lbi _args = Cabal.register pkgDescr lbi flags where pkgDescr = localPkgDescr lbi #endif +{- FOURMOLU_ENABLE -} diff --git a/cabal-install/src/Distribution/Client/IndexUtils.hs b/cabal-install/src/Distribution/Client/IndexUtils.hs index 41448553edd..295263ebd08 100644 --- a/cabal-install/src/Distribution/Client/IndexUtils.hs +++ b/cabal-install/src/Distribution/Client/IndexUtils.hs @@ -876,6 +876,7 @@ withIndexEntries -> ([IndexCacheEntry] -> IO a) -> ([NoIndexCacheEntry] -> IO a) -> IO a +{- FOURMOLU_DISABLE -} withIndexEntries _ (RepoIndex repoCtxt repo@RepoSecure{}) callback _ = #ifdef __MHS__ -- Secure repositories are not supported in this build. @@ -1045,6 +1046,7 @@ withIndexEntries verbosity (RepoIndex _repoCtxt (RepoLocalNoIndex (LocalRepo nam Right genericPackageDescription -> pure $ Just $ CacheGPD genericPackageDescription bytes _ -> pure Nothing +{- FOURMOLU_ENABLE -} withIndexEntries verbosity index callback _ = do -- non-secure repositories withBinaryFile (indexFile index) ReadMode $ \h -> do @@ -1507,24 +1509,6 @@ read00IndexCacheEntry = \line -> | BSS.null remainder -> Just (fromIntegral blockno) _ -> Nothing -#ifdef __MHS__ - bssReadInt :: BSS.ByteString -> Maybe (Int, BSS.ByteString) - bssReadInt bs = - case BSS.uncons bs of - Just ('-', bs') -> first negate <$> readUint bs' - Just ('+', bs') -> readUint bs' - _ -> readUint bs - where - readUint s = - let (digits, rest) = BSS.span isDigit s - in if BSS.null digits - then Nothing - else Just (foldl' (\acc c -> acc * 10 + (ord c - ord '0')) 0 (BSS.unpack digits), rest) -#else - bssReadInt :: BSS.ByteString -> Maybe (Int, BSS.ByteString) - bssReadInt = BSS.readInt -#endif - parseRefType str = case BSS.uncons str of Just (typeCode, remainder) @@ -1532,6 +1516,24 @@ read00IndexCacheEntry = \line -> Just (refTypeFromTypeCode typeCode) _ -> Nothing +#ifdef __MHS__ +bssReadInt :: BSS.ByteString -> Maybe (Int, BSS.ByteString) +bssReadInt bs = + case BSS.uncons bs of + Just ('-', bs') -> first negate <$> readUint bs' + Just ('+', bs') -> readUint bs' + _ -> readUint bs + where + readUint s = + let (digits, rest) = BSS.span isDigit s + in if BSS.null digits + then Nothing + else Just (foldl' (\acc c -> acc * 10 + (ord c - ord '0')) 0 (BSS.unpack digits), rest) +#else +bssReadInt :: BSS.ByteString -> Maybe (Int, BSS.ByteString) +bssReadInt = BSS.readInt +#endif + -- legacy 00-index.cache format show00IndexCache :: Cache -> String show00IndexCache Cache{..} = unlines $ map show00IndexCacheEntry cacheEntries diff --git a/cabal-install/src/Distribution/Client/IndexUtils/IndexState.hs b/cabal-install/src/Distribution/Client/IndexUtils/IndexState.hs index f663cbbe81e..2e4cd0a8204 100644 --- a/cabal-install/src/Distribution/Client/IndexUtils/IndexState.hs +++ b/cabal-install/src/Distribution/Client/IndexUtils/IndexState.hs @@ -16,9 +16,9 @@ module Distribution.Client.IndexUtils.IndexState ) where import Distribution.Client.Compat.Prelude -import Prelude () import Distribution.Client.IndexUtils.Timestamp (Timestamp) import Distribution.Client.Types.RepoName (RepoName (..)) +import Prelude () import Distribution.Parsec (parsecLeadingCommaNonEmpty) diff --git a/cabal-install/src/Distribution/Client/Init/Format.hs b/cabal-install/src/Distribution/Client/Init/Format.hs index 6eb05f4bf1e..3e632c561ea 100644 --- a/cabal-install/src/Distribution/Client/Init/Format.hs +++ b/cabal-install/src/Distribution/Client/Init/Format.hs @@ -41,9 +41,9 @@ import Distribution.Pretty import qualified Distribution.SPDX.License as SPDX import Distribution.Simple.Utils hiding (cabalVersion) import Distribution.Solver.Compat.Prelude hiding (empty) -import Prelude () import Distribution.Utils.Path import Text.PrettyPrint +import Prelude () -- | Construct a 'PrettyField' from a field that can be automatically -- converted to a 'Doc' via 'display'. diff --git a/cabal-install/src/Distribution/Client/Init/Prompt.hs b/cabal-install/src/Distribution/Client/Init/Prompt.hs index 5d6be7fd497..c673410c901 100644 --- a/cabal-install/src/Distribution/Client/Init/Prompt.hs +++ b/cabal-install/src/Distribution/Client/Init/Prompt.hs @@ -23,9 +23,9 @@ module Distribution.Client.Init.Prompt ) where import Distribution.Client.Compat.Prelude hiding (break, empty, getLine, putStr, putStrLn) -import Prelude () import Distribution.Client.Init.Types import qualified System.IO +import Prelude () -- | Create a prompt with optional default value that returns a -- String. diff --git a/cabal-install/src/Distribution/Client/Init/Types.hs b/cabal-install/src/Distribution/Client/Init/Types.hs index 0843e6643c0..a1b7acd86f9 100644 --- a/cabal-install/src/Distribution/Client/Init/Types.hs +++ b/cabal-install/src/Distribution/Client/Init/Types.hs @@ -83,11 +83,11 @@ import Distribution.Version import Language.Haskell.Extension (Extension, Language (..)) import qualified System.IO +import qualified Distribution.Compat.Directory as P import qualified Distribution.Compat.Environment as P +import qualified Distribution.Compat.Process as Process import Distribution.FieldGrammar.Newtypes (SpecLicense) -import qualified Distribution.Compat.Directory as P import System.FilePath -import qualified Distribution.Compat.Process as Process -- -------------------------------------------------------------------- -- -- Flags diff --git a/cabal-install/src/Distribution/Client/InstallPlan.hs b/cabal-install/src/Distribution/Client/InstallPlan.hs index fcfdbfc9075..9db648bc18c 100644 --- a/cabal-install/src/Distribution/Client/InstallPlan.hs +++ b/cabal-install/src/Distribution/Client/InstallPlan.hs @@ -335,12 +335,14 @@ showPlanGraph graph = renderStyle defaultStyle $ vcat (map dispPlanPackage graph) where +{- FOURMOLU_DISABLE -} dispPlanPackage (ShowPlanNode herald neighbours) = #ifdef __MHS__ sep [herald, nest 2 (vcat neighbours)] #else hang herald 2 (vcat neighbours) #endif +{- FOURMOLU_ENABLE -} -- | Generic way to show a 'GenericInstallPlan' which elicits quite a lot of information showInstallPlan_gen diff --git a/cabal-install/src/Distribution/Client/JobControl.hs b/cabal-install/src/Distribution/Client/JobControl.hs index 0786ed46ea3..dfea7a379b6 100644 --- a/cabal-install/src/Distribution/Client/JobControl.hs +++ b/cabal-install/src/Distribution/Client/JobControl.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- | -- Module : Distribution.Client.JobControl -- Copyright : (c) Duncan Coutts 2012 @@ -302,6 +303,7 @@ newJobControlFromParStrat -> Maybe Int -- ^ A cap on the number of jobs (e.g. to force a maximum of 2 concurrent downloads despite a -j8 parallel strategy) -> IO (JobControl IO a) +{- FOURMOLU_DISABLE -} newJobControlFromParStrat verbosity mcompiler parStrat numJobsCap = case parStrat of Serial -> newSerialJobControl NumJobs n -> newParallelJobControl (capJobs (fromMaybe numberOfProcessors n)) @@ -337,6 +339,7 @@ newJobControlFromParStrat verbosity mcompiler parStrat numJobsCap = case parStra #endif where capJobs n = min (fromMaybe maxBound numJobsCap) n +{- FOURMOLU_ENABLE -} -- | Check if the compiler's semaphore version is compatible with ours, -- per 'versionsAreCompatible'. A compiler that doesn't report a diff --git a/cabal-install/src/Distribution/Client/List.hs b/cabal-install/src/Distribution/Client/List.hs index dc510df952e..229248d9830 100644 --- a/cabal-install/src/Distribution/Client/List.hs +++ b/cabal-install/src/Distribution/Client/List.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- | -- Module : Distribution.Client.List -- Copyright : (c) David Himmelstrup 2005 @@ -39,6 +40,7 @@ import Distribution.Simple.PackageIndex (InstalledPackageIndex) import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex import Distribution.Simple.Program (ProgramDb) import Distribution.Simple.Setup (fromFlag, fromFlagOrDefault) +{- FOURMOLU_DISABLE -} import Distribution.Simple.Utils ( dieWithException , equating @@ -47,6 +49,7 @@ import Distribution.Simple.Utils #endif , notice ) +{- FOURMOLU_ENABLE -} import Distribution.Version ( Version , VersionRange @@ -97,12 +100,14 @@ import Control.Exception #ifndef __MHS__ import Data.Bits ((.|.)) #endif +{- FOURMOLU_DISABLE -} import Data.List ( maximumBy #ifdef __MHS__ , isInfixOf #endif ) +{- FOURMOLU_ENABLE -} import qualified Data.List as L import Data.List.NonEmpty (groupBy) import qualified Data.Map as Map @@ -153,6 +158,7 @@ getPkgList -> ListFlags -> [String] -> IO [PackageDisplayInfo] +{- FOURMOLU_DISABLE -} getPkgList verbosity packageDBs repoCtxt mcompprogdb listFlags pats = do installedPkgIndex <- for mcompprogdb $ \(comp, progdb) -> getInstalledPackages verbosity comp packageDBs progdb @@ -238,6 +244,7 @@ getPkgList verbosity packageDBs repoCtxt mcompprogdb listFlags pats = do , pkg <- search index (Regex.matchTest re) ] #endif +{- FOURMOLU_ENABLE -} -- | Show information about packages. list diff --git a/cabal-install/src/Distribution/Client/Main.hs b/cabal-install/src/Distribution/Client/Main.hs index f900152875e..77fae2d7deb 100644 --- a/cabal-install/src/Distribution/Client/Main.hs +++ b/cabal-install/src/Distribution/Client/Main.hs @@ -275,6 +275,7 @@ import Distribution.Compat.Directory ( doesFileExist , withCurrentDirectory ) +import Distribution.Compat.Process (createProcess, env, proc, waitForProcess) import System.Environment (getEnvironment, getExecutablePath, getProgName) import System.FilePath ( dropExtension @@ -290,7 +291,6 @@ import System.IO , stderr , stdout ) -import Distribution.Compat.Process (createProcess, env, proc, waitForProcess) -- | Entry point -- diff --git a/cabal-install/src/Distribution/Client/Manpage.hs b/cabal-install/src/Distribution/Client/Manpage.hs index 4a961259f53..7568bc66a62 100644 --- a/cabal-install/src/Distribution/Client/Manpage.hs +++ b/cabal-install/src/Distribution/Client/Manpage.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + -- | -- Module : Distribution.Client.Manpage -- Copyright : (c) Maciek Makowski 2015 @@ -27,6 +28,7 @@ import Distribution.Client.Init.Utils (trim) import Distribution.Client.ManpageFlags import Distribution.Client.Setup (globalCommand) import Distribution.Compat.Process (proc) +import qualified Distribution.Compat.Process as Process import Distribution.Simple.Command import Distribution.Simple.Flag (fromFlag, fromFlagOrDefault) import Distribution.Simple.Utils @@ -41,7 +43,6 @@ import Distribution.Simple.Utils import Distribution.Verbosity import System.Environment (lookupEnv) import System.IO (hClose, hPutStr) -import qualified Distribution.Compat.Process as Process data FileInfo = -- | path, description @@ -57,6 +58,7 @@ files = [ FileInfo "~/.config/cabal/config" "The defaults that can be overridden with command-line options." ] +{- FOURMOLU_DISABLE -} manpageCmd :: String -> [CommandSpec a] -> ManpageFlags -> IO () manpageCmd pname commands flags | fromFlagOrDefault False (manpageRaw flags) = @@ -121,6 +123,7 @@ manpageCmd pname commands flags mkVerbosity defaultVerbosityHandles $ fromFlag $ manpageVerbosity flags +{- FOURMOLU_ENABLE -} -- | Produces a manual page with @troff@ markup. manpage :: String -> [CommandSpec a] -> String diff --git a/cabal-install/src/Distribution/Client/PackageHash.hs b/cabal-install/src/Distribution/Client/PackageHash.hs index 0eadc0d21c0..f9cec43abd8 100644 --- a/cabal-install/src/Distribution/Client/PackageHash.hs +++ b/cabal-install/src/Distribution/Client/PackageHash.hs @@ -139,7 +139,6 @@ hashedInstalledPackageIdShort pkghashinputs@PackageHashInputs{pkgHashPkgId} = | length s <= n = s | otherwise = take (n - 1) s ++ "_" - -- | All the information that contributes to a package's hash, and thus its -- 'InstalledPackageId'. data PackageHashInputs = PackageHashInputs diff --git a/cabal-install/src/Distribution/Client/ProjectBuilding.hs b/cabal-install/src/Distribution/Client/ProjectBuilding.hs index cdc24cdcbf7..f4a6fff896e 100644 --- a/cabal-install/src/Distribution/Client/ProjectBuilding.hs +++ b/cabal-install/src/Distribution/Client/ProjectBuilding.hs @@ -93,8 +93,8 @@ import Control.Concurrent.STM (TVar, newTVarIO) import Control.Exception (handle, try) import Data.Either (isLeft) import qualified Distribution.Client.IndexUtils as IndexUtils -import Distribution.Simple.PackageIndex (InstalledPackageIndex) import Distribution.Compat.Directory (doesDirectoryExist, doesFileExist, renameDirectory) +import Distribution.Simple.PackageIndex (InstalledPackageIndex) import System.FilePath (makeRelative, normalise, takeDirectory, takeFileName, (<.>), ()) #ifdef __MHS__ type SemaphoreIdentifier = String diff --git a/cabal-install/src/Distribution/Client/ProjectConfig.hs b/cabal-install/src/Distribution/Client/ProjectConfig.hs index d1f5226df50..9e6eb4be9da 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig.hs @@ -240,12 +240,6 @@ import qualified Data.Set as Set import qualified Data.Text as Text import qualified Data.Text.Encoding as Text -import Network.URI - ( URI (..) - , URIAuth (..) - , parseAbsoluteURI - , uriToString - ) import Distribution.Compat.Directory ( canonicalizePath , doesDirectoryExist @@ -257,6 +251,12 @@ import Distribution.Compat.Directory , pathIsSymbolicLink ) import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS) +import Network.URI + ( URI (..) + , URIAuth (..) + , parseAbsoluteURI + , uriToString + ) import System.FilePath hiding (combine) import System.IO ( IOMode (ReadMode) diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/FieldGrammar.hs b/cabal-install/src/Distribution/Client/ProjectConfig/FieldGrammar.hs index 6af173e8703..06e112bc8ee 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/FieldGrammar.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/FieldGrammar.hs @@ -16,7 +16,6 @@ import qualified Distribution.Client.ProjectConfig.Lens as L import Distribution.Client.ProjectConfig.Types (PackageConfig (..), ProjectConfig (..), ProjectConfigBuildOnly (..), ProjectConfigProvenance (..), ProjectConfigShared (..)) import Distribution.Client.Utils.Parsec import Distribution.Compat.Prelude -import Prelude () import Distribution.FieldGrammar import Distribution.Simple.Flag import Distribution.Simple.InstallDirs @@ -24,6 +23,7 @@ import Distribution.Solver.Types.ConstraintSource (ConstraintSource (..)) import Distribution.Solver.Types.ProjectConfigPath import Distribution.Solver.Types.Settings (PreferVersion (..)) import Distribution.Types.PackageVersionConstraint (PackageVersionConstraint (..)) +import Prelude () projectConfigFieldGrammar :: ProjectConfigPath -> [String] -> ParsecFieldGrammar' ProjectConfig projectConfigFieldGrammar source knownPrograms = do diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/Import.hs b/cabal-install/src/Distribution/Client/ProjectConfig/Import.hs index cd5fcd554d7..3ad8748fbe1 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/Import.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/Import.hs @@ -29,9 +29,9 @@ import Data.List ((\\)) import qualified Data.Map as Map import Distribution.Client.Compat.Prelude hiding (empty, (<>)) import qualified Distribution.Client.Compat.Prelude as Prelude ((<>)) -import Prelude () import Distribution.Client.HttpUtils import Distribution.Client.ProjectConfig.Types +import Distribution.Compat.Directory (createDirectoryIfMissing) import Distribution.Compat.Lens (view) import Distribution.PackageDescription (ConfVar (..)) import Distribution.Simple.Utils (debug, noticeDoc, ordNub) @@ -39,9 +39,9 @@ import Distribution.Solver.Types.ProjectConfigPath import Distribution.Types.CondTree (CondTree (..), traverseCondTreeA) import Distribution.Utils.String (trim) import Network.URI (URI (..), parseURI) -import Distribution.Compat.Directory (createDirectoryIfMissing) import System.FilePath (isAbsolute, isPathSeparator, makeValid, ()) import Text.PrettyPrint (Doc, empty, int, nest, semi, text, vcat, (<>)) +import Prelude () -- | ProjectConfigSkeleton is a tree of conditional blocks and imports wrapping -- a config. It can be finalized by providing the conditional resolution info diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/Legacy.hs b/cabal-install/src/Distribution/Client/ProjectConfig/Legacy.hs index bb2f7cd4441..4b09654210e 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/Legacy.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/Legacy.hs @@ -203,8 +203,8 @@ import qualified Data.Map as Map import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text -import Network.URI (URI (..), nullURIAuth) import Distribution.Compat.Directory (makeAbsolute) +import Network.URI (URI (..), nullURIAuth) import System.FilePath (splitFileName) import Text.PrettyPrint ( Doc diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/Lens.hs b/cabal-install/src/Distribution/Client/ProjectConfig/Lens.hs index 5f6e1747c7b..a46083f2eb7 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/Lens.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/Lens.hs @@ -19,7 +19,6 @@ import Distribution.Client.Types.SourceRepo (SourceRepoList) import Distribution.Client.Types.WriteGhcEnvironmentFilesPolicy (WriteGhcEnvironmentFilesPolicy) import Distribution.Compat.Lens import Distribution.Compat.Prelude -import Prelude () import Distribution.Compiler (CompilerFlavor (..)) import Distribution.Package ( PackageName @@ -67,6 +66,7 @@ import Distribution.Utils.NubList ( NubList ) import Distribution.Verbosity +import Prelude () projectPackages :: Lens' ProjectConfig [Text] projectPackages f s = fmap (\x -> s{T.projectPackages = x}) (f (T.projectPackages s)) diff --git a/cabal-install/src/Distribution/Client/ProjectConfig/Parsec.hs b/cabal-install/src/Distribution/Client/ProjectConfig/Parsec.hs index 88e36e40537..e51d3689697 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig/Parsec.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig/Parsec.hs @@ -59,8 +59,8 @@ import qualified Data.Map.Strict as Map import qualified Data.Set as Set import Distribution.Client.Errors.Parser (ProjectFileSource (..)) import qualified Distribution.Compat.CharParsing as P -import Network.URI (URI, uriFragment, uriPath, uriScheme) import Distribution.Compat.Directory (makeAbsolute) +import Network.URI (URI, uriFragment, uriPath, uriScheme) import System.FilePath (splitFileName) import qualified Text.Parsec import Text.PrettyPrint (render) diff --git a/cabal-install/src/Distribution/Client/ProjectPlanning.hs b/cabal-install/src/Distribution/Client/ProjectPlanning.hs index 5e9379a63f7..31972d9ac8c 100644 --- a/cabal-install/src/Distribution/Client/ProjectPlanning.hs +++ b/cabal-install/src/Distribution/Client/ProjectPlanning.hs @@ -106,6 +106,7 @@ module Distribution.Client.ProjectPlanning ) where import Distribution.Client.Compat.Prelude +{- FOURMOLU_DISABLE -} import Text.PrettyPrint ( colon , comma @@ -121,6 +122,7 @@ import Text.PrettyPrint , ($$) , ($+$) ) +{- FOURMOLU_ENABLE -} import Distribution.Utils.LogProgress import Prelude () @@ -183,10 +185,10 @@ import qualified Hackage.Security.Client as Sec #endif import Distribution.Solver.Types.ConstraintSource +import Distribution.Solver.Types.GoalScope (Qualified (..), dispQPN) import Distribution.Solver.Types.InstSolverPackage import Distribution.Solver.Types.LabeledPackageConstraint import Distribution.Solver.Types.OptionalStanza -import Distribution.Solver.Types.GoalScope (Qualified (..), dispQPN) import Distribution.Solver.Types.PkgConfigDb import Distribution.Solver.Types.Settings import Distribution.Solver.Types.SolverId @@ -264,9 +266,9 @@ import qualified Data.Set as Set import qualified Data.Text as Text import Data.Traversable (mapAccumM) import Distribution.Client.Errors +import Distribution.Compat.Directory (getCurrentDirectory) import Distribution.Solver.Types.ProjectConfigPath import GHC.Stack (HasCallStack) -import Distribution.Compat.Directory (getCurrentDirectory) import System.FilePath import qualified Text.PrettyPrint as Disp @@ -1494,6 +1496,7 @@ getPackageSourceHashes -> (forall a. (RepoContext -> IO a) -> IO a) -> SolverInstallPlan -> Rebuild (Map PackageId PackageSourceHash) +{- FOURMOLU_DISABLE -} getPackageSourceHashes verbosity withRepoCtx solverPlan = do -- Determine if and where to get the package's source hash from. -- @@ -1663,6 +1666,7 @@ getPackageSourceHashes verbosity withRepoCtx solverPlan = do return $! hashesFromRepoMetadata <> hashesFromTarballFiles +{- FOURMOLU_ENABLE -} -- ------------------------------------------------------------ diff --git a/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs b/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs index 83f076d4d7b..b18e0d8ab45 100644 --- a/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs +++ b/cabal-install/src/Distribution/Client/Sandbox/PackageEnvironment.hs @@ -34,6 +34,7 @@ import Distribution.Client.Setup ( ConfigExFlags (..) ) import Distribution.Client.Targets (userConstraintPackageName) +import Distribution.Compat.Directory (doesFileExist) import Distribution.Deprecated.ParseUtils ( FieldDescr (..) , ParseResult (..) @@ -55,7 +56,6 @@ import Distribution.Simple.Setup ) import Distribution.Simple.Utils (debug, warn) import Distribution.Solver.Types.ConstraintSource -import Distribution.Compat.Directory (doesFileExist) import System.FilePath (()) import System.IO.Error (isDoesNotExistError) import Text.PrettyPrint (($+$)) diff --git a/cabal-install/src/Distribution/Client/ScriptUtils.hs b/cabal-install/src/Distribution/Client/ScriptUtils.hs index bc280926194..9a383846886 100644 --- a/cabal-install/src/Distribution/Client/ScriptUtils.hs +++ b/cabal-install/src/Distribution/Client/ScriptUtils.hs @@ -203,15 +203,15 @@ import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import Distribution.Client.Errors -import Distribution.Utils.Path - ( unsafeMakeSymbolicPath - ) import Distribution.Compat.Directory ( canonicalizePath , doesFileExist , getTemporaryDirectory , removePathForcibly ) +import Distribution.Utils.Path + ( unsafeMakeSymbolicPath + ) import System.FilePath ( makeRelative , normalise diff --git a/cabal-install/src/Distribution/Client/SourceFiles.hs b/cabal-install/src/Distribution/Client/SourceFiles.hs index 0e14702a789..8f00ee9ca8f 100644 --- a/cabal-install/src/Distribution/Client/SourceFiles.hs +++ b/cabal-install/src/Distribution/Client/SourceFiles.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + -- | Contains an @sdist@ like function which computes the source files -- that we should track to determine if a rebuild is necessary. -- Unlike @sdist@, we can operate directly on the true @@ -10,7 +12,6 @@ -- We can only use this code for non-Custom scripts; Custom scripts -- may have arbitrary extra dependencies (esp. new preprocessors) which -- we cannot "see" easily. -{-# LANGUAGE CPP #-} module Distribution.Client.SourceFiles (needElaboratedConfiguredPackage) where import Control.Monad ((>=>)) diff --git a/cabal-install/src/Distribution/Client/TargetSelector.hs b/cabal-install/src/Distribution/Client/TargetSelector.hs index 1a37947fea2..e725717290a 100644 --- a/cabal-install/src/Distribution/Client/TargetSelector.hs +++ b/cabal-install/src/Distribution/Client/TargetSelector.hs @@ -110,6 +110,12 @@ import Distribution.Client.Errors import Distribution.Client.Utils ( makeRelativeCanonical ) +import qualified Distribution.Compat.Directory as IO + ( canonicalizePath + , doesDirectoryExist + , doesFileExist + , getCurrentDirectory + ) import Distribution.Deprecated.ParseUtils ( readPToMaybe ) @@ -126,12 +132,6 @@ import Distribution.Simple.Utils import Distribution.Utils.Path ( getSymbolicPath ) -import qualified Distribution.Compat.Directory as IO - ( canonicalizePath - , doesDirectoryExist - , doesFileExist - , getCurrentDirectory - ) import System.FilePath ( dropExtension , dropTrailingPathSeparator diff --git a/cabal-install/src/Distribution/Client/Targets.hs b/cabal-install/src/Distribution/Client/Targets.hs index 1bf8fdeda34..300d93b478d 100644 --- a/cabal-install/src/Distribution/Client/Targets.hs +++ b/cabal-install/src/Distribution/Client/Targets.hs @@ -104,6 +104,11 @@ import qualified Data.Map as Map import Distribution.Client.Errors import qualified Distribution.Client.GZipUtils as GZipUtils import qualified Distribution.Compat.CharParsing as P +import Distribution.Compat.Directory + ( doesDirectoryExist + , doesFileExist + ) +import Distribution.Compat.Internal.LazyByteString (readFileLBS) import Distribution.Solver.Types.Machine (Machine (..)) import Distribution.Utils.Path (makeSymbolicPath) import Network.URI @@ -111,11 +116,6 @@ import Network.URI , URIAuth (..) , parseAbsoluteURI ) -import Distribution.Compat.Directory - ( doesDirectoryExist - , doesFileExist - ) -import Distribution.Compat.Internal.LazyByteString (readFileLBS) import System.FilePath ( dropExtension , splitPath diff --git a/cabal-install/src/Distribution/Client/Upload.hs b/cabal-install/src/Distribution/Client/Upload.hs index 0e63217a854..d34e2d4a0ce 100644 --- a/cabal-install/src/Distribution/Client/Upload.hs +++ b/cabal-install/src/Distribution/Client/Upload.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + module Distribution.Client.Upload (upload, uploadDoc, report) where import Distribution.Client.Compat.Prelude diff --git a/cabal-install/src/Distribution/Client/Utils.hs b/cabal-install/src/Distribution/Client/Utils.hs index cc92040245a..9d5b150f7bf 100644 --- a/cabal-install/src/Distribution/Client/Utils.hs +++ b/cabal-install/src/Distribution/Client/Utils.hs @@ -2,6 +2,7 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE PatternSynonyms #-} +{- FOURMOLU_DISABLE -} module Distribution.Client.Utils ( MergeResult (..) , mergeBy @@ -46,6 +47,7 @@ module Distribution.Client.Utils , getArgsWithResponseFiles #endif ) where +{- FOURMOLU_ENABLE -} import Distribution.Client.Compat.Prelude import Prelude () diff --git a/cabal-install/src/Distribution/Client/Utils/Newtypes.hs b/cabal-install/src/Distribution/Client/Utils/Newtypes.hs index 66669faa2a7..8adf0ef89f4 100644 --- a/cabal-install/src/Distribution/Client/Utils/Newtypes.hs +++ b/cabal-install/src/Distribution/Client/Utils/Newtypes.hs @@ -13,7 +13,6 @@ module Distribution.Client.Utils.Newtypes where import Distribution.Client.Compat.Prelude -import Prelude () import Distribution.Client.Targets (UserConstraint) import Distribution.Client.Types.AllowNewer (AllowNewer (..), AllowOlder (..)) import Distribution.Compat.CharParsing @@ -21,6 +20,7 @@ import Distribution.Parsec import Distribution.Simple.Compiler (PackageDBCWD, interpretPackageDB, readPackageDb) import Distribution.Solver.Types.ConstraintSource (ConstraintSource (..)) import Network.URI (URI, parseURI) +import Prelude () newtype PackageDBNT = PackageDBNT {getPackageDBNT :: Maybe PackageDBCWD} diff --git a/cabal-install/src/Distribution/Client/VCS.hs b/cabal-install/src/Distribution/Client/VCS.hs index 6138ac28d4b..bd876ffd0ef 100644 --- a/cabal-install/src/Distribution/Client/VCS.hs +++ b/cabal-install/src/Distribution/Client/VCS.hs @@ -95,6 +95,7 @@ import Distribution.Compat.Directory , doesFileExist , removePathForcibly ) +import qualified Distribution.Compat.Process as Process import System.FilePath ( takeDirectory , () @@ -103,7 +104,6 @@ import System.IO.Error ( isDoesNotExistError , isPermissionError ) -import qualified Distribution.Compat.Process as Process -- | A driver for a version control system, e.g. git, darcs etc. data VCS program = VCS diff --git a/cabal-install/src/Distribution/Deprecated/ReadP.hs b/cabal-install/src/Distribution/Deprecated/ReadP.hs index b832dd45803..e61c2698147 100644 --- a/cabal-install/src/Distribution/Deprecated/ReadP.hs +++ b/cabal-install/src/Distribution/Deprecated/ReadP.hs @@ -61,9 +61,9 @@ module Distribution.Deprecated.ReadP where import Distribution.Client.Compat.Prelude -import Prelude () import Distribution.ReadE (ReadE (..)) import qualified Text.ParserCombinators.ReadP as T +import Prelude () type Parser = T.ReadP diff --git a/cabal-install/tests/IntegrationTests2.hs b/cabal-install/tests/IntegrationTests2.hs index 680a6d5ecc7..9268083417d 100644 --- a/cabal-install/tests/IntegrationTests2.hs +++ b/cabal-install/tests/IntegrationTests2.hs @@ -76,11 +76,11 @@ import Control.Concurrent (threadDelay) import Control.Exception hiding (assert) import Control.Monad import Distribution.Compat.Directory +import Distribution.Compat.Process (callProcess) import System.Environment (setEnv) import System.FilePath import System.IO (hPutStrLn, stderr) import qualified System.Info -import Distribution.Compat.Process (callProcess) import Data.Tagged (Tagged (..)) import Test.Tasty diff --git a/cabal-install/tests/UnitTests/Distribution/Client/Configure.hs b/cabal-install/tests/UnitTests/Distribution/Client/Configure.hs index 8ebe76ec215..ef1c1b02f49 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/Configure.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/Configure.hs @@ -9,11 +9,11 @@ import Distribution.Client.NixStyleOptions import Distribution.Client.ProjectConfig.Types import Distribution.Client.ProjectFlags import Distribution.Client.Setup +import Distribution.Compat.Directory import Distribution.Simple import Distribution.Simple.Flag import Distribution.Simple.Utils (removeFileForcibly) import Distribution.Verbosity -import Distribution.Compat.Directory import System.FilePath import Test.Tasty import Test.Tasty.HUnit diff --git a/cabal-install/tests/UnitTests/Distribution/Client/GZipUtils.hs b/cabal-install/tests/UnitTests/Distribution/Client/GZipUtils.hs index 31a2456593d..ff9067919e6 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/GZipUtils.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/GZipUtils.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + module UnitTests.Distribution.Client.GZipUtils ( tests ) where diff --git a/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs b/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs index 7a414515730..c97af4c7926 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs @@ -13,8 +13,8 @@ import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import qualified Data.Text as Text -import Network.URI (URI) import Distribution.Compat.Directory (canonicalizePath, withCurrentDirectory) +import Network.URI (URI) import System.FilePath import System.IO.Unsafe (unsafePerformIO) diff --git a/cabal-install/tests/UnitTests/Distribution/Client/Tar.hs b/cabal-install/tests/UnitTests/Distribution/Client/Tar.hs index ca80afd5779..ee232ecdb4c 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/Tar.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/Tar.hs @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} + module UnitTests.Distribution.Client.Tar (tests) where #ifdef __MHS__ diff --git a/cabal-testsuite/src/Test/Cabal/Monad.hs b/cabal-testsuite/src/Test/Cabal/Monad.hs index ac74ed0c06e..c3c6661de54 100644 --- a/cabal-testsuite/src/Test/Cabal/Monad.hs +++ b/cabal-testsuite/src/Test/Cabal/Monad.hs @@ -115,18 +115,18 @@ import Control.Monad.IO.Class import Control.Monad.Trans.Reader import Data.ByteString.Char8 qualified as C import Data.List -import qualified Data.Map as Map +import Data.Map qualified as Map import Data.Maybe import Data.Monoid (mempty) +import Distribution.Compat.Directory +import Distribution.Compat.Process hiding (env) import Distribution.Simple.Utils hiding (info) import GHC.Stack import Options.Applicative -import Distribution.Compat.Directory import System.Exit import System.FilePath import System.IO import System.IO.Error (isDoesNotExistError) -import Distribution.Compat.Process hiding (env) import Test.Cabal.Run data CommonArgs = CommonArgs diff --git a/cabal-testsuite/src/Test/Cabal/Prelude.hs b/cabal-testsuite/src/Test/Cabal/Prelude.hs index 015d0baa74a..b72c4e3a903 100644 --- a/cabal-testsuite/src/Test/Cabal/Prelude.hs +++ b/cabal-testsuite/src/Test/Cabal/Prelude.hs @@ -99,8 +99,9 @@ import Data.ByteString.Lazy qualified as BSL import Data.Char qualified as Char import Data.List (isPrefixOf, stripPrefix) import Data.Maybe (fromMaybe, isJust, mapMaybe) -import Network.Wait (waitTcpVerbose) import Distribution.Compat.Directory +import Distribution.Compat.Process +import Network.Wait (waitTcpVerbose) import System.Environment import System.Exit (ExitCode (..)) import System.FilePath @@ -108,8 +109,7 @@ import System.FilePath.Glob qualified as Glob (compile, globDir1) import System.FilePath.Posix qualified as Posix import System.FilePath.Windows qualified as Windows import System.IO -import qualified System.OsRelease as OSR -import Distribution.Compat.Process +import System.OsRelease qualified as OSR #ifndef mingw32_HOST_OS import System.Posix.Resource diff --git a/cabal-testsuite/src/Test/Cabal/Run.hs b/cabal-testsuite/src/Test/Cabal/Run.hs index cf14a10807f..d105029b1ac 100644 --- a/cabal-testsuite/src/Test/Cabal/Run.hs +++ b/cabal-testsuite/src/Test/Cabal/Run.hs @@ -12,10 +12,10 @@ import Distribution.Simple.Program.Run import Control.Concurrent.Async import Distribution.Compat.Directory +import Distribution.Compat.Process import System.Exit import System.FilePath import System.IO -import Distribution.Compat.Process -- | The result of invoking the command line. data Result = Result diff --git a/cabal-testsuite/src/Test/Cabal/Server.hs b/cabal-testsuite/src/Test/Cabal/Server.hs index f35f62a81b2..d5fa3b50a67 100644 --- a/cabal-testsuite/src/Test/Cabal/Server.hs +++ b/cabal-testsuite/src/Test/Cabal/Server.hs @@ -27,11 +27,11 @@ import Control.Monad import Data.IORef import Data.List (intercalate, isPrefixOf) import Data.Maybe +import Distribution.Compat.Process import Distribution.Simple.Program import Foreign.C.Error (Errno (..), ePIPE) import System.Exit import System.IO -import Distribution.Compat.Process import Text.Read (readMaybe) import Prelude hiding (log) diff --git a/cabal-testsuite/src/Test/Cabal/Workdir.hs b/cabal-testsuite/src/Test/Cabal/Workdir.hs index b0a2f296d1a..a35bda70362 100644 --- a/cabal-testsuite/src/Test/Cabal/Workdir.hs +++ b/cabal-testsuite/src/Test/Cabal/Workdir.hs @@ -6,8 +6,8 @@ module Test.Cabal.Workdir where import Distribution.Simple.Configure import Distribution.Simple.Setup import Distribution.Utils.Path - ( Dist - , Dir + ( Dir + , Dist , FileOrDir (..) , Pkg , SymbolicPath diff --git a/cabal-validate/src/Cli.hs b/cabal-validate/src/Cli.hs index 7192d955750..fd0241869f5 100644 --- a/cabal-validate/src/Cli.hs +++ b/cabal-validate/src/Cli.hs @@ -21,6 +21,7 @@ import qualified Data.Text as T import qualified Data.Text.Lazy as T (toStrict) import qualified Data.Text.Lazy.Encoding as T (decodeUtf8) import Data.Version (Version, parseVersion) +import Distribution.Compat.Directory (getCurrentDirectory) import GHC.Conc (getNumCapabilities) import Options.Applicative ( FlagFields @@ -46,7 +47,6 @@ import Options.Applicative , value ) import qualified Options.Applicative as Opt -import Distribution.Compat.Directory (getCurrentDirectory) import System.Exit (exitSuccess) import System.Info (arch, os) import System.Process.Typed (proc, readProcessStdout_) diff --git a/cabal.mhs.project b/cabal.mhs.project index a9af5f0210b..a4f64cb4938 100644 --- a/cabal.mhs.project +++ b/cabal.mhs.project @@ -38,6 +38,7 @@ packages: , cabal-install , cabal-install-solver , hooks-exe + , mhs-compat-shims -- Don't include tests or benchmarks for the minimal-toolchain build tests: False diff --git a/changelog.d/copyfile-cloexec.md b/changelog.d/copyfile-cloexec.md index a5b6e3e2f64..e5293475583 100644 --- a/changelog.d/copyfile-cloexec.md +++ b/changelog.d/copyfile-cloexec.md @@ -1,6 +1,7 @@ --- synopsis: Fix intermittent failure to run a just-installed build tool packages: [Cabal] +prs: 0 --- During a parallel build, a process started while `copyFile` was running could diff --git a/changelog.d/qualified-instances.md b/changelog.d/qualified-instances.md index c3846ae074e..8b4d6213831 100644 --- a/changelog.d/qualified-instances.md +++ b/changelog.d/qualified-instances.md @@ -1,6 +1,7 @@ --- synopsis: "Let build tools and setup scripts have their own instance of a package version" packages: [cabal-install-solver, cabal-install] +prs: 0 --- A build tool (`build-tool-depends`) and a setup script (`setup-depends`) are diff --git a/changelog.d/store-per-stage.md b/changelog.d/store-per-stage.md index 13837503afc..313095face3 100644 --- a/changelog.d/store-per-stage.md +++ b/changelog.d/store-per-stage.md @@ -1,7 +1,7 @@ --- synopsis: Lay out the store by machine and toolchain packages: [cabal-install] -prs: +prs: 0 significance: significant --- diff --git a/changelog.d/wired-in-local-targets.md b/changelog.d/wired-in-local-targets.md index d4f35c3309c..e73b59173ef 100644 --- a/changelog.d/wired-in-local-targets.md +++ b/changelog.d/wired-in-local-targets.md @@ -1,6 +1,7 @@ --- synopsis: Let `--allow-boot-library-installs` rebuild a wired-in package the project provides packages: [cabal-install] +prs: 0 --- With a compiler that reports wired-in unit ids (GHC 9.14 and later), `ghc` and diff --git a/mhs-compat-shims/ChangeLog.md b/mhs-compat-shims/ChangeLog.md new file mode 100644 index 00000000000..9fcd76a6c02 --- /dev/null +++ b/mhs-compat-shims/ChangeLog.md @@ -0,0 +1,7 @@ +# ChangeLog for mhs-compat-shims + +## 0.1.0.0 + +- Initial release: MicroHs compatibility shims for Cabal and + cabal-install, extracted from `Cabal-syntax`, `Cabal`, + `cabal-install`, and `bootstrap/mhs/shims/`. diff --git a/mhs-compat-shims/LICENSE b/mhs-compat-shims/LICENSE new file mode 100644 index 00000000000..3fb6214dad1 --- /dev/null +++ b/mhs-compat-shims/LICENSE @@ -0,0 +1,34 @@ +Copyright (c) 2003-2026, Cabal Development Team. +See the AUTHORS file for the full list of copyright holders. + +See */LICENSE for the copyright holders of the subcomponents. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of Isaac Jones nor the names of other + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/mhs-compat-shims/README.md b/mhs-compat-shims/README.md new file mode 100644 index 00000000000..54d885491c9 --- /dev/null +++ b/mhs-compat-shims/README.md @@ -0,0 +1,26 @@ +The `mhs-compat-shims` package +========================== + +See the [Cabal web site] for more information. + +The `mhs-compat-shims` package provides lightweight pure-Haskell and +POSIX C compatibility shims used when building `Cabal`, +`cabal-install-solver`, and `cabal-install` with MicroHs (mhs). + +It collects the `Data.Binary`, `Text.PrettyPrint`, `Network.URI`, and +text-encoding shims (previously under `bootstrap/mhs/shims/`), the +`Distribution.Compat` MHS helpers (`MhsInstances`, `MhsPosix`, +`MhsProcess`), the `Distribution.Client.Compat.Base16` shim, and the +small C helpers in `cbits/` (`mhs_posix`, `mhs_spawn`, `mhs_handle`, +`mhs_sha256`). + +More information +================ + +Please see the [Cabal web site] for the [user guide] and [API +documentation]. There is additional information available on the +[development wiki]. + +[user guide]: http://www.haskell.org/cabal/users-guide +[API documentation]: http://www.haskell.org/cabal/release/cabal-latest/doc/API/Cabal/Distribution-Simple.html +[development wiki]: https://github.com/haskell/cabal/wiki diff --git a/Cabal/cbits/mhs_handle.c b/mhs-compat-shims/cbits/mhs_handle.c similarity index 100% rename from Cabal/cbits/mhs_handle.c rename to mhs-compat-shims/cbits/mhs_handle.c diff --git a/Cabal/cbits/mhs_handle.h b/mhs-compat-shims/cbits/mhs_handle.h similarity index 100% rename from Cabal/cbits/mhs_handle.h rename to mhs-compat-shims/cbits/mhs_handle.h diff --git a/Cabal-syntax/cbits/mhs_posix.c b/mhs-compat-shims/cbits/mhs_posix.c similarity index 100% rename from Cabal-syntax/cbits/mhs_posix.c rename to mhs-compat-shims/cbits/mhs_posix.c diff --git a/Cabal-syntax/cbits/mhs_posix.h b/mhs-compat-shims/cbits/mhs_posix.h similarity index 100% rename from Cabal-syntax/cbits/mhs_posix.h rename to mhs-compat-shims/cbits/mhs_posix.h diff --git a/cabal-install/cbits/mhs_sha256.c b/mhs-compat-shims/cbits/mhs_sha256.c similarity index 100% rename from cabal-install/cbits/mhs_sha256.c rename to mhs-compat-shims/cbits/mhs_sha256.c diff --git a/cabal-install/cbits/mhs_sha256.h b/mhs-compat-shims/cbits/mhs_sha256.h similarity index 100% rename from cabal-install/cbits/mhs_sha256.h rename to mhs-compat-shims/cbits/mhs_sha256.h diff --git a/Cabal/cbits/mhs_spawn.c b/mhs-compat-shims/cbits/mhs_spawn.c similarity index 100% rename from Cabal/cbits/mhs_spawn.c rename to mhs-compat-shims/cbits/mhs_spawn.c diff --git a/Cabal/cbits/mhs_spawn.h b/mhs-compat-shims/cbits/mhs_spawn.h similarity index 100% rename from Cabal/cbits/mhs_spawn.h rename to mhs-compat-shims/cbits/mhs_spawn.h diff --git a/mhs-compat-shims/mhs-compat-shims.cabal b/mhs-compat-shims/mhs-compat-shims.cabal new file mode 100644 index 00000000000..0c9d9652200 --- /dev/null +++ b/mhs-compat-shims/mhs-compat-shims.cabal @@ -0,0 +1,83 @@ +cabal-version: 3.6 +name: mhs-compat-shims +version: 0.1.0.0 +copyright: 2026, Cabal Development Team (see AUTHORS file) +license: BSD-3-Clause +license-file: LICENSE +author: Cabal Development Team +maintainer: cabal-devel@haskell.org +homepage: http://www.haskell.org/cabal/ +bug-reports: https://github.com/haskell/cabal/issues +synopsis: MicroHs compatibility shims for Cabal and cabal-install +description: + Lightweight pure-Haskell and POSIX C compatibility shims used when + building Cabal, cabal-install-solver, and cabal-install with MicroHs (mhs). +category: Distribution +build-type: Simple + +extra-doc-files: + README.md + ChangeLog.md + +extra-source-files: + cbits/mhs_handle.h + cbits/mhs_posix.h + cbits/mhs_sha256.h + cbits/mhs_spawn.h + src/Data/Text/Encoding/Error.hs + src/Data/Text/Internal/Encoding/Utf8.hs + src/Data/Text/Lazy/Encoding.hs + +source-repository head + type: git + location: https://github.com/haskell/cabal/ + subdir: mhs-compat-shims + +library + default-language: GHC2021 + default-extensions: NoImportQualifiedPost + hs-source-dirs: src + include-dirs: cbits + install-includes: + mhs_handle.h + mhs_posix.h + mhs_sha256.h + mhs_spawn.h + c-sources: + cbits/mhs_handle.c + cbits/mhs_posix.c + cbits/mhs_sha256.c + cbits/mhs_spawn.c + + if !os(darwin) && !os(windows) + extra-libraries: crypto + + build-depends: + , base >= 4.18 && < 5 + , bytestring >= 0.10.4.0 && < 0.13 + , containers >= 0.5.2 && < 0.9 + , directory >= 1.2.7 && < 1.4 + , filepath >= 1.4.301 && < 1.6 + , text >= 1.2.3.0 && < 2.2 + , time >= 1.4.0.1 && < 1.17 + + exposed-modules: + Data.Binary + Data.Binary.Get + Data.Binary.Put + Distribution.Client.Compat.Base16 + Distribution.Compat.Internal.MhsPosix + Distribution.Compat.Internal.MhsProcess + Distribution.Compat.MhsInstances + Network.URI + Text.PrettyPrint + + if !impl(ghc) + exposed-modules: + Data.Text.Encoding.Error + Data.Text.Internal.Encoding.Utf8 + Data.Text.Lazy.Encoding + + ghc-options: + -Wall + -Wtabs diff --git a/mhs-compat-shims/src/Data/Binary.hs b/mhs-compat-shims/src/Data/Binary.hs new file mode 100644 index 00000000000..1031ee43437 --- /dev/null +++ b/mhs-compat-shims/src/Data/Binary.hs @@ -0,0 +1,369 @@ +-- | Byte-identical reimplementation of @Data.Binary@ from +-- @binary-0.8.9.3@ for MicroHs: the 'Binary' class, its base instances +-- and the top-level encode\/decode helpers. +-- +-- Wire formats mirror GHC's @binary@ exactly: +-- +-- * fixed-width integers are big-endian (network order), except where +-- an @le@ primitive is used; +-- * 'Int' and 'Word' are 8 bytes big-endian; +-- * 'Integer' uses the portable small-tag\/big-unrolled scheme; +-- * 'Char' is UTF-8, 'String' is a length-prefixed UTF-8 sequence; +-- * lists are an 'Int' length prefix followed by the elements; +-- * 'Maybe' and 'Either' use a leading tag byte; +-- * tuples are the concatenation of their components; +-- * strict and lazy 'ByteString' are an 'Int' length prefix followed by +-- the raw bytes; +-- * strict and lazy 'Text' are an 'Int' UTF-8 byte count followed by the +-- raw UTF-8 bytes. +-- +-- Deliberate deviations from GHC's @binary@: the generic-derivation +-- support ('GBinaryGet', 'GBinaryPut' and the @DefaultSignatures@ +-- defaults) is absent because MicroHs does not implement +-- @DefaultSignatures@; 'Float'\/'Double' instances are absent because +-- MicroHs @base@ does not export @encodeFloat@\/@decodeFloat@. +-- 'runGet', 'runGetOrFail' and 'ByteOffset' are additionally re-exported +-- here for convenience (GHC's @Data.Binary@ does not re-export them). +module Data.Binary + ( Binary (..) + , Get + , Put + , ByteOffset + , runGet + , runGetOrFail + , putWord8 + , getWord8 + , encode + , decode + , decodeOrFail + , encodeFile + , decodeFile + , decodeFileOrFail + , module Data.Word + ) where + +import Data.Bits (shiftL, shiftR, xor, (.&.), (.|.)) +import Data.Char (chr, ord) +import Data.Int (Int16, Int32, Int64, Int8) +import Data.Word + +import qualified Data.ByteString as BS +import qualified Data.ByteString.Lazy as LBS +import qualified Data.Map as Map +import qualified Data.Set as Set +import qualified Data.Text as T +import qualified Data.Text.Encoding as TE +import qualified Data.Text.Lazy as LT + +import Data.Binary.Get +import Data.Binary.Put + +-- | The 'Binary' class provides 'put' and 'get', methods to encode and +-- decode a Haskell value to a lazy 'ByteString'. +class Binary t where + -- | Encode a value in the 'Put' monad. + put :: t -> Put + -- | Decode a value in the 'Get' monad. + get :: Get t + -- | Encode a list of values. The default may be overridden for + -- efficiency but must keep the same encoding format. + putList :: [t] -> Put + putList xs = put (length xs) <> mapM_ put xs + +-- | Encode a list of values with an 'Int' length prefix, without +-- blowing the stack. +getMany :: Binary a => Int -> Get [a] +getMany n + | n < 0 = fail ("Data.Binary.getMany: negative length: " ++ show n) + | otherwise = go [] n + where + go acc 0 = return (reverse acc) + go acc i = do + x <- get + go (x : acc) (i - 1) + +-- | The () type need never be written to disk. +instance Binary () where + put () = return () + get = return () + +-- | 'Bool's are encoded as a byte in the range 0 .. 1. +instance Binary Bool where + put = putWord8 . fromIntegral . fromEnum + get = do + b <- getWord8 + case b of + 0 -> return False + 1 -> return True + _ -> fail ("Could not map value " ++ show b ++ " to Bool") + +-- | 'Word8's are written as a single byte. +instance Binary Word8 where + put = putWord8 + get = getWord8 + +-- | 'Word16's are written as 2 bytes in big-endian (network) order. +instance Binary Word16 where + put = putWord16be + get = getWord16be + +-- | 'Word32's are written as 4 bytes in big-endian (network) order. +instance Binary Word32 where + put = putWord32be + get = getWord32be + +-- | 'Word64's are written as 8 bytes in big-endian (network) order. +instance Binary Word64 where + put = putWord64be + get = getWord64be + +-- | 'Int8's are written as a single byte. +instance Binary Int8 where + put = putInt8 + get = getInt8 + +-- | 'Int16's are written as 2 bytes in big-endian order. +instance Binary Int16 where + put = putInt16be + get = getInt16be + +-- | 'Int32's are written as 4 bytes in big-endian order. +instance Binary Int32 where + put = putInt32be + get = getInt32be + +-- | 'Int64's are written as 8 bytes in big-endian order. +instance Binary Int64 where + put = putInt64be + get = getInt64be + +-- | 'Word's are written as 'Word64's, 8 bytes in big-endian order. +instance Binary Word where + put = putWord64be . fromIntegral + get = fromIntegral <$> getWord64be + +-- | 'Int's are written as 'Int64's, 8 bytes in big-endian order. +instance Binary Int where + put = putInt64be . fromIntegral + get = fromIntegral <$> getInt64be + +-- Fixed-size type for the small subset of 'Integer'. +type SmallInt = Int32 + +-- | Portable, efficient serialisation of 'Integer': values fitting in +-- a 'SmallInt' get a zero tag byte plus the value; larger values get a +-- one tag byte, a sign byte and the unrolled base-256 magnitude. +instance Binary Integer where + put n + | n >= lo && n <= hi = putWord8 0 <> put (fromIntegral n :: SmallInt) + | otherwise = putWord8 1 <> put sign <> put (unroll (abs n)) + where + lo = fromIntegral (minBound :: SmallInt) :: Integer + hi = fromIntegral (maxBound :: SmallInt) :: Integer + sign = fromIntegral (signum n) :: Word8 + get = do + tag <- (get :: Get Word8) + if tag == 0 + then fromIntegral <$> (get :: Get SmallInt) + else do + sign <- (get :: Get Word8) + bytes <- (get :: Get [Word8]) + let v = roll bytes + return (if sign == 1 then v else -v) + +-- | Fold an 'Integer' to a list of its base-256 digits, most +-- significant first. +unroll :: Integer -> [Word8] +unroll 0 = [] +unroll i = let (q, r) = i `divMod` 256 in fromIntegral r : unroll q + +-- | Unfold a list of base-256 digits, most significant first, back to +-- an 'Integer'. +roll :: [Word8] -> Integer +roll = foldl unstep 0 . reverse + where + unstep a b = a * 256 + fromIntegral b + +-- | 'Char' is serialised as UTF-8. +instance Binary Char where + put = putCharUtf8 + putList str = put (length str) <> putStringUtf8 str + get = do + let getByte = fromIntegral <$> (get :: Get Word8) :: Get Int + shiftL6 = (`shiftL` 6) :: Int -> Int + w <- getByte + r <- if w < 0x80 + then return w + else if w < 0xE0 + then do + x <- xor 0x80 <$> getByte + return (x .|. shiftL6 (xor 0xC0 w)) + else if w < 0xF0 + then do + x <- xor 0x80 <$> getByte + y <- xor 0x80 <$> getByte + return (y .|. shiftL6 (x .|. shiftL6 (xor 0xE0 w))) + else do + x <- xor 0x80 <$> getByte + y <- xor 0x80 <$> getByte + z <- xor 0x80 <$> getByte + return (z .|. shiftL6 (y .|. shiftL6 (x .|. shiftL6 (xor 0xF0 w)))) + if r <= 0x10FFFF + then return (chr r) + else fail "Not a valid Unicode code point!" + +-- | Lists are an 'Int' length prefix followed by the elements. +instance Binary a => Binary [a] where + put = putList + get = do + n <- (get :: Get Int) + getMany n + +-- | 'Maybe': a tag byte (0 for 'Nothing') followed by the value. +instance Binary a => Binary (Maybe a) where + put Nothing = putWord8 0 + put (Just x) = putWord8 1 <> put x + get = do + w <- getWord8 + if w == 0 then return Nothing else Just <$> get + +-- | 'Either': a tag byte (0 for 'Left') followed by the value. +instance (Binary a, Binary b) => Binary (Either a b) where + put (Left a) = putWord8 0 <> put a + put (Right b) = putWord8 1 <> put b + get = do + w <- getWord8 + if w == 0 then Left <$> get else Right <$> get + +-- | Tuples concatenate their components. +instance (Binary a, Binary b) => Binary (a, b) where + put (a, b) = put a <> put b + get = do + a <- get + b <- get + return (a, b) + +instance (Binary a, Binary b, Binary c) => Binary (a, b, c) where + put (a, b, c) = put a <> put b <> put c + get = do + a <- get + b <- get + c <- get + return (a, b, c) + +instance (Binary a, Binary b, Binary c, Binary d) => Binary (a, b, c, d) where + put (a, b, c, d) = put a <> put b <> put c <> put d + get = do + a <- get + b <- get + c <- get + d <- get + return (a, b, c, d) + +instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a, b, c, d, e) where + put (a, b, c, d, e) = put a <> put b <> put c <> put d <> put e + get = do + a <- get + b <- get + c <- get + d <- get + e <- get + return (a, b, c, d, e) + +-- | 'Set's are an 'Int' size prefix followed by the ascending elements. +-- Matches GHC's @binary@ ('Set.size', 'Set.toAscList', +-- 'Set.fromDistinctAscList'). +instance Binary a => Binary (Set.Set a) where + put s = put (Set.size s) <> mapM_ put (Set.toAscList s) + get = do + xs <- get + return (Set.fromDistinctAscList xs) + +-- | 'Map's are an 'Int' size prefix followed by the ascending entries. +-- Matches GHC's @binary@ ('Map.size', 'Map.toAscList', +-- 'Map.fromDistinctAscList'). +instance (Binary k, Binary v) => Binary (Map.Map k v) where + put m = put (Map.size m) <> mapM_ put (Map.toAscList m) + get = do + xs <- get + return (Map.fromDistinctAscList xs) + +-- | Strict 'ByteString's are an 'Int' length prefix plus the raw bytes. +instance Binary BS.ByteString where + put bs = put (BS.length bs) <> putByteString bs + get = do + n <- (get :: Get Int) + getByteString n + +-- | Lazy 'ByteString's are an 'Int' length prefix plus the raw bytes. +instance Binary LBS.ByteString where + put bs = put (fromIntegral (LBS.length bs) :: Int) <> putLazyByteString bs + get = do + n <- (get :: Get Int) + getLazyByteString (fromIntegral n) + +-- | Strict 'Text' is an 'Int' UTF-8 byte count plus the raw UTF-8 +-- bytes, exactly like @text@'s 'Binary' instance. +instance Binary T.Text where + put t = put (TE.encodeUtf8 t) + get = do + bs <- (get :: Get BS.ByteString) + let t = TE.decodeUtf8 bs + -- Reject non-canonical input the way @text@\'s decoder does: valid + -- UTF-8 re-encodes to itself. + if TE.encodeUtf8 t == bs + then return t + else fail ("Data.Binary.Text: cannot decode byte sequence") + +-- | Lazy 'Text' is an 'Int' UTF-8 byte count plus the raw UTF-8 bytes, +-- exactly like @text@'s lazy 'Binary' instance. +instance Binary LT.Text where + put t = put (LBS.fromChunks (map TE.encodeUtf8 (LT.toChunks t))) + get = do + bs <- (get :: Get LBS.ByteString) + let strict = LBS.toStrict bs + t = TE.decodeUtf8 strict + if TE.encodeUtf8 t == strict + then return (LT.fromStrict t) + else fail ("Data.Binary.Text: cannot decode byte sequence") + +-- | Encode a value to a lazy 'ByteString'. +encode :: Binary a => a -> LBS.ByteString +encode = runPut . put + +-- | Decode a value from a lazy 'ByteString', calling 'error' on +-- invalid input. +decode :: Binary a => LBS.ByteString -> a +decode = runGet get + +-- | Decode a value, returning 'Left' on failure with the unconsumed +-- input, the byte offset and a message. +decodeOrFail :: Binary a => LBS.ByteString -> Either (LBS.ByteString, ByteOffset, String) (LBS.ByteString, ByteOffset, a) +decodeOrFail = runGetOrFail get + +-- | Lazily serialise a value to a file. +encodeFile :: Binary a => FilePath -> a -> IO () +encodeFile f v = LBS.writeFile f (encode v) + +-- | Decode a value from a file, calling 'error' on failure. +decodeFile :: Binary a => FilePath -> IO a +decodeFile f = do + result <- decodeFileOrFail f + case result of + Right x -> return x + Left (_, msg) -> error msg + +-- | Decode a value from a file, returning the byte offset and message +-- on failure. +-- +-- Note: MicroHs does not implement lazy 'LBS.readFile' (it raises +-- @Data.ByteString.hGetSome unimplemented@), so the file is read +-- strictly and converted. The decoded value is identical; only the +-- incremental\/lazy behaviour differs. +decodeFileOrFail :: Binary a => FilePath -> IO (Either (ByteOffset, String) a) +decodeFileOrFail f = do + bs <- BS.readFile f + case runGetOrFail get (LBS.fromStrict bs) of + Left (_, pos, msg) -> return (Left (pos, msg)) + Right (_, _, a) -> return (Right a) + diff --git a/mhs-compat-shims/src/Data/Binary/Get.hs b/mhs-compat-shims/src/Data/Binary/Get.hs new file mode 100644 index 00000000000..c4f98b56bb4 --- /dev/null +++ b/mhs-compat-shims/src/Data/Binary/Get.hs @@ -0,0 +1,294 @@ +-- | Byte-identical reimplementation of @Data.Binary.Get@ from +-- @binary-0.8.9.3@ for MicroHs. +-- +-- The 'Get' monad is a simple state transformer over the remaining +-- lazy 'ByteString' input plus a byte offset. Failure positions and +-- 'runGet' error messages match GHC's @binary@. +module Data.Binary.Get + ( Get + , ByteOffset + , runGet + , runGetOrFail + , skip + , isEmpty + , remaining + , bytesRead + , lookAhead + , label + , isolate + , getWord8 + , getWord16be + , getWord16le + , getWord32be + , getWord32le + , getWord64be + , getWord64le + , getInt8 + , getInt16be + , getInt16le + , getInt32be + , getInt32le + , getInt64be + , getInt64le + , getByteString + , getLazyByteString + , getRemainingLazyByteString + ) where + +import Control.Applicative (Alternative (..)) +import Control.Monad (MonadPlus (..)) +import Control.Monad.Fail (MonadFail (..)) +import Data.Bits (shiftL, (.|.)) +import Data.Int (Int16, Int32, Int64, Int8) +import Data.Word (Word16, Word32, Word64, Word8) + +import qualified Data.ByteString as BS +import qualified Data.ByteString.Lazy as LBS + +-- | Byte offset into the input, matching @binary@. +type ByteOffset = Int64 + +-- | The 'Get' monad. The function takes the remaining input and the +-- number of bytes consumed so far. On failure it returns the input +-- and offset at the failure point plus a message, exactly as +-- 'runGetOrFail' reports them. +newtype Get a = Get + { unGet :: LBS.ByteString -> Int64 -> Either (LBS.ByteString, Int64, String) (a, LBS.ByteString, Int64) + } + +instance Functor Get where + fmap f (Get m) = Get (\lbs pos -> + case m lbs pos of + Left err -> Left err + Right (a, rest, pos') -> Right (f a, rest, pos')) + +instance Applicative Get where + pure a = Get (\lbs pos -> Right (a, lbs, pos)) + Get f <*> Get x = Get (\lbs pos -> + case f lbs pos of + Left err -> Left err + Right (g, rest, pos') -> + case x rest pos' of + Left err -> Left err + Right (a, rest', pos'') -> Right (g a, rest', pos'')) + +instance Monad Get where + return = pure + Get m >>= k = Get (\lbs pos -> + case m lbs pos of + Left err -> Left err + Right (a, rest, pos') -> unGet (k a) rest pos') + +instance MonadFail Get where + fail msg = Get (\lbs pos -> Left (lbs, pos, msg)) + +-- | Backtracking choice: on failure the input is rewound and the +-- second decoder runs, exactly as in GHC's @binary@. +instance Alternative Get where + empty = Get (\lbs pos -> Left (lbs, pos, "Data.Binary.Get(Alternative).empty")) + Get f <|> Get g = Get (\lbs pos -> + case f lbs pos of + Left _ -> g lbs pos + Right x -> Right x) + some p = (:) <$> p <*> many p + many p = do + v <- (Just <$> p) <|> pure Nothing + case v of + Nothing -> pure [] + Just x -> (:) x <$> many p + +instance MonadPlus Get where + mzero = empty + mplus = (<|>) + +-- | Run a decoder, returning the leftover input, the final offset and +-- either an error message or the value. +runGetOrFail :: Get a -> LBS.ByteString -> Either (LBS.ByteString, ByteOffset, String) (LBS.ByteString, ByteOffset, a) +runGetOrFail (Get m) lbs = + case m lbs 0 of + Left err -> Left err + Right (a, rest, pos) -> Right (rest, pos, a) + +-- | Run a decoder, calling 'error' on failure, as @binary@ does. +runGet :: Get a -> LBS.ByteString -> a +runGet m lbs = + case runGetOrFail m lbs of + Left (_, pos, msg) -> error ("Data.Binary.Get.runGet at position " ++ show pos ++ ": " ++ msg) + Right (_, _, a) -> a + +-- | Consume @n@ bytes and return them unpacked, failing on short input. +getN :: Int64 -> Get [Word8] +getN n + | n < 0 = fail ("Data.Binary.Get: negative length: " ++ show n) + | otherwise = Get (\lbs pos -> + if LBS.length lbs < n + then Left (lbs, pos, "not enough bytes") + else let (h, t) = LBS.splitAt n lbs + in Right (LBS.unpack h, t, pos + n)) + +-- | Skip ahead @n@ bytes. Fails if fewer than @n@ bytes are available. +skip :: Int -> Get () +skip n + | n <= 0 = return () + | otherwise = Get (\lbs pos -> + let n64 = fromIntegral n :: Int64 + in if LBS.length lbs < n64 + then Left (lbs, pos, "not enough bytes") + else Right ((), LBS.drop n64 lbs, pos + n64)) + +-- | Succeeds iff there is no more input. +isEmpty :: Get Bool +isEmpty = Get (\lbs pos -> Right (LBS.null lbs, lbs, pos)) + +-- | Number of unread bytes. +remaining :: Get Int64 +remaining = Get (\lbs pos -> Right (LBS.length lbs, lbs, pos)) + +-- | Number of bytes read so far. +bytesRead :: Get ByteOffset +bytesRead = Get (\lbs pos -> Right (pos, lbs, pos)) + +-- | Run a decoder without consuming input. +lookAhead :: Get a -> Get a +lookAhead (Get m) = Get (\lbs pos -> + case m lbs pos of + Left err -> Left err + Right (a, _, _) -> Right (a, lbs, pos)) + +-- | Label a decoder (no-op, kept for API compatibility). +label :: String -> Get a -> Get a +label _ m = m + +-- | Run a decoder on a fixed @n@-byte window. Fails if the window is +-- not fully available or the inner decoder reads past it. Unconsumed +-- window bytes are skipped. +isolate :: Int -> Get a -> Get a +isolate n (Get m) + | n < 0 = fail ("Data.Binary.Get.isolate: negative length: " ++ show n) + | otherwise = Get (\lbs pos -> + let n64 = fromIntegral n :: Int64 + in if LBS.length lbs < n64 + then Left (lbs, pos, "not enough bytes") + else let (window, rest) = LBS.splitAt n64 lbs + in case m window pos of + Left (_, pos', msg) -> Left (lbs, pos', msg) + Right (a, leftover, _) -> + let consumed = n64 - LBS.length leftover + in Right (a, rest, pos + consumed)) + +-- | Read one byte. +getWord8 :: Get Word8 +getWord8 = do + [b] <- getN 1 + return b + +-- | Read a 16-bit word in big-endian (network) order. +getWord16be :: Get Word16 +getWord16be = do + [b0, b1] <- getN 2 + return ((fromIntegral b0 `shiftL` 8) .|. fromIntegral b1) + +-- | Read a 16-bit word in little-endian order. +getWord16le :: Get Word16 +getWord16le = do + [b0, b1] <- getN 2 + return ((fromIntegral b1 `shiftL` 8) .|. fromIntegral b0) + +-- | Read a 32-bit word in big-endian (network) order. +getWord32be :: Get Word32 +getWord32be = do + [b0, b1, b2, b3] <- getN 4 + return ((fromIntegral b0 `shiftL` 24) .|. (fromIntegral b1 `shiftL` 16) .|. + (fromIntegral b2 `shiftL` 8) .|. fromIntegral b3) + +-- | Read a 32-bit word in little-endian order. +getWord32le :: Get Word32 +getWord32le = do + [b0, b1, b2, b3] <- getN 4 + return ((fromIntegral b3 `shiftL` 24) .|. (fromIntegral b2 `shiftL` 16) .|. + (fromIntegral b1 `shiftL` 8) .|. fromIntegral b0) + +-- | Read a 64-bit word in big-endian (network) order. +getWord64be :: Get Word64 +getWord64be = do + [b0, b1, b2, b3, b4, b5, b6, b7] <- getN 8 + return ((fromIntegral b0 `shiftL` 56) .|. (fromIntegral b1 `shiftL` 48) .|. + (fromIntegral b2 `shiftL` 40) .|. (fromIntegral b3 `shiftL` 32) .|. + (fromIntegral b4 `shiftL` 24) .|. (fromIntegral b5 `shiftL` 16) .|. + (fromIntegral b6 `shiftL` 8) .|. fromIntegral b7) + +-- | Read a 64-bit word in little-endian order. +getWord64le :: Get Word64 +getWord64le = do + [b0, b1, b2, b3, b4, b5, b6, b7] <- getN 8 + return ((fromIntegral b7 `shiftL` 56) .|. (fromIntegral b6 `shiftL` 48) .|. + (fromIntegral b5 `shiftL` 40) .|. (fromIntegral b4 `shiftL` 32) .|. + (fromIntegral b3 `shiftL` 24) .|. (fromIntegral b2 `shiftL` 16) .|. + (fromIntegral b1 `shiftL` 8) .|. fromIntegral b0) + +-- | Wrap an unsigned value into its signed counterpart, matching +-- GHC's 'fromIntegral'. MicroHs traps on narrowing unsigned-to-signed +-- conversions that GHC wraps, so the wrap is done explicitly through +-- 'Int' (wide enough for 8-, 16- and 32-bit magnitudes). +wrap8 :: Word8 -> Int8 +wrap8 w = fromIntegral (if i >= 128 then i - 256 else i) + where + i = fromIntegral w :: Int + +-- | See 'wrap8'. +wrap16 :: Word16 -> Int16 +wrap16 w = fromIntegral (if i >= 32768 then i - 65536 else i) + where + i = fromIntegral w :: Int + +-- | See 'wrap8'. +wrap32 :: Word32 -> Int32 +wrap32 w = fromIntegral (if i >= 2147483648 then i - 4294967296 else i) + where + i = fromIntegral w :: Int + +-- | Read a signed 8-bit value. +getInt8 :: Get Int8 +getInt8 = wrap8 <$> getWord8 + +-- | Read a signed 16-bit value in big-endian order. +getInt16be :: Get Int16 +getInt16be = wrap16 <$> getWord16be + +-- | Read a signed 16-bit value in little-endian order. +getInt16le :: Get Int16 +getInt16le = wrap16 <$> getWord16le + +-- | Read a signed 32-bit value in big-endian order. +getInt32be :: Get Int32 +getInt32be = wrap32 <$> getWord32be + +-- | Read a signed 32-bit value in little-endian order. +getInt32le :: Get Int32 +getInt32le = wrap32 <$> getWord32le + +-- | Read a signed 64-bit value in big-endian order. +getInt64be :: Get Int64 +getInt64be = fromIntegral <$> getWord64be + +-- | Read a signed 64-bit value in little-endian order. +getInt64le :: Get Int64 +getInt64le = fromIntegral <$> getWord64le + +-- | Read @n@ bytes as a strict 'ByteString'. +getByteString :: Int -> Get BS.ByteString +getByteString n = BS.pack <$> getN (fromIntegral n) + +-- | Read @n@ bytes as a lazy 'ByteString'. +getLazyByteString :: Int64 -> Get LBS.ByteString +getLazyByteString n + | n < 0 = fail ("Data.Binary.Get.getLazyByteString: negative length: " ++ show n) + | otherwise = Get (\lbs pos -> + if LBS.length lbs < n + then Left (lbs, pos, "not enough bytes") + else let (h, t) = LBS.splitAt n lbs + in Right (h, t, pos + n)) + +-- | Read all remaining input as a lazy 'ByteString'. +getRemainingLazyByteString :: Get LBS.ByteString +getRemainingLazyByteString = Get (\lbs pos -> Right (lbs, LBS.empty, pos + LBS.length lbs)) diff --git a/mhs-compat-shims/src/Data/Binary/Put.hs b/mhs-compat-shims/src/Data/Binary/Put.hs new file mode 100644 index 00000000000..b3b65a3729e --- /dev/null +++ b/mhs-compat-shims/src/Data/Binary/Put.hs @@ -0,0 +1,202 @@ +-- | Byte-identical reimplementation of @Data.Binary.Put@ from +-- @binary-0.8.9.3@ for MicroHs. +-- +-- The 'Put' monad here is a difference list of strict 'ByteString' +-- chunks. Every primitive below emits exactly the bytes that GHC's +-- @binary@ emits for the same value (big-endian network order for the +-- @be@ variants, little-endian for the @le@ variants). +module Data.Binary.Put + ( Put + , PutM + , runPut + , runPutM + , putWord8 + , putWord16be + , putWord16le + , putWord32be + , putWord32le + , putWord64be + , putWord64le + , putInt8 + , putInt16be + , putInt16le + , putInt32be + , putInt32le + , putInt64be + , putInt64le + , putByteString + , putLazyByteString + , putCharUtf8 + , putStringUtf8 + ) where + +import Data.Bits (shiftR, (.&.)) +import Data.Char (ord) +import Data.Int (Int16, Int32, Int64, Int8) +import Data.Word (Word16, Word32, Word64, Word8) + +import qualified Data.ByteString as BS +import qualified Data.ByteString.Lazy as LBS + +-- | The 'Put' monad: a value-producing builder of strict 'ByteString' +-- chunks, accumulated in a difference list. +newtype PutM a = PutM { unPutM :: [BS.ByteString] -> (a, [BS.ByteString]) } + +-- | A 'Put' is a 'PutM' producing no interesting value. +type Put = PutM () + +instance Functor PutM where + fmap f (PutM m) = PutM (\cs -> let (a, cs') = m cs in (f a, cs')) + +instance Applicative PutM where + pure a = PutM (\cs -> (a, cs)) + PutM f <*> PutM x = PutM (\cs -> let (g, cs1) = f cs + (a, cs2) = x cs1 + in (g a, cs2)) + +instance Monad PutM where + return = pure + PutM m >>= k = PutM (\cs -> let (a, cs1) = m cs in unPutM (k a) cs1) + +instance Semigroup Put where + (<>) = (>>) + +instance Monoid Put where + mempty = return () + mappend = (<>) + +-- | Run a 'PutM', returning the value and the serialised bytes. +runPutM :: PutM a -> (a, LBS.ByteString) +runPutM (PutM m) = + let (a, chunks) = m [] + in (a, LBS.fromChunks (reverse chunks)) + +-- | Run a 'Put', returning the serialised bytes. +runPut :: Put -> LBS.ByteString +runPut = snd . runPutM + +-- | Emit one strict chunk. +tell :: BS.ByteString -> Put +tell bs = PutM (\cs -> ((), bs : cs)) + +-- | Write a byte. +putWord8 :: Word8 -> Put +putWord8 w = tell (BS.singleton w) + +-- | Write a 16-bit word in big-endian (network) order. +putWord16be :: Word16 -> Put +putWord16be w = tell (BS.pack [fromIntegral (w `shiftR` 8), fromIntegral w]) + +-- | Write a 16-bit word in little-endian order. +putWord16le :: Word16 -> Put +putWord16le w = tell (BS.pack [fromIntegral w, fromIntegral (w `shiftR` 8)]) + +-- | Write a 32-bit word in big-endian (network) order. +putWord32be :: Word32 -> Put +putWord32be w = + tell (BS.pack [ fromIntegral (w `shiftR` 24) + , fromIntegral (w `shiftR` 16) + , fromIntegral (w `shiftR` 8) + , fromIntegral w + ]) + +-- | Write a 32-bit word in little-endian order. +putWord32le :: Word32 -> Put +putWord32le w = + tell (BS.pack [ fromIntegral w + , fromIntegral (w `shiftR` 8) + , fromIntegral (w `shiftR` 16) + , fromIntegral (w `shiftR` 24) + ]) + +-- | Write a 64-bit word in big-endian (network) order. +putWord64be :: Word64 -> Put +putWord64be w = + tell (BS.pack [ fromIntegral (w `shiftR` 56) + , fromIntegral (w `shiftR` 48) + , fromIntegral (w `shiftR` 40) + , fromIntegral (w `shiftR` 32) + , fromIntegral (w `shiftR` 24) + , fromIntegral (w `shiftR` 16) + , fromIntegral (w `shiftR` 8) + , fromIntegral w + ]) + +-- | Write a 64-bit word in little-endian order. +putWord64le :: Word64 -> Put +putWord64le w = + tell (BS.pack [ fromIntegral w + , fromIntegral (w `shiftR` 8) + , fromIntegral (w `shiftR` 16) + , fromIntegral (w `shiftR` 24) + , fromIntegral (w `shiftR` 32) + , fromIntegral (w `shiftR` 40) + , fromIntegral (w `shiftR` 48) + , fromIntegral (w `shiftR` 56) + ]) + +-- | Write a signed 8-bit value. +putInt8 :: Int8 -> Put +putInt8 i = putWord8 (fromIntegral i) + +-- | Write a signed 16-bit value in big-endian order. +putInt16be :: Int16 -> Put +putInt16be i = putWord16be (fromIntegral i) + +-- | Write a signed 16-bit value in little-endian order. +putInt16le :: Int16 -> Put +putInt16le i = putWord16le (fromIntegral i) + +-- | Write a signed 32-bit value in big-endian order. +putInt32be :: Int32 -> Put +putInt32be i = putWord32be (fromIntegral i) + +-- | Write a signed 32-bit value in little-endian order. +putInt32le :: Int32 -> Put +putInt32le i = putWord32le (fromIntegral i) + +-- | Write a signed 64-bit value in big-endian order. +putInt64be :: Int64 -> Put +putInt64be i = putWord64be (fromIntegral i) + +-- | Write a signed 64-bit value in little-endian order. +putInt64le :: Int64 -> Put +putInt64le i = putWord64le (fromIntegral i) + +-- | Write a strict 'ByteString' without a length prefix. +putByteString :: BS.ByteString -> Put +putByteString = tell + +-- | Write a lazy 'ByteString' without a length prefix. +putLazyByteString :: LBS.ByteString -> Put +putLazyByteString lbs = PutM (\cs -> ((), foldl (flip (:)) cs (LBS.toChunks lbs))) + +-- | Write a 'Char' using UTF-8 encoding, byte-identical to +-- @binary-0.8.9.3@ ('Data.Binary.Builder.putCharUtf8'). +putCharUtf8 :: Char -> Put +putCharUtf8 c = tell (BS.pack (encodeChar (ord c))) + where + encodeChar :: Int -> [Word8] + encodeChar x + | x < 0x80 = + [ fromIntegral x ] + | x < 0x800 = + [ fromIntegral (0xC0 + (x `shiftR` 6)) + , fromIntegral (0x80 + (x .&. 0x3F)) + ] + | x < 0x10000 = + [ fromIntegral (0xE0 + (x `shiftR` 12)) + , fromIntegral (0x80 + ((x `shiftR` 6) .&. 0x3F)) + , fromIntegral (0x80 + (x .&. 0x3F)) + ] + | otherwise = + [ fromIntegral (0xF0 + (x `shiftR` 18)) + , fromIntegral (0x80 + ((x `shiftR` 12) .&. 0x3F)) + , fromIntegral (0x80 + ((x `shiftR` 6) .&. 0x3F)) + , fromIntegral (0x80 + (x .&. 0x3F)) + ] + +-- | Write a 'String' using UTF-8 encoding, byte-identical to +-- @binary-0.8.9.3@ ('Data.Binary.Builder.putStringUtf8'). +putStringUtf8 :: String -> Put +putStringUtf8 = mapM_ putCharUtf8 diff --git a/mhs-compat-shims/src/Data/Text/Encoding/Error.hs b/mhs-compat-shims/src/Data/Text/Encoding/Error.hs new file mode 100644 index 00000000000..8f503149e1e --- /dev/null +++ b/mhs-compat-shims/src/Data/Text/Encoding/Error.hs @@ -0,0 +1,89 @@ +-- | Missing pieces of "Data.Text.Encoding" for MicroHs. +-- +-- MicroHs ships "Data.Text.Encoding" ('decodeUtf8', 'encodeUtf8', ...) +-- but not this module. The re-exported 'decodeUtf8With' lives here +-- (rather than in "Data.Text.Encoding", which MicroHs already +-- provides) so that existing qualified imports keep working. +module Data.Text.Encoding.Error + ( OnDecodeError + , lenientDecode + , strictDecode + , UnicodeException (..) + , decodeUtf8With + ) where + +import qualified Data.ByteString as BS +import Data.Char (chr) +import Data.Word (Word8) +import qualified Data.Text as T +import Data.Bits ((.&.), (.|.), shiftL) + +-- | How to handle a decoding error: the name of the calling function, +-- the offending byte if any, and the replacement character ('Just') +-- or failure ('Nothing'). +type OnDecodeError = String -> Maybe Word8 -> Maybe Char + +-- | Replace malformed input with the replacement character U+FFFD. +lenientDecode :: OnDecodeError +lenientDecode _ _ = Just '\xFFFD' + +-- | Fail on malformed input (the decoder throws instead). +strictDecode :: OnDecodeError +strictDecode _ _ = Nothing + +-- | Exception type mirroring @text@'s; carried for API compatibility. +-- The decoder below throws a plain 'error' instead, since none of our +-- call sites catch this type. +data UnicodeException + = DecodeError String (Maybe Word8) + | EncodeError String (Maybe Char) + deriving (Eq, Show) + +-- | Decode UTF-8, consulting the 'OnDecodeError' handler for +-- malformed sequences: overlongs, surrogates, code points above +-- U+10FFFF, lone continuation bytes and truncated input. +-- Each reported byte advances past one byte and decoding resumes. +decodeUtf8With :: OnDecodeError -> BS.ByteString -> T.Text +decodeUtf8With onErr = T.pack . decode . map fromIntegral . BS.unpack + where + decode :: [Int] -> String + decode [] = [] + decode (b : bs) + | b < 0x80 = chr b : decode bs + | b < 0xC2 = bad b bs + | b < 0xE0 = two b bs + | b < 0xF0 = three b bs + | b < 0xF5 = four b bs + | otherwise = bad b bs + -- Report one bad byte and resume after it. + bad :: Int -> [Int] -> String + bad b bs = case onErr "Data.Text.Encoding.decodeUtf8With" (Just (fromIntegral b)) of + Just c -> c : decode bs + Nothing -> error "Data.Text.Encoding.decodeUtf8With: invalid input" + isCont b = b >= 0x80 && b < 0xC0 + two b1 bs = case bs of + (b2 : bs') + | isCont b2 -> + chr (((b1 .&. 0x1F) `shiftL` 6) .|. (b2 .&. 0x3F)) : decode bs' + _ -> bad b1 bs + three b1 bs = case bs of + (b2 : b3 : bs') + | isCont b2 && isCont b3 && ok3 b1 b2 -> + chr ((((b1 .&. 0x0F) `shiftL` 12) .|. ((b2 .&. 0x3F) `shiftL` 6)) .|. (b3 .&. 0x3F)) : decode bs' + _ -> bad b1 bs + four b1 bs = case bs of + (b2 : b3 : b4 : bs') + | isCont b2 && isCont b3 && isCont b4 && ok4 b1 b2 -> + chr (((((b1 .&. 0x07) `shiftL` 18) .|. ((b2 .&. 0x3F) `shiftL` 12)) .|. ((b3 .&. 0x3F) `shiftL` 6)) .|. (b4 .&. 0x3F)) : decode bs' + _ -> bad b1 bs + -- Reject overlongs. + ok3 b1 b2 + | b1 == 0xE0 = b2 >= 0xA0 + -- Reject UTF-16 surrogates. + | b1 == 0xED = b2 <= 0x9F + | otherwise = True + -- Reject overlongs and code points past U+10FFFF. + ok4 b1 b2 + | b1 == 0xF0 = b2 >= 0x90 + | b1 == 0xF4 = b2 <= 0x8F + | otherwise = True diff --git a/mhs-compat-shims/src/Data/Text/Internal/Encoding/Utf8.hs b/mhs-compat-shims/src/Data/Text/Internal/Encoding/Utf8.hs new file mode 100644 index 00000000000..65b2248dc62 --- /dev/null +++ b/mhs-compat-shims/src/Data/Text/Internal/Encoding/Utf8.hs @@ -0,0 +1,79 @@ +-- | Incremental UTF-8 decoder used by the @.cabal@ file lexer. +-- +-- MicroHs has no 'Data.Text.Internal' decoder, so this mirrors the +-- interface that @Distribution.Parsec.FieldLineStream@ expects from +-- @text@: a byte-at-a-time state machine. On well-formed input it +-- agrees with 'Data.Text.Encoding.decodeUtf8' exactly; on malformed +-- input it reports 'Reject' (the caller substitutes U+FFFD and moves +-- on) rather than throwing. +-- +-- Note: unlike batch decoding, a rejected byte is consumed, not +-- reprocessed, because the caller advances past every byte it feeds +-- in. Well-formed input decodes identically either way. +module Data.Text.Internal.Encoding.Utf8 + ( Decoder (..) + , State + , utf8DecodeStart + , utf8DecodeContinue + ) where + +import Data.Bits ((.&.), (.|.), shiftL) +import Data.Char (chr) +import Data.Word (Word8) + +-- | Incremental decoder state: remaining continuation bytes, +-- accumulated value, and the lead byte (needed to reject overlongs, +-- surrogates and out-of-range code points once the second byte +-- arrives). +data State = S !Int !Int !Word8 + +data Decoder + = Accept !Char + | Reject + | Incomplete !State !Char + +-- | Feed the first byte of a sequence. The 'Char' carried by +-- 'Incomplete' is a dummy; the real state lives in 'State'. +utf8DecodeStart :: Word8 -> Decoder +utf8DecodeStart b0 + | b < 0x80 = Accept (chr b) + | b < 0xC2 = Reject + | b < 0xE0 = Incomplete (S 1 (b .&. 0x1F) b0) dummy + | b < 0xF0 = Incomplete (S 2 (b .&. 0x0F) b0) dummy + | b < 0xF5 = Incomplete (S 3 (b .&. 0x07) b0) dummy + | otherwise = Reject + where + b :: Int + b = fromIntegral b0 + dummy = '\0' + +-- | Feed a continuation byte. Invalid bytes (and overlong, surrogate +-- or out-of-range sequences) yield 'Reject', which tells the caller +-- to emit U+FFFD and continue with the byte after the one just fed. +utf8DecodeContinue :: Word8 -> State -> Char -> Decoder +utf8DecodeContinue w (S n acc lead) _ + | not (isCont b) = Reject + | badLead = Reject + | n' == 0 = Accept (chr acc') + | otherwise = Incomplete (S n' acc' lead) dummy + where + b :: Int + b = fromIntegral w + isCont x = x >= 0x80 && x < 0xC0 + -- Overlong / surrogate / out-of-range checks apply only to the + -- first continuation byte (which is when the lead byte's + -- restrictions become testable). + badLead = n == totalFor lead && case leadI of + 0xE0 -> b < 0xA0 + 0xED -> b > 0x9F + 0xF0 -> b < 0x90 + 0xF4 -> b > 0x8F + _ -> False + leadI = fromIntegral lead :: Int + totalFor l + | l < 0xE0 = 1 + | l < 0xF0 = 2 + | otherwise = 3 + acc' = (acc `shiftL` 6) .|. (b .&. 0x3F) + n' = n - 1 + dummy = '\0' diff --git a/mhs-compat-shims/src/Data/Text/Lazy/Encoding.hs b/mhs-compat-shims/src/Data/Text/Lazy/Encoding.hs new file mode 100644 index 00000000000..20c1d3db029 --- /dev/null +++ b/mhs-compat-shims/src/Data/Text/Lazy/Encoding.hs @@ -0,0 +1,25 @@ +-- | Lazy 'ByteString' decoding helpers missing from MicroHs. +-- +-- MicroHs ships strict "Data.Text.Encoding" ('decodeUtf8', +-- 'encodeUtf8') but no lazy counterpart; the lazy decoder goes +-- through the strict one, which is fine for the small inputs +-- involved (package descriptions and index fragments). +module Data.Text.Lazy.Encoding + ( decodeUtf8With + , encodeUtf8 + ) where + +import qualified Data.ByteString.Lazy as LBS +import qualified Data.Text.Encoding as TE +import qualified Data.Text.Encoding.Error as E +import qualified Data.Text.Lazy as TL + +-- | Decode lazy UTF-8, consulting the 'OnDecodeError' handler. +-- Implemented via the strict decoder, which is fine for the small +-- inputs involved (package descriptions and index fragments). +decodeUtf8With :: E.OnDecodeError -> LBS.ByteString -> TL.Text +decodeUtf8With onErr = TL.fromStrict . E.decodeUtf8With onErr . LBS.toStrict + +-- | Encode to lazy UTF-8. +encodeUtf8 :: TL.Text -> LBS.ByteString +encodeUtf8 = LBS.fromStrict . TE.encodeUtf8 . TL.toStrict diff --git a/cabal-install/src/Distribution/Client/Compat/Base16.hs b/mhs-compat-shims/src/Distribution/Client/Compat/Base16.hs similarity index 99% rename from cabal-install/src/Distribution/Client/Compat/Base16.hs rename to mhs-compat-shims/src/Distribution/Client/Compat/Base16.hs index 082910d7133..63af1b59772 100644 --- a/cabal-install/src/Distribution/Client/Compat/Base16.hs +++ b/mhs-compat-shims/src/Distribution/Client/Compat/Base16.hs @@ -26,6 +26,7 @@ encode = BS.pack . concatMap byteHex . BS.unpack hexDigit n = fromIntegral (fromEnum c) where c = "0123456789abcdef" !! fromIntegral n + -- | Decode hex (upper- or lower-case) to bytes. decode :: BS.ByteString -> Either String BS.ByteString decode bs diff --git a/Cabal-syntax/src/Distribution/Compat/Internal/MhsPosix.hs b/mhs-compat-shims/src/Distribution/Compat/Internal/MhsPosix.hs similarity index 99% rename from Cabal-syntax/src/Distribution/Compat/Internal/MhsPosix.hs rename to mhs-compat-shims/src/Distribution/Compat/Internal/MhsPosix.hs index a8316610f49..2627cb007da 100644 --- a/Cabal-syntax/src/Distribution/Compat/Internal/MhsPosix.hs +++ b/mhs-compat-shims/src/Distribution/Compat/Internal/MhsPosix.hs @@ -208,7 +208,6 @@ mhsSetModTime fp sec nsec = -- module rather than behaviour-critical code. import Data.Bits ((.&.), (.|.)) import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) -import System.IO (writeFile) import System.IO.Error (catchIOError, isAlreadyExistsError) import System.Directory ( Permissions (..) diff --git a/Cabal/src/Distribution/Compat/Internal/MhsProcess.hs b/mhs-compat-shims/src/Distribution/Compat/Internal/MhsProcess.hs similarity index 94% rename from Cabal/src/Distribution/Compat/Internal/MhsProcess.hs rename to mhs-compat-shims/src/Distribution/Compat/Internal/MhsProcess.hs index 19eec4a2c94..cd4851e9e9d 100644 --- a/Cabal/src/Distribution/Compat/Internal/MhsProcess.hs +++ b/mhs-compat-shims/src/Distribution/Compat/Internal/MhsProcess.hs @@ -48,10 +48,8 @@ import qualified Data.ByteString as BS import Data.Char (chr, ord) import System.IO.Internal (BFILE, withHandleAny) #endif -import qualified Data.ByteString.Lazy as LBS -import Data.IORef (IORef, modifyIORef, newIORef, readIORef, writeIORef) -import Distribution.Compat.Directory (doesFileExist, getCurrentDirectory, getTemporaryDirectory, removeFile, setCurrentDirectory) -import Distribution.Compat.Internal.TempFile (openBinaryTempFile) +import Data.IORef (IORef, atomicModifyIORef', modifyIORef, newIORef, readIORef, writeIORef) +import qualified Distribution.Compat.Internal.MhsPosix as MhsPosix import Foreign.C.Error (throwErrnoIfMinus1, throwErrnoIfMinus1_) import Foreign.C.String (CString, newCAString, withCAString) import Foreign.C.Types (CInt (..)) @@ -59,9 +57,9 @@ import Foreign.Marshal.Alloc (alloca, allocaBytes, free) import Foreign.Marshal.Array (withArray0) import Foreign.Ptr (Ptr, nullPtr) import Foreign.Storable (peek, pokeElemOff, sizeOf) -import System.Environment (getEnvironment, setEnv, unsetEnv) +import System.Directory (getCurrentDirectory, getTemporaryDirectory, removeFile, setCurrentDirectory) import System.Exit (ExitCode (..)) -import System.IO (BufferMode (..), Handle, IOMode (..), hClose, hSetBuffering, openFile +import System.IO (BufferMode (..), Handle, IOMode (..), hSetBuffering, openFile #ifdef __MHS__ , hGetContents, hPutStr #endif @@ -446,19 +444,22 @@ mhsTerminate :: MhsChild -> IO () mhsTerminate (MhsChild pid _ _ _) = throwErrnoIfMinus1_ "mhsTerminate" (c_mhs_terminate (fromIntegral pid)) --- | Create a fresh empty temporary file, returning its path. The --- file exists (so the child can open it without @O_CREAT@ races) and --- is removed by 'mhsWait' once the owning child is reaped. It goes --- through "Distribution.Compat.Internal.TempFile" (atomic --- @O_CREAT@|@O_EXCL@ creation instead of MicroHs' unhardened --- check-then-open 'System.IO.openTempFile'), and is binary so piped --- child output round-trips byte-for-byte. +doesFileExist :: FilePath -> IO Bool +doesFileExist fp = (== MhsPosix.MhsFile) <$> MhsPosix.mhsPathKind fp True + +{-# NOINLINE tempPipeCounter #-} +tempPipeCounter :: IORef Int +tempPipeCounter = unsafePerformIO (newIORef 0) + mhsTempFile :: IO FilePath mhsTempFile = do tmp <- getTemporaryDirectory - (path, h) <- openBinaryTempFile tmp "cabal-mhs-pipe" - hClose h - pure path + let findTemp = do + n <- atomicModifyIORef' tempPipeCounter (\c -> let c' = c + 1 in (c', c')) + let path = tmp ++ "/cabal-mhs-pipe-" ++ show n + created <- MhsPosix.mhsCreateExclusive path 0o600 + if created then pure path else findTemp + findTemp -- | Registry remembering which temporary file backs each pipe -- 'Handle' handed out by 'mhsCreatePipe' or stream setup, so a later diff --git a/Cabal-syntax/src/Distribution/Compat/MhsInstances.hs b/mhs-compat-shims/src/Distribution/Compat/MhsInstances.hs similarity index 100% rename from Cabal-syntax/src/Distribution/Compat/MhsInstances.hs rename to mhs-compat-shims/src/Distribution/Compat/MhsInstances.hs diff --git a/mhs-compat-shims/src/Network/URI.hs b/mhs-compat-shims/src/Network/URI.hs new file mode 100644 index 00000000000..3406e2a2a80 --- /dev/null +++ b/mhs-compat-shims/src/Network/URI.hs @@ -0,0 +1,162 @@ +-- | Minimal @Network.URI@ shim for MicroHs (@mhs@). +-- +-- This is a small hand-written reimplementation (base-only, no parsec) +-- of the subset of the @network-uri@ API surface used by the cabal +-- codebase: the 'URI' and 'URIAuth' types with their record fields, +-- 'nullURI', 'nullURIAuth', 'parseURI', 'parseAbsoluteURI', +-- 'uriToString' and 'isUnreserved'. +-- +-- Parsing follows RFC 3986 loosely: @scheme \":\" hier-part [ \"?\" query ] +-- [ \"#\" fragment ]@. It is intentionally lenient about registry names +-- (e.g. Windows drive paths in @file@ URIs) and does not validate +-- percent-escapes the way @network-uri@ does. All call sites in the +-- repo pass @id@ as the escape function to 'uriToString', so escaping +-- behaviour is not load-bearing. +module Network.URI + ( URI (..) + , URIAuth (..) + , nullURI + , nullURIAuth + , parseURI + , parseAbsoluteURI + , uriToString + , isUnreserved + ) where + +import Data.Char (isAlpha, isAlphaNum, isDigit) + +-- | A Uniform Resource Identifier reference. +data URI = URI + { uriScheme :: String + , uriAuthority :: Maybe URIAuth + , uriPath :: String + , uriQuery :: String + , uriFragment :: String + } deriving (Eq) + +-- | Authority component of a 'URI'. +data URIAuth = URIAuth + { uriUserInfo :: String + , uriRegName :: String + , uriPort :: String + } deriving (Eq) + +-- | Show renders the URI in string form (as @network-uri@ does), +-- not record syntax: error messages and cache paths rely on this. +instance Show URI where + showsPrec _ u = showString (uriToString id u "") + +instance Show URIAuth where + showsPrec _ (URIAuth user reg port) = + showString (user ++ reg ++ port) + +-- | An empty URI value. +nullURI :: URI +nullURI = URI "" Nothing "" "" "" + +-- | An empty authority value. +nullURIAuth :: URIAuth +nullURIAuth = URIAuth "" "" "" + +-- | Characters that never need percent-encoding (RFC 3986 unreserved). +isUnreserved :: Char -> Bool +isUnreserved c = isAlphaNum c || c `elem` ("-_.~" :: String) + +-- | Render a URI. The first argument escapes @path@, @query@ and +-- @fragment@ (all call sites in the repo pass @id@). +uriToString :: (String -> String) -> URI -> String -> String +uriToString esc (URI scheme auth path query frag) rest = + scheme ++ authStr ++ esc path ++ esc query ++ esc frag ++ rest + where + authStr = case auth of + Nothing -> "" + Just (URIAuth user reg port) -> "//" ++ user ++ reg ++ port + +-- | Parse an absolute URI (a scheme is required). +parseURI :: String -> Maybe URI +parseURI s = do + (scheme, rest) <- splitScheme s + (auth, hier, query, frag) <- parseHier rest + return (URI scheme auth hier query frag) + +-- | Parse an absolute URI, rejecting relative references and fragments. +-- (Slightly stricter than 'parseURI'; same as @network-uri@, fragments +-- are not part of an absolute URI.) +parseAbsoluteURI :: String -> Maybe URI +parseAbsoluteURI s = do + u <- parseURI s + if null (uriFragment u) then Just u else Nothing + +-- Splits "scheme:rest", requiring a valid RFC 3986 scheme. +splitScheme :: String -> Maybe (String, String) +splitScheme s = case break (== ':') s of + (scheme, ':' : rest) + | validScheme scheme -> Just (scheme ++ ":", rest) + _ -> Nothing + where + validScheme (c : cs) = isAlpha c && all schemeChar cs + validScheme [] = False + schemeChar c = isAlphaNum c || c `elem` ("+-." :: String) + +-- Parses hier-part, query and fragment. Query keeps its leading '?', +-- fragment its leading '#', matching @network-uri@ field conventions. +parseHier :: String -> Maybe (Maybe URIAuth, String, String, String) +parseHier s = do + (auth, rest0) <- parseAuthorityPrefix s + let (hier, rest1) = break (`elem` ("?#" :: String)) rest0 + (query, frag) = parseQueryFrag rest1 + if validChars hier && validChars query && validChars frag + then Just (auth, hier, query, frag) + else Nothing + +parseAuthorityPrefix :: String -> Maybe (Maybe URIAuth, String) +parseAuthorityPrefix s + | "//" `isPrefixOf` s = + let (authStr, rest) = break (`elem` ("/?#" :: String)) (drop 2 s) + in case parseAuth authStr of + Just a -> Just (Just a, rest) + Nothing -> Nothing + | otherwise = Just (Nothing, s) + where + isPrefixOf pfx str = take (length pfx) str == pfx + +parseAuth :: String -> Maybe URIAuth +parseAuth s = do + let (user, hostport) = splitUserInfo s + (reg, port) = splitPort hostport + if validChars user && validChars reg && validPort port + then Just (URIAuth user reg port) + else Nothing + +-- Splits at the last '@'; user info keeps its trailing '@'. +splitUserInfo :: String -> (String, String) +splitUserInfo s = case break (== '@') (reverse s) of + (_, []) -> ("", s) + (revHost, _ : revUser) -> (reverse revUser ++ "@", reverse revHost) + +-- Splits reg-name and port; the port keeps its leading ':'. +splitPort :: String -> (String, String) +splitPort s = case break (== ':') (reverse s) of + (_, []) -> (s, "") + (revPort, _ : revReg) + | all isDigit (reverse revPort) -> (reverse revReg, ':' : reverse revPort) + | otherwise -> (s, "") + +validPort :: String -> Bool +validPort "" = True +validPort (':' : ds) = not (null ds) && all isDigit ds +validPort _ = False + +parseQueryFrag :: String -> (String, String) +parseQueryFrag s = case s of + ('?' : rest) -> + let (q, f) = break (== '#') rest + in ('?' : q, f) + ('#' : rest) -> ("", '#' : rest) + _ -> ("", "") + +-- Rejects spaces and control characters only; deliberately lenient +-- otherwise (e.g. backslashes in Windows file URIs are normalised +-- elsewhere in cabal by 'normaliseFileNoIndexURI'). +validChars :: String -> Bool +validChars = all (\c -> c > ' ' && c /= '\x7f') diff --git a/mhs-compat-shims/src/Text/PrettyPrint.hs b/mhs-compat-shims/src/Text/PrettyPrint.hs new file mode 100644 index 00000000000..51c4fe0418c --- /dev/null +++ b/mhs-compat-shims/src/Text/PrettyPrint.hs @@ -0,0 +1,570 @@ +-- | MicroHs-compatible subset of "Text.PrettyPrint" (HughesPJ). +-- +-- This module reimplements the HughesPJ pretty-printing combinators from +-- the Haskell @pretty@ package (version 1.1.3.6) in plain Haskell 2010, +-- restricted to the names used by @Cabal-syntax@ (see +-- @Distribution.Pretty@): 'Doc', 'Style', 'Mode', 'style', 'render', +-- 'renderStyle', 'text', 'char', 'int', 'integer', 'empty', 'isEmpty', +-- '(<>)', '(<+>)', '($$)', '($+$)', 'nest', 'sep', 'cat', 'fsep', 'hsep', +-- 'vcat', 'hcat', 'punctuate', 'comma', 'colon', 'semi', 'space', +-- 'parens', 'brackets', 'braces', 'quotes' and 'doubleQuotes'. +-- +-- The layout algorithm is the original one: a document describes a set of +-- layouts (via 'Union'), and rendering picks the widest fitting layout by +-- comparing each first line against the available space (page width and +-- ribbon derived from the 'Style'). 'PageMode' fits, 'LeftMode' renders +-- flat (ignoring line length, honouring explicit newlines) and +-- 'OneLineMode' renders everything on one line. +module Text.PrettyPrint + ( Doc + , Style (..) + , Mode (..) + , style + , render + , renderStyle + , text + , char + , int + , integer + , empty + , isEmpty + , (<>) + , (<+>) + , ($$) + , ($+$) + , nest + , sep + , cat + , fsep + , hsep + , vcat + , hcat + , punctuate + , comma + , colon + , semi + , space + , parens + , brackets + , braces + , quotes + , doubleQuotes + ) where + +import Prelude hiding ((<>)) +import qualified Data.Semigroup as Semi (Semigroup ((<>))) +import Data.String (IsString (..)) + +infixl 6 <> +infixl 6 <+> +infixl 5 $$, $+$ + +-- --------------------------------------------------------------------------- +-- The Doc data type +-- +-- A 'Doc' represents a /set/ of layouts. A 'Doc' with no 'Union' or 'NoDoc' +-- inside represents just one layout. 'Beside' and 'Above' are unreduced +-- compositions; 'reduceDoc' normalises them into the reduced constructors +-- ('Empty', 'NilAbove', 'TextBeside', 'Nest', 'Union', 'NoDoc'). + +data Doc + = Empty + | NilAbove Doc + | TextBeside String Int Doc + | Nest Int Doc + | Union Doc Doc + | NoDoc + | Beside Doc Bool Doc + | Above Doc Bool Doc + +-- | 'mappend' is '(<>)', 'mempty' is 'empty'. +instance Semi.Semigroup Doc where + (<>) = (Text.PrettyPrint.<>) + +instance Monoid Doc where + mempty = empty + mappend = (Semi.<>) + +instance IsString Doc where + fromString = text + +-- | Rendered comparison, as in the original. +instance Eq Doc where + p == q = render p == render q + +-- | Shows via the default 'style', as in the original. +instance Show Doc where + showsPrec _ doc rest = renderStyle style doc ++ rest + +-- --------------------------------------------------------------------------- +-- Rendering style + +-- | Rendering style: mode, maximum line length, and ribbon ratio. +data Style = Style + { mode :: Mode + , lineLength :: Int + , ribbonsPerLine :: Float + } + deriving (Eq, Show) + +-- | The default style (@mode=PageMode, lineLength=100, ribbonsPerLine=1.5@). +style :: Style +style = Style { mode = PageMode, lineLength = 100, ribbonsPerLine = 1.5 } + +-- | Rendering mode. +data Mode + = PageMode + | ZigZagMode + | LeftMode + | OneLineMode + deriving (Eq, Show) + +-- --------------------------------------------------------------------------- +-- Simple constructors and predicates + +-- | An empty document ('mempty'). +empty :: Doc +empty = Empty + +-- | True only for 'empty'. +isEmpty :: Doc -> Bool +isEmpty Empty = True +isEmpty _ = False + +-- | A document of height and width 1, containing a literal character. +char :: Char -> Doc +char c = TextBeside [c] 1 Empty + +-- | A document containing a string. The string is output verbatim. +text :: String -> Doc +text s = TextBeside s (length s) Empty + +-- | @int n = text (show n)@. +int :: Int -> Doc +int n = text (show n) + +-- | @integer n = text (show n)@. +integer :: Integer -> Doc +integer n = text (show n) + +-- | A ';' character. +semi :: Doc +semi = char ';' + +-- | A ',' character. +comma :: Doc +comma = char ',' + +-- | A ':' character. +colon :: Doc +colon = char ':' + +-- | A space character. +space :: Doc +space = char ' ' + +-- | Wrap a document in @(...)@. +parens :: Doc -> Doc +parens p = char '(' <> p <> char ')' + +-- | Wrap a document in @[...]@. +brackets :: Doc -> Doc +brackets p = char '[' <> p <> char ']' + +-- | Wrap a document in @{...}@. +braces :: Doc -> Doc +braces p = char '{' <> p <> char '}' + +-- | Wrap a document in @\'...\'@. +quotes :: Doc -> Doc +quotes p = char '\'' <> p <> char '\'' + +-- | Wrap a document in @\"...\"@. +doubleQuotes :: Doc -> Doc +doubleQuotes p = char '"' <> p <> char '"' + +-- | @punctuate p [d1, ... dn] = [d1 <> p, d2 <> p, ... dn-1 <> p, dn]@. +punctuate :: Doc -> [Doc] -> [Doc] +punctuate _ [] = [] +punctuate p (x : xs) = go x xs + where + go y [] = [y] + go y (z : zs) = (y <> p) : go z zs + +-- | Indent a document by the given number of positions. +nest :: Int -> Doc -> Doc +nest k p = mkNest k (reduceDoc p) + +-- --------------------------------------------------------------------------- +-- Structural operations + +-- | Simplify a built up 'Doc' into reduced form (no top-level +-- 'Beside' or 'Above'). +reduceDoc :: Doc -> Doc +reduceDoc (Beside p g q) = beside p g (reduceDoc q) +reduceDoc (Above p g q) = above p g (reduceDoc q) +reduceDoc p = p + +-- | List version of '(<>)'. +hcat :: [Doc] -> Doc +hcat = snd . reduceHoriz . foldr (\p q -> Beside p False q) empty + +-- | List version of '(<+>)'. +hsep :: [Doc] -> Doc +hsep = snd . reduceHoriz . foldr (\p q -> Beside p True q) empty + +-- | List version of '($$)'. +vcat :: [Doc] -> Doc +vcat = snd . reduceVert . foldr (\p q -> Above p False q) empty + +data IsEmpty = IsEmpty | NotEmpty + +reduceHoriz :: Doc -> (IsEmpty, Doc) +reduceHoriz (Beside p g q) = + eliminateEmpty Beside (snd (reduceHoriz p)) g (reduceHoriz q) +reduceHoriz doc = (NotEmpty, doc) + +reduceVert :: Doc -> (IsEmpty, Doc) +reduceVert (Above p g q) = + eliminateEmpty Above (snd (reduceVert p)) g (reduceVert q) +reduceVert doc = (NotEmpty, doc) + +eliminateEmpty :: + (Doc -> Bool -> Doc -> Doc) -> + Doc -> + Bool -> + (IsEmpty, Doc) -> + (IsEmpty, Doc) +eliminateEmpty _ Empty _ q = q +eliminateEmpty cons p g q = + ( NotEmpty, + case q of + (NotEmpty, q') -> cons p g q' + (IsEmpty, _) -> p + ) + +mkNest :: Int -> Doc -> Doc +mkNest k (Nest k1 p) = mkNest (k + k1) p +mkNest _ NoDoc = NoDoc +mkNest _ Empty = Empty +mkNest 0 p = p +mkNest k p = Nest k p + +mkUnion :: Doc -> Doc -> Doc +mkUnion Empty _ = Empty +mkUnion p q = p `union_` q + +nilAbove_ :: Doc -> Doc +nilAbove_ = NilAbove + +textBeside_ :: String -> Int -> Doc -> Doc +textBeside_ = TextBeside + +nest_ :: Int -> Doc -> Doc +nest_ = Nest + +union_ :: Doc -> Doc -> Doc +union_ = Union + +-- --------------------------------------------------------------------------- +-- Vertical composition + +-- | Above, with overlapping. @(x $$ y)@ puts @y@ below @x@. +($$) :: Doc -> Doc -> Doc +p $$ q = above_ p False q + +-- | Above, with no overlapping. +($+$) :: Doc -> Doc -> Doc +p $+$ q = above_ p True q + +above_ :: Doc -> Bool -> Doc -> Doc +above_ p _ Empty = p +above_ Empty _ q = q +above_ p g q = Above p g q + +above :: Doc -> Bool -> Doc -> Doc +above (Above p g1 q1) g2 q2 = above p g1 (above q1 g2 q2) +above p@(Beside _ _ _) g q = aboveNest (reduceDoc p) g 0 (reduceDoc q) +above p g q = aboveNest p g 0 (reduceDoc q) + +aboveNest :: Doc -> Bool -> Int -> Doc -> Doc +aboveNest NoDoc _ _ _ = NoDoc +aboveNest (p1 `Union` p2) g k q = + aboveNest p1 g k q `union_` aboveNest p2 g k q +aboveNest Empty _ k q = mkNest k q +aboveNest (Nest k1 p) g k q = nest_ k1 (aboveNest p g (k - k1) q) +aboveNest (NilAbove p) g k q = nilAbove_ (aboveNest p g k q) +aboveNest (TextBeside s l p) g k q = TextBeside s l rest + where + k1 = k - l + rest = case p of + Empty -> nilAboveNest g k1 q + _ -> aboveNest p g k1 q +aboveNest _ _ _ _ = error "aboveNest on unreduced Doc" + +-- Specification: @text s <> nilAboveNest g k q = text s <> (text "" $g$ nest k q)@. +nilAboveNest :: Bool -> Int -> Doc -> Doc +nilAboveNest _ _ Empty = Empty +nilAboveNest g k (Nest k1 q) = nilAboveNest g (k + k1) q +nilAboveNest g k q + | not g && k > 0 = textBeside_ (indent k) k q + | otherwise = nilAbove_ (mkNest k q) + +-- --------------------------------------------------------------------------- +-- Horizontal composition + +-- | Beside. '(<>)' is associative, with identity 'empty'. +(<>) :: Doc -> Doc -> Doc +p <> q = beside_ p False q + +-- | Beside, separated by space, unless one side is 'empty'. +(<+>) :: Doc -> Doc -> Doc +p <+> q = beside_ p True q + +beside_ :: Doc -> Bool -> Doc -> Doc +beside_ p _ Empty = p +beside_ Empty _ q = q +beside_ p g q = Beside p g q + +beside :: Doc -> Bool -> Doc -> Doc +beside NoDoc _ _ = NoDoc +beside (p1 `Union` p2) g q = beside p1 g q `union_` beside p2 g q +beside Empty _ q = q +beside (Nest k p) g q = nest_ k (beside p g q) +beside p@(Beside p1 g1 q1) g2 q2 + | g1 == g2 = beside p1 g1 (beside q1 g2 q2) + | otherwise = beside (reduceDoc p) g2 q2 +beside p@(Above _ _ _) g q = beside (reduceDoc p) g q +beside (NilAbove p) g q = nilAbove_ (beside p g q) +beside (TextBeside s l p) g q = TextBeside s l rest + where + rest = case p of + Empty -> nilBeside g q + _ -> beside p g q + +nilBeside :: Bool -> Doc -> Doc +nilBeside _ Empty = Empty +nilBeside g (Nest _ p) = nilBeside g p +nilBeside g p + | g = textBeside_ " " 1 p + | otherwise = p + +-- --------------------------------------------------------------------------- +-- Separate ('sep' and 'cat') + +-- Specification: @sep ps = oneLiner (hsep ps) `union` vcat ps@. +sep :: [Doc] -> Doc +sep = sepX True + +-- Specification: @cat ps = oneLiner (hcat ps) `union` vcat ps@. +cat :: [Doc] -> Doc +cat = sepX False + +sepX :: Bool -> [Doc] -> Doc +sepX _ [] = empty +sepX x (p : ps) = sep1 x (reduceDoc p) 0 ps + +sep1 :: Bool -> Doc -> Int -> [Doc] -> Doc +sep1 _ NoDoc _ _ = NoDoc +sep1 g (p `Union` q) k ys = + sep1 g p k ys `union_` aboveNest q False k (reduceDoc (vcat ys)) +sep1 g Empty k ys = mkNest k (sepX g ys) +sep1 g (Nest n p) k ys = nest_ n (sep1 g p (k - n) ys) +sep1 _ (NilAbove p) k ys = + nilAbove_ (aboveNest p False k (reduceDoc (vcat ys))) +sep1 g (TextBeside s l p) k ys = + textBeside_ s l (sepNB g p (k - l) ys) +sep1 _ _ _ _ = error "sep1 on unreduced Doc" + +sepNB :: Bool -> Doc -> Int -> [Doc] -> Doc +sepNB g (Nest _ p) k ys = sepNB g p k ys +sepNB g Empty k ys = + oneLiner (nilBeside g (reduceDoc rest)) + `mkUnion` nilAboveNest False k (reduceDoc (vcat ys)) + where + rest + | g = hsep ys + | otherwise = hcat ys +sepNB g p k ys = sep1 g p k ys + +-- --------------------------------------------------------------------------- +-- Fill ('fsep') + +-- | Paragraph-fill version of 'sep'. +fsep :: [Doc] -> Doc +fsep = fill True + +fill :: Bool -> [Doc] -> Doc +fill _ [] = empty +fill g (p : ps) = fill1 g (reduceDoc p) 0 ps + +fill1 :: Bool -> Doc -> Int -> [Doc] -> Doc +fill1 _ NoDoc _ _ = NoDoc +fill1 g (p `Union` q) k ys = + fill1 g p k ys `union_` aboveNest q False k (fill g ys) +fill1 g Empty k ys = mkNest k (fill g ys) +fill1 g (Nest n p) k ys = nest_ n (fill1 g p (k - n) ys) +fill1 g (NilAbove p) k ys = + nilAbove_ (aboveNest p False k (fill g ys)) +fill1 g (TextBeside s l p) k ys = + textBeside_ s l (fillNB g p (k - l) ys) +fill1 _ _ _ _ = error "fill1 on unreduced Doc" + +fillNB :: Bool -> Doc -> Int -> [Doc] -> Doc +fillNB g (Nest _ p) k ys = fillNB g p k ys +fillNB _ Empty _ [] = Empty +fillNB g Empty k (Empty : ys) = fillNB g Empty k ys +fillNB g Empty k (y : ys) = fillNBE g k y ys +fillNB g p k ys = fill1 g p k ys + +fillNBE :: Bool -> Int -> Doc -> [Doc] -> Doc +fillNBE g k y ys = + nilBeside g (fill1 g (elideNest (oneLiner (reduceDoc y))) k' ys) + `mkUnion` nilAboveNest False k (fill g (y : ys)) + where + k' + | g = k - 1 + | otherwise = k + +elideNest :: Doc -> Doc +elideNest (Nest _ d) = d +elideNest d = d + +-- | The one-line members of a set of layouts. +oneLiner :: Doc -> Doc +oneLiner NoDoc = NoDoc +oneLiner Empty = Empty +oneLiner (NilAbove _) = NoDoc +oneLiner (TextBeside s l p) = textBeside_ s l (oneLiner p) +oneLiner (Nest k p) = nest_ k (oneLiner p) +oneLiner (p `Union` _) = oneLiner p +oneLiner _ = error "oneLiner on unreduced Doc" + +-- | @first@ returns its first argument if it is non-empty, else its second. +first :: Doc -> Doc -> Doc +first p q + | nonEmptySet p = p + | otherwise = q + +nonEmptySet :: Doc -> Bool +nonEmptySet NoDoc = False +nonEmptySet (_ `Union` _) = True +nonEmptySet Empty = True +nonEmptySet (NilAbove _) = True +nonEmptySet (TextBeside _ _ p) = nonEmptySet p +nonEmptySet (Nest _ p) = nonEmptySet p +nonEmptySet _ = error "nonEmptySet on unreduced Doc" + +-- --------------------------------------------------------------------------- +-- Selecting the best layout + +-- | Choose the best rendering of a reduced document for the given line +-- length and ribbon length. The result contains no 'Union'. +best :: Int -> Int -> Doc -> Doc +best w0 r = get w0 + where + get _ Empty = Empty + get _ NoDoc = NoDoc + get w (NilAbove p) = nilAbove_ (get w p) + get w (TextBeside s l p) = textBeside_ s l (get1 w l p) + get w (Nest k p) = nest_ k (get (w - k) p) + get w (p `Union` q) = nicest w r (get w p) (get w q) + get _ _ = error "best: unreduced Doc" + + get1 _ _ Empty = Empty + get1 _ _ NoDoc = NoDoc + get1 w sl (NilAbove p) = nilAbove_ (get (w - sl) p) + get1 w sl (TextBeside s l p) = textBeside_ s l (get1 w (sl + l) p) + get1 w sl (Nest _ p) = get1 w sl p + get1 w sl (p `Union` q) = + nicest1 w r sl (get1 w sl p) (get1 w sl q) + get1 _ _ _ = error "best: unreduced Doc" + +nicest :: Int -> Int -> Doc -> Doc -> Doc +nicest w r = nicest1 w r 0 + +nicest1 :: Int -> Int -> Int -> Doc -> Doc -> Doc +nicest1 w r sl p q + | fits (min w r - sl) p = p + | otherwise = q + +-- | True if the first line of the document fits in the space available. +fits :: Int -> Doc -> Bool +fits n _ | n < 0 = False +fits _ NoDoc = False +fits _ Empty = True +fits _ (NilAbove _) = True +fits n (TextBeside _ l p) = fits (n - l) p +fits _ _ = error "fits on unreduced Doc" + +-- --------------------------------------------------------------------------- +-- Rendering + +-- | Render a document with the default 'style'. +render :: Doc -> String +render = fullRender (mode style) (lineLength style) (ribbonsPerLine style) + +-- | Render a document with a given style. +renderStyle :: Style -> Doc -> String +renderStyle s = fullRender (mode s) (lineLength s) (ribbonsPerLine s) + +fullRender :: Mode -> Int -> Float -> Doc -> String +fullRender OneLineMode _ _ doc = easyDisplay " " first (reduceDoc doc) +fullRender LeftMode _ _ doc = easyDisplay "\n" first (reduceDoc doc) +fullRender m lineLen ribbons doc = display m lineLen ribbonLen doc' + where + doc' = best bestLineLen ribbonLen (reduceDoc doc) + ribbonLen :: Int + ribbonLen = round (fromIntegral lineLen / ribbons) + bestLineLen :: Int + bestLineLen = case m of + ZigZagMode -> maxBound + _ -> lineLen + +-- | Simple rendering for 'LeftMode' and 'OneLineMode': no fitting, breaks +-- become the given separator. +easyDisplay :: String -> (Doc -> Doc -> Doc) -> Doc -> String +easyDisplay nl choose = lay + where + lay NoDoc = error "easyDisplay: NoDoc" + lay (Union p q) = lay (choose p q) + lay (Nest _ p) = lay p + lay Empty = "" + lay (NilAbove p) = nl ++ lay p + lay (TextBeside s _ p) = s ++ lay p + lay _ = error "easyDisplay on unreduced Doc" + +display :: Mode -> Int -> Int -> Doc -> String +display m pageWidth ribbonWidth doc = + case pageWidth - ribbonWidth of + gapWidth -> + case gapWidth `quot` 2 of + shift -> + let lay k (Nest k1 p) = lay (k + k1) p + lay _ Empty = "" + lay k (NilAbove p) = '\n' : lay k p + lay k (TextBeside s l p) = + case m of + ZigZagMode + | k >= gapWidth -> + '\n' + : ( replicate shift '/' + ++ ('\n' : lay1 (k - shift) s l p) + ) + | k < 0 -> + '\n' + : ( replicate shift '\\' + ++ ('\n' : lay1 (k + shift) s l p) + ) + _ -> lay1 k s l p + lay _ _ = error "display: unreduced Doc" + lay1 k s l p = indent k ++ s ++ lay2 (k + l) p + lay2 k (NilAbove p) = '\n' : lay k p + lay2 k (TextBeside s l p) = s ++ lay2 (k + l) p + lay2 k (Nest _ p) = lay2 k p + lay2 _ Empty = "" + lay2 _ _ = error "display: unreduced Doc" + in lay 0 doc + +indent :: Int -> String +indent n = replicate n ' ' diff --git a/templates/SPDX.LicenseExceptionId.template.hs b/templates/SPDX.LicenseExceptionId.template.hs index 7b355aeac24..52002420a71 100644 --- a/templates/SPDX.LicenseExceptionId.template.hs +++ b/templates/SPDX.LicenseExceptionId.template.hs @@ -15,7 +15,7 @@ import Distribution.Compat.Lens (set) import Distribution.Pretty import Distribution.Parsec import Distribution.Utils.Generic (isAsciiAlphaNum) -import Distribution.Utils.Structured (Structured (..), nominalStructure, typeVersion) +import Distribution.Utils.Structured (nominalStructure, typeVersion) import Distribution.SPDX.LicenseListVersion import qualified Data.Binary.Get as Binary diff --git a/templates/SPDX.LicenseId.template.hs b/templates/SPDX.LicenseId.template.hs index d98426ac188..9bdf35ad9a2 100644 --- a/templates/SPDX.LicenseId.template.hs +++ b/templates/SPDX.LicenseId.template.hs @@ -19,7 +19,7 @@ import Distribution.Compat.Lens (set) import Distribution.Pretty import Distribution.Parsec import Distribution.Utils.Generic (isAsciiAlphaNum) -import Distribution.Utils.Structured (Structured (..), nominalStructure, typeVersion) +import Distribution.Utils.Structured (nominalStructure, typeVersion) import Distribution.SPDX.LicenseListVersion import qualified Data.Binary.Get as Binary From 5c41b1f443eae44dbc0f8f67a7b67824d7f912d6 Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 15:33:15 +0900 Subject: [PATCH 03/17] Cabal: type captureProcess input staging as IO () Validate builds with -Werror. The local stage action discarded a polymorphic put result, so -Wunused-do-bind failed Cabal-3.19 on every GHC validate job and the Alpine static build. --- Cabal/src/Distribution/Compat/Process.hs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Cabal/src/Distribution/Compat/Process.hs b/Cabal/src/Distribution/Compat/Process.hs index bff617aa94e..8964234bfe3 100644 --- a/Cabal/src/Distribution/Compat/Process.hs +++ b/Cabal/src/Distribution/Compat/Process.hs @@ -385,7 +385,7 @@ module Distribution.Compat.Process import qualified Data.ByteString.Lazy as LBS import System.Directory (getTemporaryDirectory, removeFile) import System.Exit (ExitCode (..)) -import System.IO (IOMode (..), hClose, hPutStr, openFile, openTempFile) +import System.IO (Handle, IOMode (..), hClose, hPutStr, openFile, openTempFile) import System.Process hiding (proc) import qualified System.Process as Process @@ -463,7 +463,10 @@ data CapturedOutputs = CapturedOutputs captureProcess :: CreateProcess -> StagedInput -> IO (ExitCode, CapturedOutputs) captureProcess cp staged = do tmpDir <- getTemporaryDirectory - let stage put = do + -- `put` must return IO (). A polymorphic result is discarded here, and + -- validate builds with -Werror, so -Wunused-do-bind rejects it. + let stage :: (Handle -> IO ()) -> IO (StdStream, FilePath) + stage put = do (p, h) <- openTempFile tmpDir "cabal-captured-in" put h hClose h From 1733a7d68ce2d68fc037727ce1646c6e2eb79f0f Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 16:01:56 +0900 Subject: [PATCH 04/17] Cabal: fix validate -Werror left by the MicroHs graft Export the target-name helpers, drop two unused LogProgress imports, and restore the Windows createTempDirectory path. The graft called System.Posix.createDirectory on every non-MHS platform. --- Cabal/src/Distribution/Backpack/DescribeUnitId.hs | 1 - Cabal/src/Distribution/Backpack/UnifyM.hs | 1 - Cabal/src/Distribution/Compat/Internal/TempFile.hs | 6 ++++++ Cabal/src/Distribution/Simple/Compiler.hs | 7 +++++++ 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Cabal/src/Distribution/Backpack/DescribeUnitId.hs b/Cabal/src/Distribution/Backpack/DescribeUnitId.hs index ce88c62b8c7..9f6ce4a8ac2 100644 --- a/Cabal/src/Distribution/Backpack/DescribeUnitId.hs +++ b/Cabal/src/Distribution/Backpack/DescribeUnitId.hs @@ -9,7 +9,6 @@ import Distribution.Pretty import Distribution.Simple.Utils import Distribution.Types.ComponentName import Distribution.Types.PackageId -import Distribution.Utils.LogProgress import Distribution.Verbosity import Text.PrettyPrint diff --git a/Cabal/src/Distribution/Backpack/UnifyM.hs b/Cabal/src/Distribution/Backpack/UnifyM.hs index 801800039ce..45bc0654abd 100644 --- a/Cabal/src/Distribution/Backpack/UnifyM.hs +++ b/Cabal/src/Distribution/Backpack/UnifyM.hs @@ -58,7 +58,6 @@ import qualified Data.IntMap as IntMap import qualified Data.Map as Map import Data.STRef import qualified Data.Set as Set -import Distribution.Utils.LogProgress import Text.PrettyPrint -- TODO: more detailed trace output on high verbosity would probably diff --git a/Cabal/src/Distribution/Compat/Internal/TempFile.hs b/Cabal/src/Distribution/Compat/Internal/TempFile.hs index 15b3b3a96c0..0d629f1d8ac 100644 --- a/Cabal/src/Distribution/Compat/Internal/TempFile.hs +++ b/Cabal/src/Distribution/Compat/Internal/TempFile.hs @@ -44,8 +44,12 @@ import Distribution.Compat.Directory ) #else import System.Posix.Internals (c_getpid) +#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS) +import System.Directory (createDirectory) +#else import qualified System.Posix #endif +#endif openNewBinaryFile :: FilePath -> String -> IO (FilePath, Handle) #ifdef __MHS__ @@ -133,6 +137,8 @@ mkPrivateDir s = do if created then pure () else ioError (mkIOError alreadyExistsErrorType "createDirectory" Nothing (Just s)) +#elif defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS) +mkPrivateDir s = createDirectory s #else mkPrivateDir s = System.Posix.createDirectory s 0o700 #endif diff --git a/Cabal/src/Distribution/Simple/Compiler.hs b/Cabal/src/Distribution/Simple/Compiler.hs index ecf9ec8ecf9..e041ad7e872 100644 --- a/Cabal/src/Distribution/Simple/Compiler.hs +++ b/Cabal/src/Distribution/Simple/Compiler.hs @@ -29,6 +29,12 @@ module Distribution.Simple.Compiler , compilerCompatFlavor , compilerCompatVersion , compilerInfo + , compilerTargetAbi + , compilerTargetName + , compilerTargetsProfiling + , TargetName + , parseTargetName + , renderTargetName -- * Support for package databases , PackageDB @@ -74,6 +80,7 @@ module Distribution.Simple.Compiler , profilingDynamicSupportedOrUnknown , profilingVanillaSupported , profilingVanillaSupportedOrUnknown + , profilingDebugSupported , dynamicSupported , bytecodeArtifactsSupported , backpackSupported From ee2233234b4e128427f55fe8388f59173af23fdd Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 16:19:17 +0900 Subject: [PATCH 05/17] Cabal: keep MicroHs hang and drop GHC-redundant imports LogProgress.hang exists only under __MHS__, because MicroHs pretty has no hang. Import it only there. Compat.Prelude already exports Exception, when, and unless, so the extra imports failed -Werror. --- Cabal/src/Distribution/Backpack/ComponentsGraph.hs | 6 +++++- Cabal/src/Distribution/Backpack/DescribeUnitId.hs | 5 +++++ Cabal/src/Distribution/Backpack/MixLink.hs | 5 ++++- Cabal/src/Distribution/Backpack/ReadyComponent.hs | 6 +++++- Cabal/src/Distribution/Backpack/UnifyM.hs | 5 +++++ Cabal/src/Distribution/PackageDescription/Check.hs | 3 +-- Cabal/src/Distribution/Simple/GHC/Build/Link.hs | 1 - Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs | 3 --- 8 files changed, 25 insertions(+), 9 deletions(-) diff --git a/Cabal/src/Distribution/Backpack/ComponentsGraph.hs b/Cabal/src/Distribution/Backpack/ComponentsGraph.hs index 93729ece6d1..f8f04e9ae87 100644 --- a/Cabal/src/Distribution/Backpack/ComponentsGraph.hs +++ b/Cabal/src/Distribution/Backpack/ComponentsGraph.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + -- | See module Distribution.Backpack.ComponentsGraph ( ComponentsGraph @@ -22,8 +24,10 @@ import Distribution.Types.ComponentRequestedSpec import Distribution.Utils.Generic import Distribution.Pretty (pretty) -import Distribution.Utils.LogProgress import Text.PrettyPrint +#ifdef __MHS__ +import Distribution.Utils.LogProgress (hang) +#endif ------------------------------------------------------------------------------ -- Components graph diff --git a/Cabal/src/Distribution/Backpack/DescribeUnitId.hs b/Cabal/src/Distribution/Backpack/DescribeUnitId.hs index 9f6ce4a8ac2..3a96cf9e128 100644 --- a/Cabal/src/Distribution/Backpack/DescribeUnitId.hs +++ b/Cabal/src/Distribution/Backpack/DescribeUnitId.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + module Distribution.Backpack.DescribeUnitId where import Distribution.Compat.Prelude @@ -12,6 +14,9 @@ import Distribution.Types.PackageId import Distribution.Verbosity import Text.PrettyPrint +#ifdef __MHS__ +import Distribution.Utils.LogProgress (hang) +#endif -- Unit identifiers have a well defined, machine-readable format, -- but this format isn't very user-friendly for users. This diff --git a/Cabal/src/Distribution/Backpack/MixLink.hs b/Cabal/src/Distribution/Backpack/MixLink.hs index e7d18c2278d..f20fee7b566 100644 --- a/Cabal/src/Distribution/Backpack/MixLink.hs +++ b/Cabal/src/Distribution/Backpack/MixLink.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# LANGUAGE NondecreasingIndentation #-} -- | See @@ -21,8 +22,10 @@ import qualified Distribution.Utils.UnionFind as UnionFind import Control.Monad hiding (mapM, sequence) import qualified Data.Foldable as F import qualified Data.Map as Map -import Distribution.Utils.LogProgress import Text.PrettyPrint +#ifdef __MHS__ +import Distribution.Utils.LogProgress (hang) +#endif ----------------------------------------------------------------------- -- Linking diff --git a/Cabal/src/Distribution/Backpack/ReadyComponent.hs b/Cabal/src/Distribution/Backpack/ReadyComponent.hs index 7912a6679c9..fe9747abd5f 100644 --- a/Cabal/src/Distribution/Backpack/ReadyComponent.hs +++ b/Cabal/src/Distribution/Backpack/ReadyComponent.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + -- | See module Distribution.Backpack.ReadyComponent ( ReadyComponent (..) @@ -40,8 +42,10 @@ import Distribution.Simple.Utils import Control.Monad hiding (mapM, sequence) import qualified Data.Map as Map import qualified Data.Set as Set -import Distribution.Utils.LogProgress import Text.PrettyPrint +#ifdef __MHS__ +import Distribution.Utils.LogProgress (hang) +#endif import Distribution.Pretty import Distribution.Version diff --git a/Cabal/src/Distribution/Backpack/UnifyM.hs b/Cabal/src/Distribution/Backpack/UnifyM.hs index 45bc0654abd..6933111de6d 100644 --- a/Cabal/src/Distribution/Backpack/UnifyM.hs +++ b/Cabal/src/Distribution/Backpack/UnifyM.hs @@ -1,3 +1,5 @@ +{-# LANGUAGE CPP #-} + -- | See module Distribution.Backpack.UnifyM ( -- * Unification monad @@ -59,6 +61,9 @@ import qualified Data.Map as Map import Data.STRef import qualified Data.Set as Set import Text.PrettyPrint +#ifdef __MHS__ +import Distribution.Utils.LogProgress (hang) +#endif -- TODO: more detailed trace output on high verbosity would probably -- be appreciated by users debugging unification errors. Collect diff --git a/Cabal/src/Distribution/PackageDescription/Check.hs b/Cabal/src/Distribution/PackageDescription/Check.hs index 293c8426b76..f7c4a7e4ab7 100644 --- a/Cabal/src/Distribution/PackageDescription/Check.hs +++ b/Cabal/src/Distribution/PackageDescription/Check.hs @@ -93,8 +93,7 @@ import qualified Distribution.Compat.Lens as L import qualified Distribution.Types.BuildInfo.Lens as L import qualified Distribution.Types.GenericPackageDescription.Lens as L -import Control.Monad hiding (forM_, mapM, mapM_, sequence, sequence_) -import Data.Foldable (forM_, mapM_, sequence_) +import Data.Foldable (mapM_) -- $setup -- >>> import Control.Arrow ((&&&)) diff --git a/Cabal/src/Distribution/Simple/GHC/Build/Link.hs b/Cabal/src/Distribution/Simple/GHC/Build/Link.hs index a0db903be07..1ffae0cf0cc 100644 --- a/Cabal/src/Distribution/Simple/GHC/Build/Link.hs +++ b/Cabal/src/Distribution/Simple/GHC/Build/Link.hs @@ -5,7 +5,6 @@ module Distribution.Simple.GHC.Build.Link where import Distribution.Compat.Prelude import Prelude () -import Control.Monad hiding (mapM, sequence) import Control.Monad.IO.Class import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.Set as Set diff --git a/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs b/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs index 33827275917..8307ef71aeb 100644 --- a/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs +++ b/Cabal/src/Distribution/Simple/SetupHooks/HooksMain.hs @@ -29,9 +29,6 @@ module Distribution.Simple.SetupHooks.HooksMain -- base -import Control.Exception - ( Exception (..) - ) import Control.Monad ( (>=>) ) From ebdd9d9d5d9372709e935bc06530d36727f0e12e Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 16:35:27 +0900 Subject: [PATCH 06/17] Cabal: drop unused FileOrDir(..) imports GHC 9.14 rejects FileOrDir(..) under -Werror. The empty compatibility datatype has no constructors, and neither hooks module uses the name. --- Cabal-hooks/src/Distribution/Simple/SetupHooks.hs | 2 +- hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cabal-hooks/src/Distribution/Simple/SetupHooks.hs b/Cabal-hooks/src/Distribution/Simple/SetupHooks.hs index f86a79f235a..c2a15835b4f 100644 --- a/Cabal-hooks/src/Distribution/Simple/SetupHooks.hs +++ b/Cabal-hooks/src/Distribution/Simple/SetupHooks.hs @@ -302,7 +302,7 @@ import Distribution.Types.LocalBuildConfig import Distribution.Types.TargetInfo ( TargetInfo(..) ) import Distribution.Utils.Path - ( SymbolicPath, CWD, Pkg, FileOrDir(..), Dir + ( SymbolicPath, CWD, Pkg, Dir , interpretSymbolicPath, makeRelativePathEx , RelativePath, Source, Build , getSymbolicPath, sameDirectory, moduleNameSymbolicPath diff --git a/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs b/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs index b7574561cd2..1a3d281b435 100644 --- a/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs +++ b/hooks-exe/cli/Distribution/Client/SetupHooks/CallHooksExe.hs @@ -60,7 +60,7 @@ import Distribution.Utils.Path , Dist , Pkg , SymbolicPath - , FileOrDir(..), Dir + , Dir , interpretSymbolicPath ) import Distribution.Verbosity From a9c74bb5c4059718e2d3ba5c590902174bc41e34 Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 16:58:06 +0900 Subject: [PATCH 07/17] Cabal-tests: drop unused directory and process dependencies The test library and custom-setup-tests import Compat.Directory and Compat.Process, not the directory or process packages. GHC 9.6 -Wunused-packages rejects those direct dependencies. --- Cabal-tests/Cabal-tests.cabal | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Cabal-tests/Cabal-tests.cabal b/Cabal-tests/Cabal-tests.cabal index 37ce8bfe322..4b1c87ddd8a 100644 --- a/Cabal-tests/Cabal-tests.cabal +++ b/Cabal-tests/Cabal-tests.cabal @@ -22,7 +22,7 @@ source-repository head library hs-source-dirs: lib exposed-modules: Test.Utils.TempTestDir - build-depends: base, directory, Cabal, filepath, exceptions + build-depends: base, Cabal, filepath, exceptions -- Small, fast running tests. test-suite unit-tests @@ -135,9 +135,7 @@ test-suite custom-setup-tests , base , Cabal , Cabal-syntax - , directory , filepath - , process , text default-language: GHC2021 From e8c5d0e8e745771f2e551f2442d543247e7a79a6 Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 17:34:42 +0900 Subject: [PATCH 08/17] Cabal: drop directory deps that only use Compat.Directory cabal-install-solver and several test suites import Distribution.Compat.Directory, not the directory package. GHC -Wunused-packages rejects the direct dependency. integration-tests2 likewise only uses Compat.Process. --- Cabal-tests/Cabal-tests.cabal | 3 --- cabal-install-solver/cabal-install-solver.cabal | 1 - cabal-install/cabal-install.cabal | 5 ----- 3 files changed, 9 deletions(-) diff --git a/Cabal-tests/Cabal-tests.cabal b/Cabal-tests/Cabal-tests.cabal index 4b1c87ddd8a..f5af2e72e7d 100644 --- a/Cabal-tests/Cabal-tests.cabal +++ b/Cabal-tests/Cabal-tests.cabal @@ -95,7 +95,6 @@ test-suite parser-tests , Cabal-syntax , Cabal-tree-diff , Diff >=0.4 && <2.1 - , directory , filepath , tasty >=1.2.3 && <1.6 , tasty-golden >=2.3.1.1 && <2.4 @@ -115,7 +114,6 @@ test-suite check-tests , Cabal , Cabal-syntax , Diff >=0.4 && <2.1 - , directory , filepath , tasty >=1.2.3 && <1.6 , tasty-golden >=2.3.1.1 && <2.4 @@ -153,7 +151,6 @@ test-suite hackage-tests , Cabal-syntax , Cabal-tree-diff , deepseq >= 1.4 - , directory , filepath , time diff --git a/cabal-install-solver/cabal-install-solver.cabal b/cabal-install-solver/cabal-install-solver.cabal index e6d91931757..f15306beb52 100644 --- a/cabal-install-solver/cabal-install-solver.cabal +++ b/cabal-install-solver/cabal-install-solver.cabal @@ -110,7 +110,6 @@ library , Cabal ^>=3.19 , Cabal-syntax ^>=3.19 , containers >=0.5.6.2 && <0.9 - , directory >= 1.3.8.5 && < 1.4 , filepath >= 1.4.301 && < 1.6 , mtl >=2.0 && <2.4 , transformers >=0.4.2.0 && <0.7 diff --git a/cabal-install/cabal-install.cabal b/cabal-install/cabal-install.cabal index 839ffc0aa08..391f711331a 100644 --- a/cabal-install/cabal-install.cabal +++ b/cabal-install/cabal-install.cabal @@ -387,7 +387,6 @@ test-suite unit-tests , Cabal-QuickCheck , Cabal-tests , containers - , directory , filepath , mtl , network-uri >= 2.6.2.0 && <2.7 @@ -418,7 +417,6 @@ test-suite parser-tests build-depends: , cabal-install , containers - , directory , filepath , network-uri >= 2.6.2.0 && <2.7 , tasty >= 1.2.3 && <1.6 @@ -470,9 +468,7 @@ test-suite integration-tests2 , bytestring , cabal-install , containers - , directory , filepath - , process , tasty >= 1.5.4 && <1.6 , tasty-hunit >= 0.10 , tasty-expected-failure @@ -506,7 +502,6 @@ test-suite long-tests , Cabal-tests , cabal-install , containers - , directory , filepath , mtl , network-uri >= 2.6.2.0 && <2.7 From 8d0f386d9673cf03ec6be6efe4b11665617a09ea Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 18:04:48 +0900 Subject: [PATCH 09/17] Cabal: drop solver imports the prelude already provides Validate -Werror rejected three cabal-install-solver imports. Machine.hs kept the standard Prelude in scope, so Data.Foldable (Foldable) was unused on GHC. Hide that Prelude, as the other solver modules do, so deriving Foldable still sees the class on GHC and MicroHs. OptionalStanza imported Structured, which Compat.Prelude already exports. nominalStructure stays. PkgConfigDb imported mapM, which Traversable(..) from the prelude already provides. --- cabal-install-solver/src/Distribution/Solver/Types/Machine.hs | 1 + .../src/Distribution/Solver/Types/OptionalStanza.hs | 2 +- .../src/Distribution/Solver/Types/PkgConfigDb.hs | 3 --- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/cabal-install-solver/src/Distribution/Solver/Types/Machine.hs b/cabal-install-solver/src/Distribution/Solver/Types/Machine.hs index 45349772459..e8f942e995e 100644 --- a/cabal-install-solver/src/Distribution/Solver/Types/Machine.hs +++ b/cabal-install-solver/src/Distribution/Solver/Types/Machine.hs @@ -16,6 +16,7 @@ module Distribution.Solver.Types.Machine import Data.Foldable (Foldable) import Distribution.Compat.Prelude +import Prelude () -- | The machine whose toolchain a package is compiled with. -- diff --git a/cabal-install-solver/src/Distribution/Solver/Types/OptionalStanza.hs b/cabal-install-solver/src/Distribution/Solver/Types/OptionalStanza.hs index c1261fb26a4..6f3e9fd6b14 100644 --- a/cabal-install-solver/src/Distribution/Solver/Types/OptionalStanza.hs +++ b/cabal-install-solver/src/Distribution/Solver/Types/OptionalStanza.hs @@ -27,7 +27,7 @@ import Prelude () import Data.Bits (testBit, (.|.), (.&.)) import Distribution.Types.ComponentRequestedSpec (ComponentRequestedSpec (..)) -import Distribution.Utils.Structured (Structured (..), nominalStructure) +import Distribution.Utils.Structured (nominalStructure) ------------------------------------------------------------------------------- -- OptionalStanza diff --git a/cabal-install-solver/src/Distribution/Solver/Types/PkgConfigDb.hs b/cabal-install-solver/src/Distribution/Solver/Types/PkgConfigDb.hs index d412e80c5e8..8ba28b267be 100644 --- a/cabal-install-solver/src/Distribution/Solver/Types/PkgConfigDb.hs +++ b/cabal-install-solver/src/Distribution/Solver/Types/PkgConfigDb.hs @@ -21,9 +21,6 @@ import Distribution.Solver.Compat.Prelude import Prelude () import Control.Exception (handle) -#ifndef __MHS__ -import Control.Monad (mapM) -#endif import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as LBS import qualified Data.Map as M From 5ddda20f78ec1651691c3ddd424b60a786a6cecd Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 19:47:40 +0900 Subject: [PATCH 10/17] Cabal: drop unused imports and deps validate rejects GHC 9.8.4 with cabal.validate.project (-Werror) failed the cabal-install library, Cabal-tests, cabal-validate, and solver-benchmarks. Compat.Prelude already exports the names those imports repeated. FileOrDir is an empty datatype, so FileOrDir(..) is unused. directory and process are unused where the code only imports Compat.Directory and Compat.Process. The external setup runner now covers InLibraryArgs so -Wincomplete-patterns is satisfied. --- Cabal-tests/Cabal-tests.cabal | 7 ++++--- .../UnitTests/Distribution/Compat/Directory.hs | 1 - .../UnitTests/Distribution/Compat/Graph.hs | 18 +++++++++--------- .../UnitTests/Distribution/Compat/Prelude.hs | 4 ++++ .../tests/UnitTests/Distribution/SPDX.hs | 2 +- cabal-install/cabal-install.cabal | 1 - .../Distribution/Client/CmdHaddockProject.hs | 2 +- .../src/Distribution/Client/CmdOutdated.hs | 1 - .../src/Distribution/Client/FileMonitor.hs | 2 -- .../src/Distribution/Client/GlobalFlags.hs | 1 - .../src/Distribution/Client/HashValue.hs | 2 ++ .../src/Distribution/Client/IndexUtils.hs | 2 +- .../src/Distribution/Client/InstallPlan.hs | 2 +- .../Client/ProjectBuilding/UnpackedPackage.hs | 4 ++-- .../src/Distribution/Client/ProjectConfig.hs | 1 - .../src/Distribution/Client/ProjectPlanning.hs | 3 +-- .../src/Distribution/Client/SetupWrapper.hs | 5 +++++ cabal-install/src/Distribution/Client/Utils.hs | 1 - cabal-testsuite/src/Test/Cabal/Workdir.hs | 1 - cabal-validate/cabal-validate.cabal | 1 - solver-benchmarks/solver-benchmarks.cabal | 2 -- 21 files changed, 31 insertions(+), 32 deletions(-) diff --git a/Cabal-tests/Cabal-tests.cabal b/Cabal-tests/Cabal-tests.cabal index f5af2e72e7d..ec98473c8f7 100644 --- a/Cabal-tests/Cabal-tests.cabal +++ b/Cabal-tests/Cabal-tests.cabal @@ -68,10 +68,8 @@ test-suite unit-tests , Cabal-QuickCheck , containers , Diff >=0.4 && <2.1 - , directory >=1.2.7 , filepath , pretty - , process , QuickCheck >=2.14 && <2.20 , tasty >=1.2.3 && <1.6 , tasty-hunit @@ -80,7 +78,10 @@ test-suite unit-tests , text if !os(windows) - build-depends: unix + build-depends: + , directory >=1.2.7 + , process + , unix ghc-options: -Wall default-language: GHC2021 diff --git a/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs b/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs index bbd5de675f2..a4dbd88eba9 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs @@ -1,7 +1,6 @@ module UnitTests.Distribution.Compat.Directory (tests) where import Control.Exception (IOException, try) -import System.Directory (doesDirectoryExist, doesFileExist) import System.FilePath ((), isAbsolute) import System.IO.Error (isAlreadyExistsError) diff --git a/Cabal-tests/tests/UnitTests/Distribution/Compat/Graph.hs b/Cabal-tests/tests/UnitTests/Distribution/Compat/Graph.hs index 4e2a853fa5d..2c20511882b 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/Compat/Graph.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/Compat/Graph.hs @@ -7,7 +7,7 @@ module UnitTests.Distribution.Compat.Graph import Distribution.Compat.Graph import qualified Prelude -import Prelude hiding (null) +import Prelude hiding (lookup, null) import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck @@ -19,6 +19,7 @@ import Data.Array ((!)) import Data.Maybe import Data.List (sort) import Data.Proxy (Proxy (..)) +import Data.Typeable (Typeable) import Distribution.Utils.Structured (Structure (Nominal), Structured (..), nominalStructure) tests :: [TestTree] @@ -175,8 +176,8 @@ keyParamTests = -- every topological order starts with 1 and ends with 3. let sorted = map nodeKey (topSort keyGraph) sort sorted @?= [TKey 1, TKey 2, TKey 3] - head sorted @?= TKey 1 - last sorted @?= TKey 3 + take 1 sorted @?= [TKey 1] + drop (length sorted - 1) sorted @?= [TKey 3] sort (map nodeKey (revTopSort keyGraph)) @?= [TKey 1, TKey 2, TKey 3] cycles keyGraph @?= [] , testCase "broken" $ do @@ -195,7 +196,7 @@ newtype TKey = TKey Int deriving (Eq, Ord, Show) data TNode = TNode TKey [TKey] - deriving (Eq, Show) + deriving (Eq, Ord, Show) instance IsNode TKey TNode where nodeKey (TNode k _) = k @@ -204,11 +205,10 @@ instance IsNode TKey TNode where instance Structured TNode where structure = nominalStructure --- | The 'Structured' instance for 'Graph' must stay usable with only --- 'Structured a' in scope (no 'Typeable k'), so that generically --- derived plan types keep compiling. This helper only typechecks --- while the instance head is weak enough. -graphStructureOf :: Structured a => Proxy (Graph k a) -> Structure +-- | Pin the 'Structured' instance context. 'Structured' has a 'Typeable' +-- superclass, so 'Structured (Graph k a)' needs 'Typeable k' as well as +-- 'Structured a'. 'structure' itself tags the node list, not @k@. +graphStructureOf :: (Typeable k, Structured a) => Proxy (Graph k a) -> Structure graphStructureOf = structure prop_structure_tag :: Bool diff --git a/Cabal-tests/tests/UnitTests/Distribution/Compat/Prelude.hs b/Cabal-tests/tests/UnitTests/Distribution/Compat/Prelude.hs index 8b045a01a86..720aa2c8a67 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/Compat/Prelude.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/Compat/Prelude.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -Wno-orphans #-} module UnitTests.Distribution.Compat.Prelude ( tests @@ -16,8 +17,11 @@ import qualified Data.List.NonEmpty as NE import Test.Tasty import Test.Tasty.QuickCheck +-- QuickCheck 2.17 added 'Arbitrary' for most of 'base', including 'NonEmpty'. +#if !MIN_VERSION_QuickCheck(2,17,0) instance Arbitrary a => Arbitrary (NE.NonEmpty a) where arbitrary = (NE.:|) <$> arbitrary <*> arbitrary +#endif tests :: [TestTree] tests = diff --git a/Cabal-tests/tests/UnitTests/Distribution/SPDX.hs b/Cabal-tests/tests/UnitTests/Distribution/SPDX.hs index 601a2623436..e6fd6fbb0e9 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/SPDX.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/SPDX.hs @@ -2,7 +2,6 @@ module UnitTests.Distribution.SPDX (spdxTests) where import Data.Data (fromConstr, toConstr) -import Data.List (sort) import Distribution.Compat.Prelude.Internal import Prelude () @@ -11,6 +10,7 @@ import Distribution.Parsec (eitherParsec) import Distribution.Pretty (prettyShow) import Test.Tasty +import Test.Tasty.HUnit (Assertion, assertEqual, testCase) import Test.Tasty.QuickCheck import Test.QuickCheck.Instances.Cabal () diff --git a/cabal-install/cabal-install.cabal b/cabal-install/cabal-install.cabal index 391f711331a..5150c2652a0 100644 --- a/cabal-install/cabal-install.cabal +++ b/cabal-install/cabal-install.cabal @@ -255,7 +255,6 @@ library , filepath >= 1.4.301 && < 1.6 , hooks-exe ^>= 3.19 , mtl >= 2.0 && < 2.4 - , process >= 1.6.29.0 && < 1.7 , stm >= 2.0 && < 2.6 , time >= 1.5.0.1 && < 1.17 , text >= 1.2.3 && < 1.3 || >= 2.0 && < 2.2 diff --git a/cabal-install/src/Distribution/Client/CmdHaddockProject.hs b/cabal-install/src/Distribution/Client/CmdHaddockProject.hs index f641cacfff3..245766c31d6 100644 --- a/cabal-install/src/Distribution/Client/CmdHaddockProject.hs +++ b/cabal-install/src/Distribution/Client/CmdHaddockProject.hs @@ -19,7 +19,7 @@ import Distribution.Client.DistDirLayout ) import Distribution.Client.InstallPlan (foldPlanPackage) import qualified Distribution.Client.InstallPlan as InstallPlan -import Distribution.Client.NixStyleOptions (NixStyleFlags (NixStyleFlags, configFlags, haddockFlags)) +import Distribution.Client.NixStyleOptions (configFlags, haddockFlags) import qualified Distribution.Client.NixStyleOptions as NixStyleOptions import Distribution.Client.ProjectOrchestration ( AvailableTarget (..) diff --git a/cabal-install/src/Distribution/Client/CmdOutdated.hs b/cabal-install/src/Distribution/Client/CmdOutdated.hs index f7c385725bd..d113b676c2d 100644 --- a/cabal-install/src/Distribution/Client/CmdOutdated.hs +++ b/cabal-install/src/Distribution/Client/CmdOutdated.hs @@ -64,7 +64,6 @@ import Distribution.Compat.Directory import Distribution.Client.ProjectOrchestration import Control.Monad hiding (forM_, mapM, mapM_, sequence, sequence_) -import Data.Foldable (forM_, mapM_) import Distribution.Client.ScriptUtils import Distribution.Package import Distribution.ReadE diff --git a/cabal-install/src/Distribution/Client/FileMonitor.hs b/cabal-install/src/Distribution/Client/FileMonitor.hs index d692581db98..fefbd25835f 100644 --- a/cabal-install/src/Distribution/Client/FileMonitor.hs +++ b/cabal-install/src/Distribution/Client/FileMonitor.hs @@ -32,7 +32,6 @@ import qualified Data.ByteString.Lazy as BS import qualified Data.Map.Strict as Map import Control.Exception -import Control.Monad hiding (forM_, mapM, mapM_, sequence, sequence_) import Control.Monad.Except ( ExceptT , runExceptT @@ -42,7 +41,6 @@ import Control.Monad.Except import Control.Monad.State (StateT, mapStateT) import qualified Control.Monad.State as State import Control.Monad.Trans (MonadIO, liftIO) -import Data.Foldable (forM_, mapM_) import Distribution.Client.Glob import Distribution.Client.HashValue diff --git a/cabal-install/src/Distribution/Client/GlobalFlags.hs b/cabal-install/src/Distribution/Client/GlobalFlags.hs index ded5405327c..afbc4bf9403 100644 --- a/cabal-install/src/Distribution/Client/GlobalFlags.hs +++ b/cabal-install/src/Distribution/Client/GlobalFlags.hs @@ -62,7 +62,6 @@ import System.FilePath ( isAbsolute , () ) -import System.IO.Error (userError) #ifndef __MHS__ import qualified Distribution.Client.Security.DNS as Sec.DNS diff --git a/cabal-install/src/Distribution/Client/HashValue.hs b/cabal-install/src/Distribution/Client/HashValue.hs index dead5ee7b10..8ab14fdb79e 100644 --- a/cabal-install/src/Distribution/Client/HashValue.hs +++ b/cabal-install/src/Distribution/Client/HashValue.hs @@ -30,7 +30,9 @@ import qualified Crypto.Hash.SHA256 as SHA256 #endif import System.IO (IOMode (..), withBinaryFile) +#ifdef __MHS__ import System.IO.Unsafe (unsafePerformIO) +#endif #ifdef __MHS__ import Foreign.C.Types (CSize (..), CUChar (..)) diff --git a/cabal-install/src/Distribution/Client/IndexUtils.hs b/cabal-install/src/Distribution/Client/IndexUtils.hs index 295263ebd08..cfba20152a7 100644 --- a/cabal-install/src/Distribution/Client/IndexUtils.hs +++ b/cabal-install/src/Distribution/Client/IndexUtils.hs @@ -144,7 +144,7 @@ import Distribution.Client.Utils import Distribution.Compat.Internal.LazyByteString (hGetContentsLBS, readFileLBS) import Distribution.Compat.Time (getFileAge, getModTime) import Distribution.Utils.Generic (fstOf3) -import Distribution.Utils.Structured (Structured (..), nominalStructure, structuredDecodeFileOrFail, structuredEncodeFile) +import Distribution.Utils.Structured (nominalStructure, structuredDecodeFileOrFail, structuredEncodeFile) #ifdef __MHS__ import Distribution.Compat.Directory (doesDirectoryExist, doesFileExist, listDirectory) #else diff --git a/cabal-install/src/Distribution/Client/InstallPlan.hs b/cabal-install/src/Distribution/Client/InstallPlan.hs index 9db648bc18c..f26cac63c43 100644 --- a/cabal-install/src/Distribution/Client/InstallPlan.hs +++ b/cabal-install/src/Distribution/Client/InstallPlan.hs @@ -108,7 +108,7 @@ import Distribution.Solver.Types.Settings import Distribution.Solver.Types.SolverId import Distribution.Utils.LogProgress -import Distribution.Utils.Structured (Structure (Nominal), Structured (..)) +import Distribution.Utils.Structured (Structure (Nominal)) -- TODO: Need this when we compute final UnitIds -- import qualified Distribution.Simple.Configure as Configure diff --git a/cabal-install/src/Distribution/Client/ProjectBuilding/UnpackedPackage.hs b/cabal-install/src/Distribution/Client/ProjectBuilding/UnpackedPackage.hs index a63d8517d57..e1bab338756 100644 --- a/cabal-install/src/Distribution/Client/ProjectBuilding/UnpackedPackage.hs +++ b/cabal-install/src/Distribution/Client/ProjectBuilding/UnpackedPackage.hs @@ -121,8 +121,8 @@ import GHC.Clock (getMonotonicTime) #ifdef __MHS__ import System.CPUTime (getCPUTime) #endif -import Distribution.Compat.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, listDirectory) -import System.FilePath (dropDrive, normalise, takeDirectory, (<.>), ()) +import Distribution.Compat.Directory (canonicalizePath, createDirectoryIfMissing) +import System.FilePath (takeDirectory, (<.>), ()) import System.IO (Handle, IOMode (AppendMode), withFile) #ifdef __MHS__ type SemaphoreIdentifier = String diff --git a/cabal-install/src/Distribution/Client/ProjectConfig.hs b/cabal-install/src/Distribution/Client/ProjectConfig.hs index 9e6eb4be9da..9717848a32a 100644 --- a/cabal-install/src/Distribution/Client/ProjectConfig.hs +++ b/cabal-install/src/Distribution/Client/ProjectConfig.hs @@ -228,7 +228,6 @@ import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar #endif import qualified Distribution.Client.GZipUtils as GZipUtils -import qualified Distribution.Client.Tar as Tar import Control.Exception (handle) import Control.Monad.Trans (liftIO) diff --git a/cabal-install/src/Distribution/Client/ProjectPlanning.hs b/cabal-install/src/Distribution/Client/ProjectPlanning.hs index 31972d9ac8c..9576fbd0f29 100644 --- a/cabal-install/src/Distribution/Client/ProjectPlanning.hs +++ b/cabal-install/src/Distribution/Client/ProjectPlanning.hs @@ -173,7 +173,6 @@ import qualified Distribution.Client.InstallPlan as InstallPlan import qualified Distribution.Client.SolverInstallPlan as SolverInstallPlan import Distribution.CabalSpecVersion -import Distribution.Utils.LogProgress import Distribution.Utils.NubList import Distribution.Utils.Path hiding ( (<.>) @@ -246,7 +245,7 @@ import qualified Distribution.PackageDescription as PD import qualified Distribution.PackageDescription.Configuration as PD import qualified Distribution.Simple.Configure as Cabal import qualified Distribution.Simple.GHC as GHC -import Distribution.Simple.InstallDirs (InstallDirs (InstallDirs, datasubdir, libexecsubdir, libsubdir)) +import Distribution.Simple.InstallDirs (datasubdir, libexecsubdir, libsubdir) import qualified Distribution.Simple.InstallDirs as InstallDirs import qualified Distribution.Simple.LocalBuildInfo as Cabal import qualified Distribution.Simple.Setup as Cabal diff --git a/cabal-install/src/Distribution/Client/SetupWrapper.hs b/cabal-install/src/Distribution/Client/SetupWrapper.hs index aa476c9163b..0c5b04e00bd 100644 --- a/cabal-install/src/Distribution/Client/SetupWrapper.hs +++ b/cabal-install/src/Distribution/Client/SetupWrapper.hs @@ -851,6 +851,11 @@ externalSetupMethod path verbosity options _ args NotInLibrary = #endif +-- The external method is only selected for 'NotInLibrary'. 'InLibraryArgs' +-- is handled by 'runSetupMethod' before this runner is called. +externalSetupMethod _ _ _ _ _ (InLibraryArgs _) = + error "internal error: externalSetupMethod called for the in-library setup method" + useCachedSetupExecutable :: BuildType -> Bool useCachedSetupExecutable bt = bt == Simple || bt == Configure diff --git a/cabal-install/src/Distribution/Client/Utils.hs b/cabal-install/src/Distribution/Client/Utils.hs index 9d5b150f7bf..9e5333df597 100644 --- a/cabal-install/src/Distribution/Client/Utils.hs +++ b/cabal-install/src/Distribution/Client/Utils.hs @@ -86,7 +86,6 @@ import Distribution.Utils.Path ( CWD , Dir , File - , FileOrDir (..) , Pkg , RelativePath , SymbolicPath diff --git a/cabal-testsuite/src/Test/Cabal/Workdir.hs b/cabal-testsuite/src/Test/Cabal/Workdir.hs index a35bda70362..37300fd85bd 100644 --- a/cabal-testsuite/src/Test/Cabal/Workdir.hs +++ b/cabal-testsuite/src/Test/Cabal/Workdir.hs @@ -8,7 +8,6 @@ import Distribution.Simple.Setup import Distribution.Utils.Path ( Dir , Dist - , FileOrDir (..) , Pkg , SymbolicPath , getSymbolicPath diff --git a/cabal-validate/cabal-validate.cabal b/cabal-validate/cabal-validate.cabal index cba4dbe1a16..80cf211ce42 100644 --- a/cabal-validate/cabal-validate.cabal +++ b/cabal-validate/cabal-validate.cabal @@ -41,7 +41,6 @@ executable cabal-validate , bytestring >=0.11 && <1 , Cabal-syntax >=3.19 && <3.20 , containers >=0.6 && <1 - , directory >=1.0 && <2 , filepath >=1 && <2 , optparse-applicative >=0.18 && <1 , terminal-size >=0.3 && <1 diff --git a/solver-benchmarks/solver-benchmarks.cabal b/solver-benchmarks/solver-benchmarks.cabal index 3e5741aa51b..73d902a4e5b 100644 --- a/solver-benchmarks/solver-benchmarks.cabal +++ b/solver-benchmarks/solver-benchmarks.cabal @@ -33,10 +33,8 @@ library , containers , Cabal ^>= 3.19 , Cabal-syntax ^>= 3.19 - , directory , filepath , optparse-applicative - , process , time , statistics >= 0.14 && < 0.17 , vector From 49cce1add09358d161a67c792ef650fcc9b5b256 Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 21:21:54 +0900 Subject: [PATCH 11/17] Cabal: reuse store units and fix dynlib rpaths getStoreEntries listed the store root, so units under store/lib were never reused. --offline then refused a cached remote package that still looked configured. List the lib directories, and skip reuse when a dependency is still configured instead of asserting. Foreign libraries take their rpath from flibdir. Inplace v2-run also gets rpaths relative to the component build directory. Pin SetupHooks <.> to a Build file path so GHC 9.8+ accepts it, and update the GenericPackageDescription and LocalBuildInfo structure hashes. --- .../Distribution/Utils/Structured.hs | 4 +- .../src/Distribution/Simple/GHC/Build/Link.hs | 26 ++++++--- .../src/Distribution/Client/InstallPlan.hs | 22 ++++--- .../src/Distribution/Client/Store.hs | 58 +++++++++---------- .../UnitTests/Distribution/Client/Store.hs | 7 +-- .../SetupHooksC2HsRules/SetupHooks.hs | 13 ++++- 6 files changed, 77 insertions(+), 53 deletions(-) diff --git a/Cabal-tests/tests/UnitTests/Distribution/Utils/Structured.hs b/Cabal-tests/tests/UnitTests/Distribution/Utils/Structured.hs index 2b5d4b19667..800bb4ed28b 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/Utils/Structured.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/Utils/Structured.hs @@ -33,8 +33,8 @@ md5Check proxy md5Int = structureHash proxy @?= md5FromInteger md5Int md5CheckGenericPackageDescription :: Proxy GenericPackageDescription -> Assertion md5CheckGenericPackageDescription proxy = md5Check proxy - 0x007316e7fd40543810a54a4d35883343 + 0x81c5dcb63c46f4047bd56cf64f8f37f4 md5CheckLocalBuildInfo :: Proxy LocalBuildInfo -> Assertion md5CheckLocalBuildInfo proxy = md5Check proxy - 0x1707be2edbed103d734de60544097b67 + 0x80401bf783c8dec1ac932567bcc43aab diff --git a/Cabal/src/Distribution/Simple/GHC/Build/Link.hs b/Cabal/src/Distribution/Simple/GHC/Build/Link.hs index 1ffae0cf0cc..3fbc8994bfd 100644 --- a/Cabal/src/Distribution/Simple/GHC/Build/Link.hs +++ b/Cabal/src/Distribution/Simple/GHC/Build/Link.hs @@ -603,13 +603,17 @@ getRPaths pbci = do if supportRPaths hostOS then do libraryPaths <- liftIO $ depLibraryPaths False (relocatable lbi) lbi clbi + -- Inplace `v2-run` executes the artifact from the component build + -- directory. Install-relative rpaths only resolve after the file is + -- copied to 'ownDir', so also emit rpaths relative to the build dir. + inplacePaths <- liftIO $ depLibraryPaths True False lbi clbi let hostPref = case hostOS of OSX -> "@loader_path" _ -> "$ORIGIN" - -- The directory this artifact is installed to: a library goes to - -- the libdir, an executable to the bindir (the same split as - -- 'depLibraryPaths'). Absolute rpaths are re-expressed relative to - -- it below. + -- The directory this artifact is installed to. A foreign library + -- is copied to 'flibdir', not 'libdir'; using 'libdir' there bakes + -- @$ORIGIN/..@, which does not contain the Haskell dynlib once the + -- .so lives in 'flibdir'. installDirs = absoluteComponentInstallDirs (localPkgDescr lbi) @@ -618,7 +622,10 @@ getRPaths pbci = do NoCopyDest ownDir = case clbi of ExeComponentLocalBuildInfo{} -> bindir installDirs + FLibComponentLocalBuildInfo{} -> flibdir installDirs _ -> libdir installDirs + buildOwnDir = + interpretSymbolicPathLBI lbi (componentBuildDir lbi clbi) -- Every rpath entry is loader-relative: -- -- * a relative path gets the @$ORIGIN@ / @\@loader_path@ prefix, as @@ -636,9 +643,9 @@ getRPaths pbci = do -- dependencies live in sibling prefixes, and changes how -- @library-dirs@ are registered, neither of which rpath -- generation needs. - relPath p + relTo origin p | isRelative p = hostPref p - | otherwise = hostPref shortRelativePath ownDir p + | otherwise = hostPref shortRelativePath origin p rpaths = -- The artifact's own directory comes first, so a library -- installed next to it is found: 'depLibraryPaths' can yield the @@ -649,8 +656,13 @@ getRPaths pbci = do -- the missing self-rpath is fatal: a Backpack signature -- implementation installed next to the instantiated unit fails -- to load (GHC's testsuite T14304 on Alpine). + -- + -- Build-dir rpaths are dangling once the artifact is copied into + -- the store. They stay relative, so a missing directory is skipped + -- rather than aborting dyld the way an absolute rpath would. toNubListR [hostPref] - <> toNubListR (map relPath libraryPaths) + <> toNubListR (map (relTo ownDir) libraryPaths) + <> toNubListR (map (relTo buildOwnDir) inplacePaths) <> toNubListR (map getSymbolicPath $ extraLibDirs bi) return rpaths else return mempty diff --git a/cabal-install/src/Distribution/Client/InstallPlan.hs b/cabal-install/src/Distribution/Client/InstallPlan.hs index f26cac63c43..30ba1da75e4 100644 --- a/cabal-install/src/Distribution/Client/InstallPlan.hs +++ b/cabal-install/src/Distribution/Client/InstallPlan.hs @@ -433,8 +433,15 @@ remove shouldRemove plan = -- | Change a number of packages in the 'Configured' state to the 'Installed' -- state. -- --- To preserve invariants, the package must have all of its dependencies --- already installed too (that is 'PreExisting' or 'Installed'). +-- A package is installed only when every dependency is already installed +-- ('PreExisting' or 'Installed'). Dependencies are visited first, so a +-- dependency selected by @shouldBeInstalled@ is installed before the packages +-- that need it. A dependency that is still configured — a setup or build-tool +-- package that is not in its own store — blocks reuse of this package. The +-- package stays 'Configured' and is built. Skipping here, rather than +-- asserting, keeps the invariant that a completed package does not depend on +-- an unfinished one (see Note [Store reuse and cross-machine dependencies] +-- in "Distribution.Client.Store"). installed :: IsGraph k ipkg srcpkg => (srcpkg -> Bool) @@ -449,11 +456,12 @@ installed shouldBeInstalled installPlan = , shouldBeInstalled pkg ] where - markInstalled plan pkg = - assert (all isInstalled (directDeps plan (nodeKey pkg))) $ - plan - { planGraph = Graph.insert (Installed pkg) (planGraph plan) - } + markInstalled plan pkg + | all isInstalled (directDeps plan (nodeKey pkg)) = + plan + { planGraph = Graph.insert (Installed pkg) (planGraph plan) + } + | otherwise = plan -- | Lookup a package in the plan. lookup diff --git a/cabal-install/src/Distribution/Client/Store.hs b/cabal-install/src/Distribution/Client/Store.hs index a0c524e3f52..33ec9d887e8 100644 --- a/cabal-install/src/Distribution/Client/Store.hs +++ b/cabal-install/src/Distribution/Client/Store.hs @@ -21,6 +21,8 @@ module Distribution.Client.Store import Distribution.Client.Compat.Prelude import Prelude () +import Control.Monad.IO.Class (liftIO) + import Distribution.Client.DistDirLayout import Distribution.Client.RebuildMonad import Distribution.Client.Toolchain (Machine, Toolchain) @@ -122,40 +124,34 @@ doesStoreEntryExist StoreDirLayout{storePackageDirectory} machine toolchain unit -- store. getStoreEntries :: StoreDirLayout -> Machine -> Toolchain -> Rebuild (Set UnitId) getStoreEntries StoreDirLayout{storeDirectory} machine toolchain = do - paths <- getDirectoryContentsMonitored (storeDirectory machine toolchain) - return $! mkEntries paths - where - mkEntries = - Set.delete (mkUnitId "package.conf.d") - . Set.delete (mkUnitId "incoming") - . Set.fromList - . map mkUnitId - . filter valid - valid ('.' : _) = False - valid _ = True + -- Units live in @store/lib/@ (see 'storePackageInstallDirs''). + -- The store root only has @lib@, @bin@, @incoming@ and @package.conf.d@, + -- and @lib@ also holds the shared objects directly, so only directories + -- are unit ids. + let libDir = storeDirectory machine toolchain "lib" + names <- getDirectoryContentsMonitored libDir + dirs <- filterM (liftIO . doesDirectoryExist . (libDir )) names + return $! Set.fromList (map mkUnitId dirs) --- Note [Store reuse is disabled under this layout] --- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- 'getStoreEntries' above reads the store directory expecting a directory per --- unit. Since units moved into a shared @lib@ (see --- 'storePackageInstallDirs''), what it actually finds is @lib@, @bin@ and the --- incoming directory, so the set it returns never matches a real unit and --- 'improveInstallPlanWithUpToDatePackages' never marks anything up to date --- from the store. Every build therefore reinstalls what it already has. +-- Note [Store reuse and cross-machine dependencies] +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- 'getStoreEntries' lists @store/lib@. 'improveInstallPlanWithInstalledPackages' +-- then marks a configured package installed when its unit is in that set. -- --- This is deliberately left as it is, because fixing it is not enough on its --- own: reading @lib@, or reading the unit ids out of the package database, --- both make the improvement start firing, and it then trips --- @InstallPlan.installed@'s invariant ("the package must have all of its --- dependencies already installed too") during stage2 of a GHC build. The --- store is closed under library dependencies but not under /setup/ and --- build-tool dependencies, which belong to the build machine and live in a --- different store: the host store here holds 45 units and the build store 21, --- so a host package can be present while the build-machine dependency that --- 'directDeps' reports for it is not. +-- That improvement used to trip @InstallPlan.installed@ during a GHC stage2 +-- build. The store is closed under library dependencies, but not under setup +-- and build-tool dependencies: those belong to the build machine and live in +-- a different store (one GHC build had 45 units in the host store and 21 in +-- the build store). A host package can be present while the build-machine +-- dependency 'directDeps' reports is still configured. -- --- So the improvement needs to be made machine-aware before the enumeration is --- fixed, and the two have to land together. +-- 'InstallPlan.installed' therefore skips a package whose dependencies are +-- not all installed yet, instead of asserting. Dependencies are visited +-- first, so a dependency that is itself in its own store is installed before +-- the package that needs it. A dependency that is still configured blocks +-- reuse of this package, and the package is built again. That keeps the +-- plan's "completed packages do not depend on unfinished packages" invariant +-- without refusing to reuse the packages whose dependencies are present. -- | The outcome of 'newStoreEntry': either the store entry was newly created -- or it existed already. The latter case happens if there was a race between diff --git a/cabal-install/tests/UnitTests/Distribution/Client/Store.hs b/cabal-install/tests/UnitTests/Distribution/Client/Store.hs index 6981ce25747..29edc6e3a9a 100644 --- a/cabal-install/tests/UnitTests/Distribution/Client/Store.hs +++ b/cabal-install/tests/UnitTests/Distribution/Client/Store.hs @@ -185,7 +185,7 @@ assertNewStoreEntry copyFiles register expectedOutcome = do - entries <- runRebuild tmp $ getStoreEntries storeDirLayout Host tc + before <- runRebuild tmp $ getStoreEntries storeDirLayout Host tc outcome <- newStoreEntry verbosity @@ -197,8 +197,7 @@ assertNewStoreEntry register assertEqual "newStoreEntry outcome" expectedOutcome outcome assertStoreEntryExists storeDirLayout tc unitid True - let expected = Set.insert unitid entries - assertStoreContent tmp storeDirLayout tc expected + assertStoreContent tmp storeDirLayout tc (Set.insert unitid before) assertStoreEntryExists :: StoreDirLayout @@ -218,7 +217,7 @@ assertStoreContent -> Assertion assertStoreContent tmp storeDirLayout tc expected = do actual <- runRebuild tmp $ getStoreEntries storeDirLayout Host tc - assertEqual "store content" actual expected + assertEqual "store content" expected actual assertFileEqual :: FilePath -> String -> Assertion assertFileEqual path expected = do diff --git a/cabal-testsuite/PackageTests/SetupHooks/SetupHooksC2HsRules/SetupHooks.hs b/cabal-testsuite/PackageTests/SetupHooks/SetupHooksC2HsRules/SetupHooks.hs index 45559af69c9..55be04ffca4 100644 --- a/cabal-testsuite/PackageTests/SetupHooks/SetupHooksC2HsRules/SetupHooks.hs +++ b/cabal-testsuite/PackageTests/SetupHooks/SetupHooksC2HsRules/SetupHooks.hs @@ -71,17 +71,26 @@ preBuildRules (PreBuildComponentInputs { buildingWhat = what, localBuildInfo = l rewriteFileEx verbosity (getSymbolicPath $ hsDir modPath <.> "hs") $ unlines $ ("module " ++ modName modNm ++ " where\n") : (map ( ( "import " ++ ) . modName ) importModNms ++ srcLines) - rewriteFileEx verbosity (getSymbolicPath $ chiDir unsafeCoerceSymbolicPath modPath <.> "myChi") "" + -- 'unsafeCoerceSymbolicPath' leaves the path's endpoint polymorphic. + -- '<.>' only has a 'File' instance, so pin it or GHC 9.8+ reports + -- an ambiguous type variable (GHC-39999). + let chiPath :: SymbolicPathX OnlyRelative Build File + chiPath = unsafeCoerceSymbolicPath modPath <.> "myChi" + rewriteFileEx verbosity (getSymbolicPath $ chiDir chiPath) "" mkRule modNm = dynamicRule (static Dict) (mkCommand (static Dict) (static computeC2HsDepsAction) $ C2HsDepsInput { ruleIds = modToRuleId, ..}) (mkCommand (static Dict) (static runC2HsAction) $ C2HsInput {hsDir = autogenDir, chiDir = buildDir, ..}) [ FileDependency $ Location inDir (modPath <.> "myChs") ] - ( Location autogenDir (modPath <.> "hs" ) NE.:| [ Location buildDir (unsafeCoerceSymbolicPath modPath <.> "myChi") ] ) + ( Location autogenDir (modPath <.> "hs") NE.:| [ Location buildDir chiOut ] ) where modPath = moduleNameSymbolicPath modNm inDir = sameDirectory + -- Pin the file endpoint. '<.>' has no polymorphic instance, and + -- 'unsafeCoerceSymbolicPath' leaves it ambiguous (GHC-39999). + chiOut :: SymbolicPathX OnlyRelative Build File + chiOut = unsafeCoerceSymbolicPath modPath <.> "myChi" -- NB: in practice, we would get the module names by looking at the .cabal -- file and performing a search for `.chs` files on disk, but for this test From 2334eb8febf8d35843ca6a34712b17791f3bceaf Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 22:31:09 +0900 Subject: [PATCH 12/17] Cabal: keep inplace dirs off executable RPATH Baking the dist build directory into an executable RPATH lets runExe find an internal dynamic library that was never installed (Cabal #4025). v2-run puts those directories on the loader path of the child process instead: DYLD_LIBRARY_PATH on OSX, PATH on Windows, and LD_LIBRARY_PATH elsewhere. An existing loader path is kept. Skip the owner-execute round trip in the directory permissions test on Windows. System.Directory does not report that bit for a file that is not a program. --- .../Distribution/Compat/Directory.hs | 8 +- .../src/Distribution/Simple/GHC/Build/Link.hs | 14 +--- .../src/Distribution/Client/CmdRun.hs | 78 ++++++++++++++++++- 3 files changed, 85 insertions(+), 15 deletions(-) diff --git a/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs b/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs index a4dbd88eba9..2419ff64a97 100644 --- a/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs +++ b/Cabal-tests/tests/UnitTests/Distribution/Compat/Directory.hs @@ -3,6 +3,7 @@ module UnitTests.Distribution.Compat.Directory (tests) where import Control.Exception (IOException, try) import System.FilePath ((), isAbsolute) import System.IO.Error (isAlreadyExistsError) +import System.Info (os) import Distribution.Compat.Directory import Distribution.Simple.Utils (withTempDirectory) @@ -19,8 +20,13 @@ tests = , testCase "canonicalizePath resolves existing files" canonExistingTest , testCase "createDirectoryIfMissing rejects existing files" mkdirOnFileTest , testCase "createDirectoryIfMissing accepts existing directories" mkdirOnDirTest - , testCase "getPermissions gates searchable on directories" permsSearchableTest ] + -- 'System.Directory' on Windows does not round-trip the owner-execute + -- bit for a file that is not a program. The gating this checks is the + -- POSIX behaviour of 'directory'. + ++ [ testCase "getPermissions gates searchable on directories" permsSearchableTest + | os /= "mingw32" + ] removeFileTest :: Assertion removeFileTest = diff --git a/Cabal/src/Distribution/Simple/GHC/Build/Link.hs b/Cabal/src/Distribution/Simple/GHC/Build/Link.hs index 3fbc8994bfd..063d8d1ee98 100644 --- a/Cabal/src/Distribution/Simple/GHC/Build/Link.hs +++ b/Cabal/src/Distribution/Simple/GHC/Build/Link.hs @@ -603,10 +603,6 @@ getRPaths pbci = do if supportRPaths hostOS then do libraryPaths <- liftIO $ depLibraryPaths False (relocatable lbi) lbi clbi - -- Inplace `v2-run` executes the artifact from the component build - -- directory. Install-relative rpaths only resolve after the file is - -- copied to 'ownDir', so also emit rpaths relative to the build dir. - inplacePaths <- liftIO $ depLibraryPaths True False lbi clbi let hostPref = case hostOS of OSX -> "@loader_path" _ -> "$ORIGIN" @@ -624,8 +620,6 @@ getRPaths pbci = do ExeComponentLocalBuildInfo{} -> bindir installDirs FLibComponentLocalBuildInfo{} -> flibdir installDirs _ -> libdir installDirs - buildOwnDir = - interpretSymbolicPathLBI lbi (componentBuildDir lbi clbi) -- Every rpath entry is loader-relative: -- -- * a relative path gets the @$ORIGIN@ / @\@loader_path@ prefix, as @@ -657,12 +651,12 @@ getRPaths pbci = do -- implementation installed next to the instantiated unit fails -- to load (GHC's testsuite T14304 on Alpine). -- - -- Build-dir rpaths are dangling once the artifact is copied into - -- the store. They stay relative, so a missing directory is skipped - -- rather than aborting dyld the way an absolute rpath would. + -- Inplace build directories are intentionally absent. Baking the + -- dist dir into an executable RPATH lets 'runExe' find an internal + -- library that was never installed (Cabal #4025). 'v2-run' puts + -- those directories on the loader path instead. toNubListR [hostPref] <> toNubListR (map (relTo ownDir) libraryPaths) - <> toNubListR (map (relTo buildOwnDir) inplacePaths) <> toNubListR (map getSymbolicPath $ extraLibDirs bi) return rpaths else return mempty diff --git a/cabal-install/src/Distribution/Client/CmdRun.hs b/cabal-install/src/Distribution/Client/CmdRun.hs index 0869878388f..d159691c659 100644 --- a/cabal-install/src/Distribution/Client/CmdRun.hs +++ b/cabal-install/src/Distribution/Client/CmdRun.hs @@ -31,6 +31,9 @@ import Distribution.Client.CmdErrorMessages , targetSelectorFilter , targetSelectorPluralPkgs ) +import Distribution.Client.DistDirLayout + ( DistDirLayout (distBuildDirectory) + ) import Distribution.Client.Errors import Distribution.Client.GlobalFlags ( defaultGlobalFlags @@ -39,6 +42,7 @@ import Distribution.Client.InstallPlan ( foldPlanPackage , toList ) +import qualified Distribution.Client.InstallPlan as IP import Distribution.Client.NixStyleOptions ( NixStyleFlags (..) , cfgVerbosity @@ -54,12 +58,17 @@ import qualified Distribution.Client.ProjectOrchestration as Orchestration (targ import Distribution.Client.ProjectPlanning ( ElaboratedConfiguredPackage (..) , ElaboratedInstallPlan + , ElaboratedSharedConfig , binDirectoryFor ) import Distribution.Client.ProjectPlanning.Types ( ElaboratedPackageOrComponent (..) , dataDirsEnvironmentForPlan + , elabDistDirParams , elabExeDependencyPaths + , elabOrderLibDependencies + , elabPlatform + , isInplaceBuildStyle ) import Distribution.Client.ScriptUtils ( AcceptNoTargets (..) @@ -106,6 +115,10 @@ import Distribution.Simple.Utils , warn , wrapText ) +import Distribution.System + ( OS (..) + , Platform (..) + ) import Distribution.Types.ComponentName ( componentNameRaw @@ -134,11 +147,15 @@ import Distribution.Verbosity #ifdef __MHS__ import System.Environment ( getArgs + , lookupEnv ) #else import GHC.Environment ( getFullArgs ) +import System.Environment + ( lookupEnv + ) #endif import Distribution.Compat.Directory ( doesFileExist @@ -151,6 +168,7 @@ getFullArgs = getArgs import System.FilePath ( isPathSeparator , isValid + , searchPathSeparator , () ) @@ -352,6 +370,35 @@ runAction flags targetAndArgs globalFlags = do logExtraProgramSearchPath verbosity extraPath progPath <- programSearchPathAsPATHVar (map ProgramSearchPathDir extraPath ++ defaultProgramSearchPath) + -- Inplace dynamic libraries are not on the executable RPATH (Cabal + -- #4025). Put their build directories on the loader path for this run. + -- Windows loads DLLs from PATH. Keep any path the caller already set. + dyld0 <- lookupEnv "DYLD_LIBRARY_PATH" + ld0 <- lookupEnv "LD_LIBRARY_PATH" + let Platform _ os = elabPlatform (elaboratedShared buildCtx) pkg + libDirs = inplaceRunLibDirs (distDirLayout baseCtx) (elaboratedShared buildCtx) elaboratedPlan pkg + libPath = intercalate [searchPathSeparator] libDirs + keepOld Nothing p = p + keepOld (Just old) p + | null old = p + | otherwise = p ++ searchPathSeparator : old + progPath' = + case os of + Windows + | not (null libDirs) -> + libPath ++ searchPathSeparator : progPath + _ -> progPath + loaderEnv = + case os of + OSX + | not (null libDirs) -> + [("DYLD_LIBRARY_PATH", Just (keepOld dyld0 libPath))] + Windows -> [] + _ + | not (null libDirs) -> + [("LD_LIBRARY_PATH", Just (keepOld ld0 libPath))] + _ -> [] + if dryRun then notice verbosity "Running of executable suppressed by flag(s)" else @@ -361,12 +408,35 @@ runAction flags targetAndArgs globalFlags = do { progInvokePath = exePath , progInvokeArgs = args , progInvokeEnv = - ("PATH", Just progPath) - : dataDirsEnvironmentForPlan - (distDirLayout baseCtx) - elaboratedPlan + ("PATH", Just progPath') + : loaderEnv + ++ dataDirsEnvironmentForPlan + (distDirLayout baseCtx) + elaboratedPlan } +-- | Build directories of inplace library dependencies. 'v2-run' executes the +-- artifact from the component build directory, and those libraries are not +-- on its RPATH. +inplaceRunLibDirs + :: DistDirLayout + -> ElaboratedSharedConfig + -> ElaboratedInstallPlan + -> ElaboratedConfiguredPackage + -> [FilePath] +inplaceRunLibDirs layout shared plan pkg = + sortNub + [ distBuildDirectory layout (elabDistDirParams shared dep) "build" + | key <- elabOrderLibDependencies pkg + , Just depPkg <- [IP.lookup plan key] + , Just dep <- [planSource depPkg] + , isInplaceBuildStyle (elabBuildStyle dep) + ] + where + planSource (IP.Configured elab) = Just elab + planSource (IP.Installed elab) = Just elab + planSource _ = Nothing + -- | Split @cabal run@ arguments (@exe cmd@ arguments in the examples) into -- target selectors and target executable arguments. -- From 8bec903b83b0ef2332e73f86d176a44f9466190a Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 22:33:44 +0900 Subject: [PATCH 13/17] Cabal: format the v2-run loader-path expression fourmolu 0.12 aligns the (++) with the (:) in progInvokeEnv. --- cabal-install/src/Distribution/Client/CmdRun.hs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cabal-install/src/Distribution/Client/CmdRun.hs b/cabal-install/src/Distribution/Client/CmdRun.hs index d159691c659..7b70261a4de 100644 --- a/cabal-install/src/Distribution/Client/CmdRun.hs +++ b/cabal-install/src/Distribution/Client/CmdRun.hs @@ -410,9 +410,9 @@ runAction flags targetAndArgs globalFlags = do , progInvokeEnv = ("PATH", Just progPath') : loaderEnv - ++ dataDirsEnvironmentForPlan - (distDirLayout baseCtx) - elaboratedPlan + ++ dataDirsEnvironmentForPlan + (distDirLayout baseCtx) + elaboratedPlan } -- | Build directories of inplace library dependencies. 'v2-run' executes the From 681589ff93ee4413806c702f497b9c910b547f51 Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Wed, 25 Nov 2026 23:29:45 +0900 Subject: [PATCH 14/17] Cabal: put external dynlib dirs on the v2-run loader path v2-run executes the binary from its component build directory. The install-relative $ORIGIN rpath to GHC's libHSbase does not resolve from there, and the loader path only listed inplace build directories. CmmSourcesDyn then failed to load libHSbase on Linux. Pre-existing packages contribute libraryDynDirs, or libraryDirs when that list is empty. Non-inplace elaborated packages contribute dynlibdir and libdir. Inplace build directories stay off the executable RPATH. --- .../src/Distribution/Client/CmdRun.hs | 55 ++++++++++++++----- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/cabal-install/src/Distribution/Client/CmdRun.hs b/cabal-install/src/Distribution/Client/CmdRun.hs index 7b70261a4de..aa9acc3e43a 100644 --- a/cabal-install/src/Distribution/Client/CmdRun.hs +++ b/cabal-install/src/Distribution/Client/CmdRun.hs @@ -61,6 +61,9 @@ import Distribution.Client.ProjectPlanning , ElaboratedSharedConfig , binDirectoryFor ) +import Distribution.Client.ProjectPlanning.Machine + ( withoutMachine + ) import Distribution.Client.ProjectPlanning.Types ( ElaboratedPackageOrComponent (..) , dataDirsEnvironmentForPlan @@ -89,6 +92,7 @@ import Distribution.Client.Utils , occursOnlyOrBefore ) +import qualified Distribution.InstalledPackageInfo as IPI import Distribution.Simple.BuildToolDepends ( getAllInternalToolDependencies ) @@ -96,6 +100,7 @@ import Distribution.Simple.Command ( CommandUI (..) , usageAlternatives ) +import qualified Distribution.Simple.InstallDirs as InstallDirs import Distribution.Simple.Program.Find ( ProgramSearchPathEntry (ProgramSearchPathDir) , defaultProgramSearchPath @@ -371,12 +376,15 @@ runAction flags targetAndArgs globalFlags = do progPath <- programSearchPathAsPATHVar (map ProgramSearchPathDir extraPath ++ defaultProgramSearchPath) -- Inplace dynamic libraries are not on the executable RPATH (Cabal - -- #4025). Put their build directories on the loader path for this run. - -- Windows loads DLLs from PATH. Keep any path the caller already set. + -- #4025). The install-relative $ORIGIN rpath of an external library + -- (GHC's base, for example) is computed against the install bindir, so + -- it does not resolve from the build directory where v2-run executes + -- the binary. Put both sets of directories on the loader path for this + -- run. Windows loads DLLs from PATH. Keep any path the caller already set. dyld0 <- lookupEnv "DYLD_LIBRARY_PATH" ld0 <- lookupEnv "LD_LIBRARY_PATH" let Platform _ os = elabPlatform (elaboratedShared buildCtx) pkg - libDirs = inplaceRunLibDirs (distDirLayout baseCtx) (elaboratedShared buildCtx) elaboratedPlan pkg + libDirs = runLibDirs (distDirLayout baseCtx) (elaboratedShared buildCtx) elaboratedPlan pkg libPath = intercalate [searchPathSeparator] libDirs keepOld Nothing p = p keepOld (Just old) p @@ -415,27 +423,46 @@ runAction flags targetAndArgs globalFlags = do elaboratedPlan } --- | Build directories of inplace library dependencies. 'v2-run' executes the --- artifact from the component build directory, and those libraries are not --- on its RPATH. -inplaceRunLibDirs +-- | Directories the dynamic loader searches when 'v2-run' executes an +-- artifact from its component build directory. +-- +-- Inplace libraries are intentionally absent from the executable RPATH +-- (Cabal #4025). Pre-existing libraries such as GHC's base are recorded +-- with an install-relative rpath, which does not resolve from that build +-- directory, so their dynamic-library directories are included here too. +runLibDirs :: DistDirLayout -> ElaboratedSharedConfig -> ElaboratedInstallPlan -> ElaboratedConfiguredPackage -> [FilePath] -inplaceRunLibDirs layout shared plan pkg = +runLibDirs layout shared plan pkg = sortNub - [ distBuildDirectory layout (elabDistDirParams shared dep) "build" + [ dir | key <- elabOrderLibDependencies pkg , Just depPkg <- [IP.lookup plan key] - , Just dep <- [planSource depPkg] - , isInplaceBuildStyle (elabBuildStyle dep) + , dir <- depDirs depPkg ] where - planSource (IP.Configured elab) = Just elab - planSource (IP.Installed elab) = Just elab - planSource _ = Nothing + depDirs (IP.PreExisting ipkg) = + case IPI.libraryDynDirs (withoutMachine ipkg) of + [] -> IPI.libraryDirs (withoutMachine ipkg) + dirs -> dirs + depDirs (IP.Configured elab) = elabDirs elab + depDirs (IP.Installed elab) = elabDirs elab + + elabDirs elab + | isInplaceBuildStyle (elabBuildStyle elab) = + [ distBuildDirectory layout (elabDistDirParams shared elab) + "build" + ] + | otherwise = + let dirs = elabInstallDirs elab + in filter + (not . null) + [ InstallDirs.dynlibdir dirs + , InstallDirs.libdir dirs + ] -- | Split @cabal run@ arguments (@exe cmd@ arguments in the examples) into -- target selectors and target executable arguments. From 89a80e86367e9d4cf049702fed8bd320ad2893c9 Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Thu, 26 Nov 2026 00:55:21 +0900 Subject: [PATCH 15/17] Cabal: import the InstallDirs constructor for MicroHs MicroHs bootstrap failed in ProjectPlanning with "undefined value: InstallDirs" at the data constructor. The last green MicroHs bootstrap imported that constructor. Keeping only the field selectors makes MicroHs reject the qualified record pattern. The pattern uses the constructor directly, so GHC still treats the import as used. --- cabal-install/src/Distribution/Client/ProjectPlanning.hs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cabal-install/src/Distribution/Client/ProjectPlanning.hs b/cabal-install/src/Distribution/Client/ProjectPlanning.hs index 9576fbd0f29..2487954e305 100644 --- a/cabal-install/src/Distribution/Client/ProjectPlanning.hs +++ b/cabal-install/src/Distribution/Client/ProjectPlanning.hs @@ -245,7 +245,9 @@ import qualified Distribution.PackageDescription as PD import qualified Distribution.PackageDescription.Configuration as PD import qualified Distribution.Simple.Configure as Cabal import qualified Distribution.Simple.GHC as GHC -import Distribution.Simple.InstallDirs (datasubdir, libexecsubdir, libsubdir) +import Distribution.Simple.InstallDirs + ( InstallDirs (InstallDirs, datasubdir, libexecsubdir, libsubdir) + ) import qualified Distribution.Simple.InstallDirs as InstallDirs import qualified Distribution.Simple.LocalBuildInfo as Cabal import qualified Distribution.Simple.Setup as Cabal @@ -4767,7 +4769,7 @@ storePackageInstallDirs' machine toolchain unitid = - InstallDirs.InstallDirs{..} + InstallDirs{..} where -- Everything a machine installs is rooted at that machine's store -- directory, not at a directory of its own: one @lib@ holding a From 3522bcc72a9de6e8e7490b6d38914de098948fee Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Thu, 26 Nov 2026 02:36:32 +0900 Subject: [PATCH 16/17] Cabal: look up store units by package name findDependencyInStore stripped vowels on macOS to imitate hashedInstalledPackageIdVeryShort. That id was removed, and macOS store directories use the long id, which starts with the package name. CopyHie, HaddockBuildDepends, and quickjump searched for h-dpndncy, x, and ndf and missed hie-dependency, exe/lib, and indef. --- cabal-testsuite/src/Test/Cabal/Prelude.hs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/cabal-testsuite/src/Test/Cabal/Prelude.hs b/cabal-testsuite/src/Test/Cabal/Prelude.hs index b72c4e3a903..026a5f37b2b 100644 --- a/cabal-testsuite/src/Test/Cabal/Prelude.hs +++ b/cabal-testsuite/src/Test/Cabal/Prelude.hs @@ -1458,15 +1458,10 @@ findDependencyInStore pkgName = do -- name ("lib" matches "libHSlib-...so"), so only directories can match. packageDirs <- filterM (doesDirectoryExist . (storeLibDir )) =<< listDirectory storeLibDir - -- Ideally, we should call 'hashedInstalledPackageId' from 'Distribution.Client.PackageHash'. - -- But 'PackageHashInputs', especially 'PackageHashConfigInputs', is too hard to construct. - let pkgName' = - if buildOS == OSX - then filter (not . flip elem "aeiou") pkgName - else -- simulates the way 'hashedInstalledPackageId' uses to compress package name - pkgName - let libDir = case filter (pkgName' `isPrefixOf`) packageDirs of - [] -> error $ "Could not find " <> pkgName' <> " when searching for " <> pkgName' <> " in\n" <> show packageDirs + -- Long unit ids start with the package name, version, and hash. + -- macOS no longer strips vowels from that name, so the name is the prefix. + let libDir = case filter (pkgName `isPrefixOf`) packageDirs of + [] -> error $ "Could not find " <> pkgName <> " when searching for " <> pkgName <> " in\n" <> show packageDirs (dir : _) -> dir pure (storeLibDir libDir) From 99bb532a11afd68a3afb701474958e35930e1f36 Mon Sep 17 00:00:00 2001 From: Moritz Angermann Date: Thu, 26 Nov 2026 03:09:05 +0900 Subject: [PATCH 17/17] Cabal: import the NixStyleFlags constructor for MicroHs MicroHs bootstrap failed while compiling Main with "undefined value: NixStyleFlags" at the data constructor. CmdHaddockProject updates a NixStyleFlags record, and MicroHs needs that constructor imported. 5ddda20f7 dropped it as unused for GHC. The pattern names the constructor, so the import stays used. --- .../Distribution/Client/CmdHaddockProject.hs | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/cabal-install/src/Distribution/Client/CmdHaddockProject.hs b/cabal-install/src/Distribution/Client/CmdHaddockProject.hs index 245766c31d6..3ad8e026269 100644 --- a/cabal-install/src/Distribution/Client/CmdHaddockProject.hs +++ b/cabal-install/src/Distribution/Client/CmdHaddockProject.hs @@ -19,7 +19,9 @@ import Distribution.Client.DistDirLayout ) import Distribution.Client.InstallPlan (foldPlanPackage) import qualified Distribution.Client.InstallPlan as InstallPlan -import Distribution.Client.NixStyleOptions (configFlags, haddockFlags) +import Distribution.Client.NixStyleOptions + ( NixStyleFlags (NixStyleFlags, configFlags, haddockFlags) + ) import qualified Distribution.Client.NixStyleOptions as NixStyleOptions import Distribution.Client.ProjectOrchestration ( AvailableTarget (..) @@ -417,13 +419,15 @@ haddockProjectAction flags _extraArgs globalFlags = do } nixFlags = - (commandDefaultFlags CmdHaddock.haddockCommand) - { haddockFlags = haddockFlags' - , configFlags = - (NixStyleOptions.configFlags (commandDefaultFlags CmdBuild.buildCommand)) - { configCommonFlags = commonFlags - } - } + case commandDefaultFlags CmdHaddock.haddockCommand of + baseFlags@NixStyleFlags{} -> + baseFlags + { haddockFlags = haddockFlags' + , configFlags = + (NixStyleOptions.configFlags (commandDefaultFlags CmdBuild.buildCommand)) + { configCommonFlags = commonFlags + } + } -- Build a self contained directory which contains haddocks of all -- transitive dependencies; or depend on `--haddocks-html-location` to